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.
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.
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.
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.
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.
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.
- 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
Intin the place of a
- 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.