ScalaKnol: Understanding Uniform Access Principle


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

case class Employee (name: String){
  val salary:Int = 100
  }

and we have the calling code like this

object Bonus {
    def calculateBonus(employee: Employee) = {
      employee.salary match {
        case x if (x <= 100) => println("10% bonus")
        case _ => println("5% bonus")
      }
    }
  }
  
  val junior = new Employee("Vikas")              //> junior  : CompositionInheritance.Employee = Employee(Vikas)
  val senior = new Employee("Ayush")              //> senior  : CompositionInheritance.Employee = Employee(Ayush)
  
  Bonus.calculateBonus(junior)                    //> 10% bonus
  Bonus.calculateBonus(senior)                    //> 10% bonus

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

 case class Employee(name: String) {
    def salary: Int = if (name.startsWith("V")) 200 else 100
  }

  object Bonus {
    def calculateBonus(employee: Employee) = {
      employee.salary match {
        case x if (x <= 100) => println("10% bonus")
        case _ => println("5% bonus")
      }
    }
  }

  val junior = new Employee("Vikas")              //> junior  : CompositionInheritance.Employee = Employee(Vikas)
  val senior = new Employee("Ayush")              //> senior  : CompositionInheritance.Employee = Employee(Ayush)

  Bonus.calculateBonus(junior)                    //> 5% bonus
  Bonus.calculateBonus(senior)                    //> 10% bonus

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.

About these ads

About Vikas Hazrati

Vikas is the CTO @ Knoldus which is a group of software industry veterans who have joined hands to add value to the art of software development. We do niche product and project development on Scala and Java. We consult and coach on effective software development and agile practices. With our focus on software craftsmanship you can be assured of a good quality at the right price. To know more, send a mail to info@knoldus.com or visit www.knoldus.com
This entry was posted in Scala and tagged , , . Bookmark the permalink.

3 Responses to ScalaKnol: Understanding Uniform Access Principle

  1. 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

  2. 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 ;).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s