What is Uniform Access Principle?

Table of contents
Reading Time: 2 minutes

Uniform Access Principle is a programming concept which was first introduced by Bertrand Meyer which stated that

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.

The principle simply means that the notation used to access a feature of a class shouldn’t differ depending on whether it’s an attribute or a method.

For example, if you have an object Person and you want to find it’s age, you should use the same notation whether the age is stored field or a computed value. The client should not know or care whether the age is calculated or stored. This gives the Person object flexibility to change between the two which is an unnecessary concern from the client side.

Implementation of UAP(Uniform Access Principle) in Scala

Scala supports this principle by allowing parentheses to not be placed at call sites of parameterless functions. As a result, a parameterless function definition can be changed to a val, or vice versa, without affecting client code. Accessing methods and variables is the same in scala.

For example,

In above example, the methods and variables of class Runnable can be altered without affecting the client code which is calling it. The notation to access is same for both.

But Java does not support this principle, as 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.

Scala suffers from a namespace collision problem because of how the principle works.

For example, the following code would lead to a compilation error in Scala while it would work fine in Java.

Therefore, compiler checks for error as there can be ambiguity at the language level.

This principle provides a few advantages to Scala developers or the language itself:

  • Leads to better design patterns.
  • Client-side remains unaffected and the code logic can be altered easily.
  • Refactoring of code becomes easier.
  • Scala Collections API benefits from this principle.
  • It leads to less confusion as in case of array.length or string.length, both are accessed in the same way.
  • Writing unit tests becomes easier.

Hope you find this blog interesting, Thanks for reading.

knoldus-advt-sticker

Written by 

Vidisha Gupta is a software consultant having more than 0.5 years of experience. She likes to keep up with the trending technologies. She is familiar with languages such as C, C++, Java, Scala and is currently working on reactive technologies like spark, Lagom, Kafka, Cassandra. Her hobbies includes exploring new things, watching web series and listening music.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading