Search code examples
scalacoding-styleconventionsparenthesesreadability

Should a Scala DAO get / select method with no arguments (arity-0) have parentheses?


According to the Scala guide, methods of arity-0 (no arguments) can and should have their parentheses omitted if:

the method in question has no side-effects (purely-functional)

That's quite an ambiguous statement to make, isn't it?

I'm trying to figure out whether a DAO with a getter/select arity-0 method should have parentheses or not.

On one hand it should, because accessing a database might be a costly action with "performance side effects" on the application.

On the other hand it shouldn't, because the DAO trait is unaware of the implementation, and by definition, it's simply a getter method that doesn't alter the state of the application.

What say you?


Solution

  • Scala 0 arity methods without parentheses are essentially properties.

    Look at what Microsoft has to say about properties. Substitute "zero-arity method without parentheses" for "property" in the statements below, and it still works, for the most part:

    Consider using a property if the member represents a logical attribute of the type.

    For example, BorderStyle is a property because the style of the border is an attribute of a ListView.

    Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.

        public int Department
        {
            get { return department; } 
            set { department = value; }
        }
    

    Do use a method, rather than a property, in the following situations.

    • The operation is orders of magnitude slower than a field set would be. If you are even considering providing an asynchronous version of an operation to avoid blocking the thread, it is very likely that the operation is too expensive to be a property. In particular, operations that access the network or the file system (other than once for initialization) should most likely be methods, not properties.

    • The operation is a conversion, such as the Object.ToString method.

    • The operation returns a different result each time it is called, even if the parameters do not change. For example, the NewGuid method returns a different value each time it is called.
    • The operation has a significant and observable side effect. Note that populating an internal cache is not generally considered an observable side effect.
    • The operation returns a copy of an internal state (this does not include copies of value type objects returned on the stack).
    • The operation returns an array.

    As you can see, a property is the simple case of returning a value from an object. A method is essentially everything else.