没有参数 (arity-0) 的 Scala DAO get / select 方法应该有括号吗?

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

根据 Scala guide,arity-0 的方法(无参数)可以而且应该省略括号,如果:

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

这是一个非常模棱两可的声明,不是吗?

我想弄清楚带有 getter/select arity-0 方法的 DAO 是否应该有括号。

一方面应该如此,因为在应用程序上 "performance side effects" 访问数据库可能是一项代价高昂的操作。

另一方面,它不应该,因为 DAO 特征不知道实现,根据定义,它只是一个 getter 方法,不会改变应用程序的状态。

你怎么说?

我也会应用 referential transparency 作为指导。非引用透明的方法值得 () 让用户知道。

例如

def randomInt(): Int

对比

case class Rectangle(width: Int, height: Int) { def area: Int = width * height }

(是的,在这种情况下 area 可能是 vallazy val 但这不是重点)

在你的例子中,从数据源获取数据不是引用透明的,所以我会选择 ()

没有括号的Scala 0 arity方法本质上是properties.

看看what Microsoft has to say about properties。在下面的语句中用 "zero-arity method without parentheses" 替换 "property" ,它仍然有效,在大多数情况下:

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.

如您所见,属性 是从对象返回值的简单情况。方法本质上是 其他一切。