Въведение в AutoValue

1. Общ преглед

AutoValue е генератор на изходен код за Java, и по-точно това е библиотека за генериране на изходен код за обекти на стойност или обекти, въведени от стойност .

За да генерирате обект от тип стойност, всичко, което трябва да направите, е да анотирате абстрактния клас с анотацията @AutoValue и да компилирате своя клас. Това, което се генерира, е обект на стойност с методи за достъп, параметризиран конструктор, правилно заменен toString (), equals (Object) и hashCode () методи.

Следният кодов фрагмент е бърз пример за абстрактен клас, който при компилиране ще доведе до обект на стойност с име AutoValue_Person .

@AutoValue abstract class Person { static Person create(String name, int age) { return new AutoValue_Person(name, age); } abstract String name(); abstract int age(); } 

Нека продължим и да разберем повече за стойностните обекти, защо се нуждаем от тях и как AutoValue може да помогне задачата за генериране и рефакторинг на код да отнеме много по-малко време.

2. Настройка на Maven

За да използвате AutoValue в проекти на Maven, трябва да включите следната зависимост в pom.xml :

 com.google.auto.value auto-value 1.2 

Най-новата версия може да бъде намерена, като следвате тази връзка.

3. Обекти с типизирана стойност

Ценностните типове са крайният продукт на библиотеката, така че за да оценим нейното място в нашите задачи за развитие, трябва да разберем изцяло ценностните типове, какви са те, какви не са и защо се нуждаем от тях.

3.1. Какво представляват типовете ценности?

Обектите от стойност са обекти, чието равенство помежду си не се определя от идентичността, а по-скоро от тяхното вътрешно състояние. Това означава, че два екземпляра на обект, въведен от стойност, се считат за равни, стига да имат равни стойности на полето.

Обикновено типовете стойности са неизменни . Техните полета трябва да бъдат окончателни и те не трябва да имат методи за задаване , тъй като това ще ги направи променливи след създаването на екземпляр.

Те трябва да консумират всички полеви стойности чрез конструктор или фабричен метод.

Типовете стойности не са JavaBeans, тъй като нямат конструктор на аргументи по подразбиране или нула, нито имат методи за задаване, по същия начин те не са обекти за трансфер на данни, нито обикновени стари Java обекти .

Освен това класът, въведен от стойност, трябва да бъде окончателен, така че да не може да се разширява, най-малкото някой да замени методите. JavaBeans, DTO и POJO не трябва да са окончателни.

3.2. Създаване на стойност-тип

Ако приемем, че искаме да създадем тип стойност, наречен Foo с полета, наречени текст и число. Как бихме се справили с това?

Щяхме да направим финален клас и да маркираме всички негови полета като окончателни. След това бихме използвали IDE за генериране на конструктора, метода hashCode (), метода equals (Object) , гетерите като задължителни методи и метод toString () и бихме имали клас като този:

