Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named parameters lead to maintenance problems and inferior readability?

Tags:

scala

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
like image 489
Thomas Jung Avatar asked May 18 '10 12:05

Thomas Jung


2 Answers

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

like image 117
Jon Skeet Avatar answered Nov 25 '22 19:11

Jon Skeet


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.

like image 39
huynhjl Avatar answered Nov 25 '22 18:11

huynhjl