The ScalaKnol series attempts to share a nugget of Scala wisdom every few days or sometimes few times a day. Keep tuned. Today we would look at the Uniform Access Principle.
The principle states that the client code or the calling code should not be affected by the decision to implement an attribute as a field or a method. Hence essentially irrespective of whether the attribute is defined with a val or a def, the calling client should be agnostic of the same.
For example, if we have a class like
and we have the calling code like this
As always, you can see the output because we are coding in worksheet. Now suppose we have a change which results in the val salary now actually becoming a method. In this case let us assume that people whose name starts with a V get a higher salary. (Ok, I am biased, don’t curse your parents yet, because the bonus percentage goes down 😉
So, the new way to define our class then becomes something like this, and you would notice the change in the
If you notice, we did not change the client / calling code even though we changed the attribute from val to def. This is the Uniform Access Principle which Scala supports. Java on the other hand does not support this principle. If you recall, in Java we have array.length. Now string is also an array but for String we have to write string.length() because it is a method and not a field.
3 thoughts on “ScalaKnol: Understanding Uniform Access Principle2 min read”
Also, both method(def) and field(val) exist in the same namespace in Scala unlike Java where we can have a field and a method by the same name together
Great article, but please add “M” to the higher paying initials ;)! I think it’s fair to give a tip of the hat to Bertrand Meyer here, who already advocated for the UAP in his book (Object Oriented Software Construction) in the 80ies. This topic, and Meyer’s treatment of Abstract Data Types are really worth a read.
There are some less defensible positions in Meyer’s book as well, e.g. arguing for mutating setters (which weakens the UAP — what if an “assignment” fails?), and for covariant _parameter_ types in overridden methods (the first edition was released before Barbara Liskov’s eponymous principle), but I think that makes for an even more interesting read ;).
Thanks for the note and the references, Michael. Full credit to Bertand Meyer and the , M would be added to higher paid ones in the next release 😉
Comments are closed.