Auto Value

Jintin
HackerNoon.com
3 min readOct 29, 2017

--

Auto Value is a library to help you easily construct value class. It automatically generate code at build time to reduce lots of boilerplate in your source code.

The Old Days

Let’s start from a simple POJO to see what we can improve.

What the matter of this simple code?

  1. Getter and setter seems boilerplate but we still have to add to comply with the encapsulate rule.
  2. Manually override hasCode() and equals() to distinguish different objects.
  3. Manually override toString() for better logging purpose.

AutoValue is here to rescue.

Get Start

How Auto Value can help us? Here is the sample code after we use AutoValue.

By add the @AutoValue annotation, Auto Value auto generate the AutoValue_Point class for us. We access the real class by the abstract interface Point. So what problem we solved?

  1. No getter anymore
  2. No setter which imply immutable in most case
  3. Hide the detail of all basic function (equals, hashCode) in the generate class

p.s. One thing to notice is that we can still modify the value if it’s Array type like List.

What the generate class do?

We can also check whatAutoValue_Point do for us.

Builder Pattern

What if the parameters is too many so it’s hard to read? AutoValue also support builder mode to instantiate object.

The usage is simple as normal builder.

Update Value

AutoValue object is immutable by its design, but the builder pattern also benefit us to clone object when we have to. Just add an abstract toBuilder to indicate we have the functionality to create builder by existing value. Than we can transform the builder back to object after we update value or at anytime.

Reference

--

--

Jintin
HackerNoon.com

Android/iOS developer, husband and dad. Love to build interesting things to make life easier.