Scala Tutorials Part #14 - Uniform Access Principle in Scala
Originally Posted On : 10 Apr 2017
Uniform Access Principle
This is part 14 of the scala tutorial series. Check here for the full series.
Index
Introduction
The Uniform access principle is a programming concept that goes simply as
All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation.
It was put forth by Bertrand Meyer in his book called Object oriented software construction. This is not necessarily a functional programming concept, for instance you would not find this abundantly present in haskell as this is more oriented towards OOP rather than FP.
Implementation in scala
We already saw in the scala classes article that the getters and setters can be used in the same way. Accessing methods and variables is the same in scala.
val array : Array[Int] = Array(10,30,44)
val someString = "Testing"
println(array.length)
println(someString.length)
The same example in java leads to an error.
In java accessing the length of an array is different from accessing the length of a string.
We cannot access both in the same way because the array length is a variable and the String.length()
is actually a method inside the String class.
Another example in scala.
class Runnable {
val string = "Scala 2.12 is out"
def anotherString = "Scala 2.12 is out"
}
object Runnable extends App {
val instance = new Runnable
println(instance.string)
println(instance.anotherString)
}
Namespace Collision
There is a possibility of name space collision due to the nature of how the uniform access principle works. For instance, the below example would work in java.
public class Test {
int example = 10;
public int example() {
return 10;
}
}
Something similar in scala would end up in a compilation error.
The error checking is necessary since it would lead to ambiguity at the language level and the compiler throws an error to prevent it.
Summing it up
- Less confusion, access array length and string length in the same way.
- The client side code can consume it and the handler code logic can be changed without fear of breaking the client code unless
it breaks the contract i.e return
Int
in the place of aString
- Refactoring and unit testing is much easier because of this.
- Leads to better design patterns and libraries. In fact the collection API in scala benefits a lot from this.