So, I have this idea for a long time and want to share it with you. What if Scala somewhere in the future will always require use of named arguments, unless passed variables have matching names with the names of arguments? Let me show you the example:
def foo(processId: Int, title: String, isHighPriority: Boolean) = ???
And we have the following variables:
val processId = 1
val anotherProcessId = 2
val title = "main"
val isHighPriority = true
In that cases compiler will accept the follwing
foo(processId, title, isHighPriority) // obviously
foo(isHighPriority, processId, title) // still ok, because compiler doesn't care about order, he matches the names
foo(isHighPriority = false, title, processId = 1) // as a result, we can freely mix and use named and not named variables in any order
And here are some restrictions:
foo(processId = anotherProcessId, title, isHighPriority) // even thou we are passing variables in the right order, one of them has different name than its argument
foo(processId, title: "main", isHighPriority) // we are passing the value directly, so we need to explicitly tell the name of the argument
foo(processId, title, isHighPriority = !isHighPriority) // name of the last variable matches, but we are not passing it, but rather result of operations on that variable, so we need to name it
What are the benefits? I can name a few:
- Better readability. Without checking the definition of the function, we can tell from code what is being passed and to what arguments.
- More freedom. The definition and usage are almost completely decoupled.
- Safety. Just imagine that someone decided to move around arguments.
def foo(childId: Int, parentId: Int) // old definition
def foo(parentId: Int, childId: Int) // new definition
...
// Finding this bug in the code can me a nightmare:
foo(childId, parentId) // somewhere the function is being called the 'old way'
- If you think that this is not going to happen with responsible programmers, proper code review, and etc, then unfortunately you are too naive. This happens more often than it should be in the sane world. Especially when the library or code is not mature enough and still evolving.
- We will softly push programmers to write cleaner code and make more meaningful names for arguments. Like soft opionated view on how to write clean code.
So, what do you think?