tags:

views:

155

answers:

2

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 * 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
+11  A: 

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...)

Jon Skeet
Good point, wasn't even thinking in terms of public vs non-public API.
R0MANARMY
I've added some sample code for the name switching problem you suggested.
Thomas Jung
+1  A: 

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.

huynhjl
The point is that you cannot change the parameter name in a public interface. This leads to a worse readability in the method as you end up with a misleading parameter name or a alias definition.
Thomas Jung
You cannot change the method name, either, without a full refactoring of all client code.
Randall Schulz
@Randall - But unless you're calling recursively you won't refer to the method name in the implementation. The parameter names are used in the method and have a higher impact on readability.
Thomas Jung