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.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close