public final class Foo { private final String text; private final int number; public Foo(String text, int number) { this.text = text; this.number = number; } // standard getters @Override public int hashCode() { return Objects.hash(text, number); } @Override public String toString() { return "Foo [text=" + text + ", number=" + number + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Foo other = (Foo) obj; if (number != other.number) return false; if (text == null) { if (other.text != null) return false; } else if (!text.equals(other.text)) { return false; } return true; } }

След създаването на екземпляр на Foo очакваме вътрешното му състояние да остане същото за целия си жизнен цикъл.

Както ще видим в следващата алинея на хеш-код на даден обект трябва да се промени от инстанция на инстанция , но за ценностни видове, ние трябва да го връзвам с областите, които определят вътрешното състояние на обекта на стойност.

Следователно, дори промяната на поле на същия обект би променила стойността на hashCode .

3.3. Как работят типовете стойности

Причината, поради която типовете стойности трябва да бъдат неизменни, е да се предотврати всяка промяна във вътрешното им състояние от приложението, след като те са били създадени.

Винаги, когато искаме да сравним каквито и да е два обекта, въведени от стойност, трябва да използваме метода equals (Object) от класа Object .

Това означава, че винаги трябва да заменяме този метод в нашите собствени типове стойности и да връщаме true, само ако полетата на обектите на стойност, които сравняваме, имат равни стойности.

Освен това, за нас, за да използвате нашите стойност обекти в хеш-базирани колекции като HashSet ите и HashMap и без да се счупи, ние трябва правилно прилагане на хеш-код () метод .

3.4. Защо ни трябват ценностни типове

Нуждата от ценностни типове се появява доста често. Това са случаи, в които бихме искали да заменим поведението по подразбиране на оригиналния клас Object .

Както вече знаем, изпълнението по подразбиране на клас Object разглежда два обекта равни, когато имат еднаква идентичност, но за нашите цели ние считаме, че два обекта са равни, когато имат едно и също вътрешно състояние .

Ако приемем, че бихме искали да създадем паричен обект, както следва:

public class MutableMoney { private long amount; private String currency; public MutableMoney(long amount, String currency) { this.amount = amount; this.currency = currency; } // standard getters and setters }

Можем да пуснем следния тест върху него, за да проверим равенството му:

@Test public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() { MutableMoney m1 = new MutableMoney(10000, "USD"); MutableMoney m2 = new MutableMoney(10000, "USD"); assertFalse(m1.equals(m2)); }

Забележете семантиката на теста.

Считаме, че е преминало, когато двата парични обекта не са равни. Това е така, защото не сме заменили метода equals , така че равенството се измерва чрез сравняване на препратките към паметта на обектите, които, разбира се, няма да бъдат различни, тъй като те са различни обекти, заемащи различни места в паметта.

Each object represents 10,000 USD but Java tells us our money objects are not equal. We want the two objects to test unequal only when either the currency amounts are different or the currency types are different.

Now let us create an equivalent value object and this time we will let the IDE generate most of the code:

public final class ImmutableMoney { private final long amount; private final String currency; public ImmutableMoney(long amount, String currency) { this.amount = amount; this.currency = currency; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (amount ^ (amount >>> 32)); result = prime * result + ((currency == null) ? 0 : currency.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ImmutableMoney other = (ImmutableMoney) obj; if (amount != other.amount) return false; if (currency == null) { if (other.currency != null) return false; } else if (!currency.equals(other.currency)) return false; return true; } }

The only difference is that we overrode the equals(Object) and hashCode() methods, now we have control over how we want Java to compare our money objects. Let's run its equivalent test:

@Test public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() { ImmutableMoney m1 = new ImmutableMoney(10000, "USD"); ImmutableMoney m2 = new ImmutableMoney(10000, "USD"); assertTrue(m1.equals(m2)); }

Notice the semantics of this test, we expect it to pass when both money objects test equal via the equals method.

4. Why AutoValue?

Now that we thoroughly understand value-types and why we need them, we can look at AutoValue and how it comes into the equation.

4.1. Issues With Hand-Coding

When we create value-types like we have done in the preceding section, we will run into a number of issues related to bad design and a lot of boilerplate code.

A two field class will have 9 lines of code: one for package declaration, two for the class signature and its closing brace, two for field declarations, two for constructors and its closing brace and two for initializing the fields, but then we need getters for the fields, each taking three more lines of code, making six extra lines.

Overriding the hashCode() and equalTo(Object) methods require about 9 lines and 18 lines respectively and overriding the toString() method adds another five lines.

That means a well-formatted code base for our two field class would take about 50 lines of code.

4.2 IDEs to The Rescue?

This is is easy with an IDE like Eclipse or IntilliJ and with only one or two value-typed classes to create. Think about a multitude of such classes to create, would it still be as easy even if the IDE helps us?

Fast forward, some months down the road, assume we have to revisit our code and make amendments to our Money classes and perhaps convert the currency field from the String type to another value-type called Currency.

4.3 IDEs Not Really so Helpful

An IDE like Eclipse can't simply edit for us our accessor methods nor the toString(), hashCode() or equals(Object) methods.

This refactoring would have to be done by hand. Editing code increases the potential for bugs and with every new field we add to the Money class, the number of lines increases exponentially.

Recognizing the fact that this scenario happens, that it happens often and in large volumes will make us really appreciate the role of AutoValue.

5. AutoValue Example

The problem AutoValue solves is to take all the boilerplate code that we talked about in the preceding section, out of our way so that we never have to write it, edit it or even read it.

We will look at the very same Money example, but this time with AutoValue. We will call this class AutoValueMoney for the sake of consistency:

@AutoValue public abstract class AutoValueMoney { public abstract String getCurrency(); public abstract long getAmount(); public static AutoValueMoney create(String currency, long amount) { return new AutoValue_AutoValueMoney(currency, amount); } }

What has happened is that we write an abstract class, define abstract accessors for it but no fields, we annotate the class with @AutoValue all totalling to only 8 lines of code, and javac generates a concrete subclass for us which looks like this:

public final class AutoValue_AutoValueMoney extends AutoValueMoney { private final String currency; private final long amount; AutoValue_AutoValueMoney(String currency, long amount) { if (currency == null) throw new NullPointerException(currency); this.currency = currency; this.amount = amount; } // standard getters @Override public int hashCode() { int h = 1; h *= 1000003; h ^= currency.hashCode(); h *= 1000003; h ^= amount; return h; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof AutoValueMoney) { AutoValueMoney that = (AutoValueMoney) o; return (this.currency.equals(that.getCurrency())) && (this.amount == that.getAmount()); } return false; } }

We never have to deal with this class directly at all, neither do we have to edit it when we need to add more fields or make changes to our fields like the currency scenario in the previous section.

Javac will always regenerate updated code for us.

While using this new value-type, all callers see is only the parent type as we will see in the following unit tests.

Here is a test that verifies that our fields are being set correctly:

@Test public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() { AutoValueMoney m = AutoValueMoney.create("USD", 10000); assertEquals(m.getAmount(), 10000); assertEquals(m.getCurrency(), "USD"); }

A test to verify that two AutoValueMoney objects with the same currency and same amount test equal follow:

@Test public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() { AutoValueMoney m1 = AutoValueMoney.create("USD", 5000); AutoValueMoney m2 = AutoValueMoney.create("USD", 5000); assertTrue(m1.equals(m2)); }

When we change the currency type of one money object to GBP, the test: 5000 GBP == 5000 USD is no longer true:

@Test public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() { AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000); AutoValueMoney m2 = AutoValueMoney.create("USD", 5000); assertFalse(m1.equals(m2)); }

6. AutoValue With Builders

The initial example we have looked at covers the basic usage of AutoValue using a static factory method as our public creation API.

Notice that if all our fields were Strings, it would be easy to interchange them as we passed them to the static factory method, like placing the amount in the place of currency and vice versa.

This is especially likely to happen if we have many fields and all are of String type. This problem is made worse by the fact that with AutoValue, all fields are initialized through the constructor.

To solve this problem we should use the builder pattern. Fortunately. this can be generated by AutoValue.

Our AutoValue class does not really change much, except that the static factory method is replaced by a builder:

@AutoValue public abstract class AutoValueMoneyWithBuilder { public abstract String getCurrency(); public abstract long getAmount(); static Builder builder() { return new AutoValue_AutoValueMoneyWithBuilder.Builder(); } @AutoValue.Builder abstract static class Builder { abstract Builder setCurrency(String currency); abstract Builder setAmount(long amount); abstract AutoValueMoneyWithBuilder build(); } }

The generated class is just the same as the first one but a concrete inner class for the builder is generated as well implementing the abstract methods in the builder:

static final class Builder extends AutoValueMoneyWithBuilder.Builder { private String currency; private long amount; Builder() { } Builder(AutoValueMoneyWithBuilder source) { this.currency = source.getCurrency(); this.amount = source.getAmount(); } @Override public AutoValueMoneyWithBuilder.Builder setCurrency(String currency) { this.currency = currency; return this; } @Override public AutoValueMoneyWithBuilder.Builder setAmount(long amount) { this.amount = amount; return this; } @Override public AutoValueMoneyWithBuilder build() { String missing = ""; if (currency == null) { missing += " currency"; } if (amount == 0) { missing += " amount"; } if (!missing.isEmpty()) { throw new IllegalStateException("Missing required properties:" + missing); } return new AutoValue_AutoValueMoneyWithBuilder(this.currency,this.amount); } }

Notice also how the test results don't change.

If we want to know that the field values are actually correctly set through the builder, we can execute this test:

@Test public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() { AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder(). setAmount(5000).setCurrency("USD").build(); assertEquals(m.getAmount(), 5000); assertEquals(m.getCurrency(), "USD"); }

To test that equality depends on internal state:

@Test public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() { AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder() .setAmount(5000).setCurrency("USD").build(); AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder() .setAmount(5000).setCurrency("USD").build(); assertTrue(m1.equals(m2)); }

And when the field values are different:

@Test public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() { AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder() .setAmount(5000).setCurrency("USD").build(); AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder() .setAmount(5000).setCurrency("GBP").build(); assertFalse(m1.equals(m2)); }

7. Conclusion

In this tutorial, we have introduced most of the basics of Google's AutoValue library and how to use it to create value-types with a very little code on our part.

An alternative to Google's AutoValue is the Lombok project – you can have a look at the introductory article about using Lombok here.

Пълното изпълнение на всички тези примери и кодови фрагменти може да се намери в проекта AutoValue GitHub.