Tuesday, October 8, 2013

Scala: get rid of not-null validations

Scala has been always known as a language which allows special handling of null values. There is ton of articles regarding Some[T], None, Option[T].

What is most annoying code for me? Null validations, see usual example:


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Entity {

}

class ServiceA {
  def method(a: Entity, b: Entity, c: Entity, d: Entity) = {
    Validate.notNull(a)
    Validate.notNull(b)
    Validate.notNull(c)
    Validate.notNull(d)
  }
}

class ServiceB(val a: ServiceA) {
  def method() = {
    a.method(null,null,null,null)
  }
}

When you start to write save code in the term of fails-as-fast-as-possible, your code, services or even domain model, will be weedy, you will find such boilerplate code at every method because you can't be sure which parameter supplied someone to you class or method.

Unfortunately Scala has beautiful way how to achieve nice and simple code - without these checks. If you don't think that null is proper state for your class, just dismiss this option. How to do that?


1
2
3
class Entity extends NotNull{

}

Well, that's all. Look at screenshot from my IDE what is about to happen:

notNull trait scala

Now, if you are sure that you don't want to allow null value for your entity, you can implement NotNull trait and you can remove many lines from your source code.

I was surprised when I found this trait in scala code, because many tutorials or even famous Scala for the Impatient book does not mention this simple but beautiful piece of code.

0 comments: