Friday, January 3, 2014

Scala Design Tips

In this section, I would like to share some useful tips for Java developers,

Tip 1 - Trait, or not to Trait

What is a Trait? - Trait contains set of methods (not functions) and each method defines a behavior of an object. Mix-in this trait into a class gives that class a new set of behavior.
RULE 1
If the behavior will not be reused, then make it a concrete class. It is not a reusable behavior after all.
RULE 1 Example,
class Account {
def withdraw(...) = {}
def deposit(...) = {}
}
trait AccountManager {
def withdraw(accountId: Long, amount: Int) = {. . } // this behavior doesn't seems like re-usable by other classes except by the Account 
class
def desposit(accountId: Long, amount: Int) {.. } // this behavior doesn't seems like re-usable by other classes except by the Account  class
}
RULE 2
If a set of behavior makes a class definition lengthy, to increase the readability define a trait with self reference to that superclass. The self reference will ensure that any trait or class 'mixin' this trait must have self reference to super class.

RULE
2 Example,
trait EmployeeManagement {
self: Employee =>
def add: Employee = {...}
def remove: Employee = {...}
}
class Employee extends EmployeeManagment {
val name = ""
val address =""
}
RULE 3
If efficiency is very important, lean towards using a classMost Java runtimes make a virtual method invocation of a class member a faster operation than an interface method invocation. Traits get compiled to interfaces and therefore may pay a slight performance overhead

Tip 2. Data Encapsulation: Case Class or Class?

When the Scala compiler sees a case class, it automatically generates copy(), toString(), hashcode(), equals() . This is the design of a "Case Class" in Scala. 

case class EncapsulateUsingCaseClass(a: Int, b:Int) {}
class EncapsulateUsingClass(a: Int, b:Int) {}




Tip 3. Maintain Immutability with Case Class

// You may want to change the address after the object is created. Even though Scala allows you to declare 'var' for case class parameters,
// this piece of code is conflicting with Immutability concept.
case class Student(id: String, name: String, var address: Int)
// Use 'Successor Value' Pattern to modify any of the fields in an object. The above case class can be written using successor value pattern
case class Student(id: String, name: String, age: Int) {
def modifyAge(newAge: Int): Student = Student(id, name, newAge)
}

No comments:

Post a Comment