寫程式應該要盡可能的避免duplicate code(重複程式碼),一樣的、沒有價值的東西,一直寫幹嘛?對吧!
在Android開發上,不管你是使用哪一種Architecture(MVC、MVP、MVVM...等等),都一定有Model層,Model是我們在程式開發上最原始、最簡單的東西。
但打開你的Project看看你的Model,會發現重複的method一直在出現【getter、setter、equals、hashCode、toString....】等等等。
現在,我們透過【AutoValue】就可以大幅的簡化它了。
這個由google maintain的github開源項目,在本文章撰寫時最新版本是v1.4.1
Library projects:
Gradle:
//auto-value provided 'com.google.auto.value:auto-value:1.4.1' annotationProcessor 'com.google.auto.value:auto-value:1.4.1'
以下使用一個Book類別做示範
Before:
public class Book { private String name; private int price; private String author; public Book(String name, int price, String author) { this.name = name; this.price = price; this.author = author; } @Override public String toString() { return "Book{" + "name=" + name + ", price=" + price + ", author=" + author + "}"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
Book book = new Book("安森瓦舍", 87, "Anson"); System.out.println("書名:" + book.getName()); System.out.println("價格:" + book.getPrice()); System.out.println("作者:" + book.getAuthor());
After:
@AutoValue public abstract class Book { public abstract String name(); public abstract int price(); public abstract String author(); public static Book create(String name, int price, String author) { return new AutoValue_Book(name, price, author); } }
Book book = Book.create("安森瓦舍", 87, "Anson"); System.out.println("書名:" + book.name()); System.out.println("價格:" + book.price()); System.out.println("作者:" + book.author());
如果你想使用Builder pattern的話
@AutoValue public abstract class Book { public abstract String name(); public abstract int price(); public abstract String author(); public static Book create(String name, int price, String author) { return builder() .name(name) .price(price) .author(author) .build(); } public static Builder builder() { return new AutoValue_Book.Builder(); } @AutoValue.Builder public abstract static class Builder { public abstract Builder name(String name); public abstract Builder price(int price); public abstract Builder author(String author); public abstract Book build(); } }
Book book = Book.create("安森瓦舍", 87, "Anson"); System.out.println("書名:" + book.name()); System.out.println("價格:" + book.price()); System.out.println("作者:" + book.author());
延伸閱讀:
● 最簡潔的Model層 - AutoValue 使用介紹【二】
● 最簡潔的Model層 - AutoValue 使用介紹【三】