开发者

Named parameters lead to maintenance problems and inferior readability?

With named parameters like

def f(x : Int = 1, y : Int = 2) = x * y

your parameter names become part of the interface

f(x=3)

Now if you want to change the parameter names locally, you are forced to perserve the public name of the parameter:

    def f(x : Int = 1, y : Int = 2) = {
        val (a,b) = (x,y)
        a *开发者_如何学JAVA b
    }

If this a real problem? Is there a syntax to support this directly? Who do other languages handle this?

A small illustration of the problems you can run into if you switch parameter names, as suggested by Jon.

trait X{ def f(x : Int, y : Int) }
class A extends X{
    override def f(y : Int, x : Int) = println("" + y + x) 
}
val a = new A
scala> a.f(x = 1, y = 2)
21
scala> (a : X).f(x = 1, y = 2)
12


Yes, the parameter name is effectively part of the public interface. This is a "problem" for any language which has named arguments - or indeed produces code which is consumed by languages supporting named arguments. Sometimes this isn't well understood.

For example, C# 3 doesn't support named arguments - but VB does. So if you create a library in C# 3, someone builds against it in VB, then changing parameter names counts as a breaking change.

Ultimately some of this will be handled by refactoring tools, but it boils down to the same sort of caution as with any other aspect of a public API... you need to be very cautious.

You should also be very cautious when overriding a method with parameters - use the same parameter names as the original method, or you could cause some very subtle issues. (In particular, switching round the names of parameters would be very evil...)


I don't know about the "inferior readability" part of your title. The few times I used named parameters, it was to provide default values like increment:Int = 100000, maxCount:Int = 1000000. I think it helps readability when you have to changed on value where you call the function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