Pengantar AutoValue

1. Ikhtisar

AutoValue adalah generator kode sumber untuk Java, dan lebih khusus lagi ini adalah pustaka untuk menghasilkan kode sumber untuk objek nilai atau objek dengan tipe nilai .

Untuk menghasilkan objek tipe nilai, yang harus Anda lakukan adalah membuat anotasi kelas abstrak dengan anotasi @AutoValue dan mengompilasi kelas Anda. Apa yang dihasilkan adalah objek nilai dengan metode aksesor, konstruktor berparameter, dengan benar mengganti metode toString (), sama dengan (Object) dan hashCode () .

Potongan kode berikut adalah contoh cepat dari kelas abstrak yang ketika dikompilasi akan menghasilkan objek nilai bernama 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(); } 

Mari lanjutkan dan cari tahu lebih banyak tentang objek nilai, mengapa kita membutuhkannya, dan bagaimana AutoValue dapat membantu membuat tugas membuat dan memfaktorkan ulang kode jauh lebih memakan waktu.

2. Pengaturan Maven

Untuk menggunakan AutoValue dalam project Maven, Anda perlu menyertakan dependensi berikut di pom.xml :

 com.google.auto.value auto-value 1.2 

Versi terbaru dapat ditemukan dengan mengikuti tautan ini.

3. Objek dengan Tipe Nilai

Tipe-nilai adalah produk akhir perpustakaan, jadi untuk menghargai tempatnya dalam tugas-tugas pengembangan kita, kita harus benar-benar memahami tipe-nilai, apa itu, apa yang bukan dan mengapa kita membutuhkannya.

3.1. Apakah Tipe-Nilai Itu?

Objek tipe nilai adalah objek yang kesetaraannya satu sama lain tidak ditentukan oleh identitas, melainkan oleh keadaan internalnya. Ini berarti bahwa dua contoh objek dengan tipe nilai dianggap sama selama keduanya memiliki nilai bidang yang sama.

Biasanya, tipe nilai tidak dapat diubah . Bidang mereka harus dibuat final dan tidak boleh memiliki metode penyetel karena ini akan membuatnya dapat diubah setelah pembuatan instance.

Mereka harus menggunakan semua nilai bidang melalui konstruktor atau metode pabrik.

Tipe nilai bukan JavaBeans karena tidak memiliki konstruktor argumen default atau nol dan juga tidak memiliki metode penyetel, demikian pula, bukan Objek Transfer Data atau Objek Java Lama Biasa .

Selain itu, kelas tipe nilai harus final, sehingga mereka tidak dapat diperpanjang, setidaknya seseorang menimpa metode. JavaBeans, DTO dan POJO tidak harus final.

3.2. Menciptakan Tipe-Nilai

Dengan asumsi kami ingin membuat tipe nilai yang disebut Foo dengan bidang yang disebut teks dan angka. Bagaimana kita melakukannya?

Kami akan membuat kelas terakhir dan menandai semua bidangnya sebagai final. Kemudian kita akan menggunakan IDE untuk menghasilkan konstruktor, metode hashCode () , metode sama dengan (Objek) , getter sebagai metode wajib dan metode toString () , dan kita akan memiliki kelas seperti ini:

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; } }

Setelah membuat instance Foo , kami berharap status internalnya tetap sama selama seluruh siklus hidupnya.

Seperti yang akan kita lihat pada sub - bagian berikut, kode hash dari suatu objek harus berubah dari satu contoh ke contoh lainnya , tetapi untuk tipe-nilai, kita harus mengikatnya ke bidang yang menentukan keadaan internal dari objek nilai.

Oleh karena itu, bahkan mengubah bidang dari objek yang sama akan mengubah nilai kode hash .

3.3. Bagaimana Tipe-Nilai Bekerja

Alasan tipe nilai harus tetap adalah untuk mencegah perubahan apa pun pada status internalnya oleh aplikasi setelah dibuatkan contoh.

Setiap kali kita ingin membandingkan dua objek yang diketik dengan nilai , oleh karena itu, kita harus menggunakan metode sama dengan (Objek) dari kelas Objek .

Ini berarti bahwa kita harus selalu mengganti metode ini dalam tipe nilai kita sendiri dan hanya mengembalikan true jika bidang objek nilai yang kita bandingkan memiliki nilai yang sama.

Selain itu, bagi kita untuk menggunakan objek nilai kita dalam koleksi berbasis hash seperti HashSet dan HashMap tanpa merusak, kita harus menerapkan metode hashCode () dengan benar .

3.4. Mengapa Kita Membutuhkan Tipe-Nilai

Kebutuhan akan tipe nilai sering muncul. Ini adalah kasus di mana kami ingin menimpa perilaku default kelas Object asli .

Seperti yang sudah kita ketahui, implementasi default dari kelas Object menganggap dua objek sama ketika mereka memiliki identitas yang sama namun untuk tujuan kita, kita menganggap dua objek sama ketika mereka memiliki keadaan internal yang sama .

Dengan asumsi kita ingin membuat objek uang sebagai berikut:

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 }

Kami dapat menjalankan pengujian berikut untuk menguji kesetaraannya:

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

Perhatikan semantik tes.

Kami menganggapnya telah berlalu ketika dua objek uang tidak sama. Ini karena kita belum menimpa metode sama sehingga kesetaraan diukur dengan membandingkan referensi memori dari objek, yang tentunya tidak akan berbeda karena mereka adalah objek berbeda yang menempati lokasi memori berbeda.

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.

Implementasi lengkap dari semua contoh dan cuplikan kode ini dapat ditemukan di proyek AutoValue GitHub.