1. หลีกเลี่ยงรหัสซ้ำ
Java เป็นภาษาที่ยอดเยี่ยม แต่บางครั้งมันก็ดูละเอียดเกินไปสำหรับสิ่งที่คุณต้องทำในโค้ดของคุณสำหรับงานทั่วไปหรือการปฏิบัติตามกรอบปฏิบัติบางอย่าง สิ่งเหล่านี้มักไม่นำมูลค่าที่แท้จริงมาสู่ด้านธุรกิจของโปรแกรมของคุณ - และนี่คือที่ที่ลอมบอกมาที่นี่เพื่อทำให้ชีวิตของคุณมีความสุขและมีประสิทธิผลมากขึ้น
วิธีการทำงานคือการเสียบเข้ากับกระบวนการสร้างของคุณและสร้าง bytecode Java โดยอัตโนมัติในไฟล์. classของคุณตามคำอธิบายประกอบโครงการจำนวนหนึ่งที่คุณแนะนำในโค้ดของคุณ
รวมไว้ในงานสร้างของคุณไม่ว่าคุณจะใช้ระบบใดอยู่ตรงไปตรงมามาก หน้าโครงการมีคำแนะนำโดยละเอียดเกี่ยวกับข้อมูลเฉพาะ โครงการส่วนใหญ่ของฉันเป็นแบบ maven ดังนั้นฉันมักจะทิ้งการพึ่งพาในขอบเขตที่ให้ไว้และฉันก็พร้อมที่จะไป:
... org.projectlombok lombok 1.18.10 provided ...
ตรวจสอบเวอร์ชันล่าสุดที่มีอยู่ที่นี่
โปรดทราบว่าการขึ้นอยู่กับลอมบอกจะไม่ทำให้ผู้ใช้. jarของคุณขึ้นอยู่กับมันเช่นกันเนื่องจากเป็นการพึ่งพาการสร้างที่บริสุทธิ์ไม่ใช่รันไทม์
2. Getters / Setters, Constructors - ซ้ำซาก
การห่อหุ้มคุณสมบัติของอ็อบเจ็กต์ผ่าน public getter และ setter method เป็นวิธีปฏิบัติทั่วไปในโลก Java และเฟรมเวิร์กจำนวนมากใช้รูปแบบ "Java Bean" นี้อย่างกว้างขวาง: คลาสที่มีคอนสตรัคเตอร์ว่างและเมธอด get / set สำหรับ "properties"
ซึ่งเป็นเรื่องปกติมากที่ IDE ส่วนใหญ่รองรับการสร้างโค้ดอัตโนมัติสำหรับรูปแบบเหล่านี้ (และอื่น ๆ ) อย่างไรก็ตามรหัสนี้จำเป็นต้องอยู่ในแหล่งที่มาของคุณและยังได้รับการดูแลเมื่อมีการเพิ่มคุณสมบัติใหม่หรือเปลี่ยนชื่อฟิลด์
ลองพิจารณาคลาสนี้ที่เราต้องการใช้เป็นเอนทิตี JPA เป็นตัวอย่าง:
@Entity public class User implements Serializable { private @Id Long id; // will be set when persisting private String firstName; private String lastName; private int age; public User() { } public User(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } // getters and setters: ~30 extra lines of code }
นี่เป็นคลาสที่ค่อนข้างเรียบง่าย แต่ยังคงพิจารณาว่าเราเพิ่มรหัสพิเศษสำหรับ getters และ setters หรือไม่เราจะได้คำจำกัดความที่เราจะมีรหัสค่าศูนย์สำเร็จรูปมากกว่าข้อมูลทางธุรกิจที่เกี่ยวข้อง: "ผู้ใช้มีก่อนและ นามสกุลและอายุ”
ให้เราตอนนี้Lombok-izeชั้นเรียนนี้:
@Entity @Getter @Setter @NoArgsConstructor // <--- THIS is it public class User implements Serializable { private @Id Long id; // will be set when persisting private String firstName; private String lastName; private int age; public User(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } }
โดยการเพิ่ม@Getterและ@Setterคำอธิบายประกอบที่เราบอกไปลอมบอก, ดี, สร้างเหล่านี้สำหรับเขตข้อมูลทั้งหมดของการเรียน @NoArgsConstructorจะนำไปสู่การสร้างตัวสร้างที่ว่างเปล่า
โปรดทราบว่านี่เป็นรหัสชั้นเรียนทั้งหมดฉันไม่ได้ละเว้นสิ่งใดที่ตรงข้ามกับเวอร์ชันด้านบนด้วย// getters and setters comment สำหรับคลาสแอตทริบิวต์ที่เกี่ยวข้องสามคลาสนี่คือการประหยัดรหัสที่สำคัญ!
หากคุณเพิ่มแอตทริบิวต์ (คุณสมบัติ) เพิ่มเติมให้กับคลาสUserของคุณสิ่งเดียวกันจะเกิดขึ้น: คุณใช้คำอธิบายประกอบกับประเภทนั้นเองดังนั้นพวกเขาจะคำนึงถึงฟิลด์ทั้งหมดตามค่าเริ่มต้น
จะเป็นอย่างไรหากคุณต้องการปรับแต่งการแสดงผลของคุณสมบัติบางอย่าง ตัวอย่างเช่นฉันต้องการเก็บแพ็กเกจตัวแก้ไขฟิลด์IDเอนทิตีของฉันไว้หรือมีการป้องกันไว้ให้มองเห็นได้เนื่องจากคาดว่าจะอ่านได้ แต่ไม่ได้กำหนดโดยรหัสแอปพลิเคชัน เพียงใช้@Setter แบบละเอียดสำหรับฟิลด์นี้โดยเฉพาะ:
private @Id @Setter(AccessLevel.PROTECTED) Long id;
3. Getter ขี้เกียจ
บ่อยครั้งที่แอปพลิเคชันจำเป็นต้องดำเนินการบางอย่างที่มีราคาแพงและบันทึกผลลัพธ์ไว้ใช้ในภายหลัง
ตัวอย่างเช่นสมมติว่าเราจำเป็นต้องอ่านข้อมูลคงที่จากไฟล์หรือฐานข้อมูล โดยทั่วไปเป็นแนวทางปฏิบัติที่ดีในการดึงข้อมูลนี้หนึ่งครั้งจากนั้นแคชเพื่อให้อ่านในหน่วยความจำภายในแอปพลิเคชัน ซึ่งจะช่วยไม่ให้แอปพลิเคชันทำซ้ำการดำเนินการที่มีราคาแพง
อีกรูปแบบที่พบบ่อยคือการดึงข้อมูลนี้เมื่อจำเป็นครั้งแรกเท่านั้น กล่าวอีกนัยหนึ่งคือรับข้อมูลเฉพาะเมื่อมีการเรียก getter ที่เกี่ยวข้องในครั้งแรก นี้เรียกว่าขี้เกียจโหลด
สมมติว่าข้อมูลนี้ถูกแคชเป็นฟิลด์ภายในคลาส ตอนนี้คลาสต้องตรวจสอบให้แน่ใจว่าการเข้าถึงฟิลด์นี้ส่งคืนข้อมูลแคช วิธีการหนึ่งที่เป็นไปได้ในการดำเนินการดังกล่าวเป็นระดับที่จะทำให้วิธีทะเยอทะยานเรียกข้อมูลเฉพาะในกรณีที่ข้อมูลเป็นโมฆะ ด้วยเหตุนี้เราเรียกสิ่งนี้ว่าขี้เกียจทะเยอทะยาน
Lombok ทำให้สิ่งนี้เป็นไปได้ด้วยพารามิเตอร์lazyในคำอธิบายประกอบ@ Getter ที่เราเห็นด้านบน
ตัวอย่างเช่นพิจารณาคลาสง่ายๆนี้:
public class GetterLazy { @Getter(lazy = true) private final Map transactions = getTransactions(); private Map getTransactions() { final Map cache = new HashMap(); List txnRows = readTxnListFromFile(); txnRows.forEach(s -> { String[] txnIdValueTuple = s.split(DELIMETER); cache.put(txnIdValueTuple[0], Long.parseLong(txnIdValueTuple[1])); }); return cache; } }
นี้อ่านบางรายการจากไฟล์ลงในแผนที่ เนื่องจากข้อมูลในไฟล์ไม่เปลี่ยนแปลงเราจะทำการแคชหนึ่งครั้งและอนุญาตให้เข้าถึงผ่าน getter
หากเราดูโค้ดที่คอมไพล์แล้วของคลาสนี้เราจะเห็นเมธอด getter ซึ่งจะอัพเดตแคชหากเป็นโมฆะจากนั้นส่งคืนข้อมูลแคช :
public class GetterLazy { private final AtomicReference transactions = new AtomicReference(); public GetterLazy() { } //other methods public Map getTransactions() { Object value = this.transactions.get(); if (value == null) { synchronized(this.transactions) { value = this.transactions.get(); if (value == null) { Map actualValue = this.readTxnsFromFile(); value = actualValue == null ? this.transactions : actualValue; this.transactions.set(value); } } } return (Map)((Map)(value == this.transactions ? null : value)); } }
เป็นเรื่องที่น่าสนใจที่จะชี้ให้เห็นว่าลอมบอกห่อฟิลด์ข้อมูลไว้ในAtomicReference สิ่งนี้ช่วยให้มั่นใจได้ถึงการอัปเดตอะตอมในฟิลด์ธุรกรรม getTransactions ()วิธีการนี้ยังทำให้แน่ใจว่าจะอ่านไฟล์ถ้าการทำธุรกรรมเป็นโมฆะ
ไม่แนะนำให้ใช้ฟิลด์ธุรกรรม AtomicReferenceโดยตรงจากภายในคลาส ขอแนะนำให้ใช้เมธอด getTransactions ()เพื่อเข้าถึงฟิลด์
ด้วยเหตุนี้ถ้าเราใช้คำอธิบายประกอบอีกเช่นลอมบอกToStringในระดับเดียวกัน,มันจะใช้getTransactions ()แทนการเข้าถึงโดยตรงสนาม
4. คลาสสุดคุ้ม / DTO
มีหลายสถานการณ์ที่เราต้องการกำหนดประเภทข้อมูลโดยมีจุดประสงค์เพียงอย่างเดียวในการแสดง "ค่า" ที่ซับซ้อนหรือเป็น "ออบเจ็กต์การถ่ายโอนข้อมูล" โดยส่วนใหญ่จะอยู่ในรูปแบบของโครงสร้างข้อมูลที่ไม่เปลี่ยนรูปที่เราสร้างเพียงครั้งเดียวและไม่ต้องการเปลี่ยนแปลง .
เราออกแบบคลาสเพื่อแสดงการล็อกอินที่ประสบความสำเร็จ เราต้องการให้เขตข้อมูลทั้งหมดไม่เป็นโมฆะและวัตถุไม่เปลี่ยนรูปเพื่อให้เราสามารถเข้าถึงคุณสมบัติของเธรดได้อย่างปลอดภัย:
public class LoginResult { private final Instant loginTs; private final String authToken; private final Duration tokenValidity; private final URL tokenRefreshUrl; // constructor taking every field and checking nulls // read-only accessor, not necessarily as get*() form }
อีกครั้งจำนวนโค้ดที่เราต้องเขียนสำหรับส่วนที่แสดงความคิดเห็นจะมีปริมาณมากกว่าข้อมูลที่เราต้องการห่อหุ้มและมีคุณค่าที่แท้จริงสำหรับเรา เราสามารถใช้ลอมบอกอีกครั้งเพื่อปรับปรุงสิ่งนี้:
@RequiredArgsConstructor @Accessors(fluent = true) @Getter public class LoginResult { private final @NonNull Instant loginTs; private final @NonNull String authToken; private final @NonNull Duration tokenValidity; private final @NonNull URL tokenRefreshUrl; }
เพียงเพิ่มคำอธิบายประกอบ@RequiredArgsConstructorและคุณจะได้รับตัวสร้างสำหรับฟิลด์สุดท้ายทั้งหมดภายในคลาสเช่นเดียวกับที่คุณประกาศไว้ การเพิ่ม@NonNullให้กับแอตทริบิวต์ทำให้ตัวสร้างของเราตรวจสอบความเป็นโมฆะและโยนNullPointerExceptionsตามนั้น สิ่งนี้จะเกิดขึ้นเช่นกันหากฟิลด์ไม่สิ้นสุดและเราได้เพิ่ม@Setterให้
คุณไม่ต้องการแบบฟอร์มget * ()แบบเก่าที่น่าเบื่อสำหรับคุณสมบัติของคุณหรือไม่? เพราะเราได้เพิ่ม@Accessors (คล่องแคล่ว = true)ในตัวอย่างนี้“getters” จะมีชื่อเดียวกันวิธีการเป็นคุณสมบัติ: getAuthToken ()ก็จะกลายเป็นauthToken ()
แบบฟอร์ม "คล่องแคล่ว" นี้จะใช้กับฟิลด์ที่ไม่ใช่ขั้นสุดท้ายสำหรับตัวตั้งค่าแอตทริบิวต์และยังอนุญาตให้มีการโทรแบบเชน:
// Imagine fields were no longer final now return new LoginResult() .loginTs(Instant.now()) .authToken("asdasd") . // and so on
5. Core Java Boilerplate
อีกสถานการณ์หนึ่งที่เราจบลงด้วยการเขียนโค้ดที่เราจำเป็นต้องรักษาคือเมื่อสร้างtoString () , เท่ากับ ()และhashCode ()วิธีการ IDE พยายามช่วยเหลือเกี่ยวกับเทมเพลตสำหรับการสร้างสิ่งเหล่านี้โดยอัตโนมัติในแง่ของแอตทริบิวต์คลาสของเรา
เราสามารถทำสิ่งนี้โดยอัตโนมัติโดยใช้คำอธิบายประกอบระดับชั้นอื่น ๆ ของลอมบอก:
- @ToString: will generate a toString() method including all class attributes. No need to write one ourselves and maintain it as we enrich our data model.
- @EqualsAndHashCode: will generate both equals() and hashCode() methods by default considering all relevant fields, and according to very well though semantics.
These generators ship very handy configuration options. For example, if your annotated classes take part of a hierarchy you can just use the callSuper=true parameter and parent results will be considered when generating the method's code.
More on this: say we had our User JPA entity example include a reference to events associated to this user:
@OneToMany(mappedBy = "user") private List events;
We wouldn't like to have the whole list of events dumped whenever we call the toString() method of our User, just because we used the @ToString annotation. No problem: just parameterize it like this: @ToString(exclude = {“events”}), and that won't happen. This is also helpful to avoid circular references if, for example, UserEvents had a reference to a User.
For the LoginResult example, we may want to define equality and hash code calculation just in terms of the token itself and not the other final attributes in our class. Then, simply write something like @EqualsAndHashCode(of = {“authToken”}).
Bonus: if you liked the features from the annotations we've reviewed so far you may want to examine @Data and @Value annotations as they behave as if a set of them had been applied to our classes. After all, these discussed usages are very commonly put together in many cases.
5.1. (Not) Using the @EqualsAndHashCode With JPA Entities
Whether to use the default equals() and hashCode() methods or create custom ones for the JPA entities, is an often discussed topic among developers. There are multiple approaches we can follow; each having its pros and cons.
By default, @EqualsAndHashCode includes all non-final properties of the entity class. We can try to “fix” this by using the onlyExplicitlyIncluded attribute of the @EqualsAndHashCode to make Lombok use only the entity's primary key. Still, however, the generated equals() method can cause some issues. Thorben Janssen explains this scenario in greater detail in one of his blog posts.
In general, we should avoid using Lombok to generate the equals() and hashCode() methods for our JPA entities!
6. The Builder Pattern
The following could make for a sample configuration class for a REST API client:
public class ApiClientConfiguration { private String host; private int port; private boolean useHttps; private long connectTimeout; private long readTimeout; private String username; private String password; // Whatever other options you may thing. // Empty constructor? All combinations? // getters... and setters? }
We could have an initial approach based on using the class default empty constructor and providing setter methods for every field. However, we'd ideally want configurations not to be re-set once they've been built (instantiated), effectively making them immutable. We therefore want to avoid setters, but writing such a potentially long args constructor is an anti-pattern.
Instead, we can tell the tool to generate a builder pattern, preventing us to write an extra Builder class and associated fluent setter-like methods by simply adding the @Builder annotation to our ApiClientConfiguration.
@Builder public class ApiClientConfiguration { // ... everything else remains the same }
Leaving the class definition above as such (no declare constructors nor setters + @Builder) we can end up using it as:
ApiClientConfiguration config = ApiClientConfiguration.builder() .host("api.server.com") .port(443) .useHttps(true) .connectTimeout(15_000L) .readTimeout(5_000L) .username("myusername") .password("secret") .build();
7. Checked Exceptions Burden
Lots of Java APIs are designed so that they can throw a number of checked exceptions client code is forced to either catch or declare to throws. How many times have you turned these exceptions you know won't happen into something like this?
public String resourceAsString() { try (InputStream is = this.getClass().getResourceAsStream("sure_in_my_jar.txt")) { BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); return br.lines().collect(Collectors.joining("\n")); } catch (IOException | UnsupportedCharsetException ex) { // If this ever happens, then its a bug. throw new RuntimeException(ex); <--- encapsulate into a Runtime ex. } }
If you want to avoid this code patterns because the compiler won't be otherwise happy (and, after all, you know the checked errors cannot happen), use the aptly named @SneakyThrows:
@SneakyThrows public String resourceAsString() { try (InputStream is = this.getClass().getResourceAsStream("sure_in_my_jar.txt")) { BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); return br.lines().collect(Collectors.joining("\n")); } }
8. Ensure Your Resources Are Released
Java 7 introduced the try-with-resources block to ensure your resources held by instances of anything implementing java.lang.AutoCloseable are released when exiting.
Lombok provides an alternative way of achieving this, and more flexibly via @Cleanup. Use it for any local variable whose resources you want to make sure are released. No need for them to implement any particular interface, you'll just get its close() method called.
@Cleanup InputStream is = this.getClass().getResourceAsStream("res.txt");
Your releasing method has a different name? No problem, just customize the annotation:
@Cleanup("dispose") JFrame mainFrame = new JFrame("Main Window");
9. Annotate Your Class to Get a Logger
Many of us add logging statements to our code sparingly by creating an instance of a Logger from our framework of choice. Say, SLF4J:
public class ApiClientConfiguration { private static Logger LOG = LoggerFactory.getLogger(ApiClientConfiguration.class); // LOG.debug(), LOG.info(), ... }
This is such a common pattern that Lombok developers have cared to simplify it for us:
@Slf4j // or: @Log @CommonsLog @Log4j @Log4j2 @XSlf4j public class ApiClientConfiguration { // log.debug(), log.info(), ... }
Many logging frameworks are supported and of course you can customize the instance name, topic, etc.
10. Write Thread-Safer Methods
In Java you can use the synchronized keyword to implement critical sections. However, this is not a 100% safe approach: other client code can eventually also synchronize on your instance, potentially leading to unexpected deadlocks.
This is where @Synchronized comes in: annotate your methods (both instance and static) with it and you'll get an autogenerated private, unexposed field your implementation will use for locking:
@Synchronized public /* better than: synchronized */ void putValueInCache(String key, Object value) { // whatever here will be thread-safe code }
11. Automate Objects Composition
Java does not have language level constructs to smooth out a “favor composition inheritance” approach. Other languages have built-in concepts such as Traits or Mixins to achieve this.
Lombok's @Delegate comes in very handy when you want to use this programming pattern. Let's consider an example:
- We want Users and Customers to share some common attributes for naming and phone number
- We define both an interface and an adapter class for these fields
- We'll have our models implement the interface and @Delegate to their adapter, effectively composing them with our contact information
First, let's define an interface:
public interface HasContactInformation { String getFirstName(); void setFirstName(String firstName); String getFullName(); String getLastName(); void setLastName(String lastName); String getPhoneNr(); void setPhoneNr(String phoneNr); }
And now an adapter as a support class:
@Data public class ContactInformationSupport implements HasContactInformation { private String firstName; private String lastName; private String phoneNr; @Override public String getFullName() { return getFirstName() + " " + getLastName(); } }
The interesting part comes now, see how easy it is to now compose contact information into both model classes:
public class User implements HasContactInformation { // Whichever other User-specific attributes @Delegate(types = {HasContactInformation.class}) private final ContactInformationSupport contactInformation = new ContactInformationSupport(); // User itself will implement all contact information by delegation }
The case for Customer would be so similar we'd omit the sample for brevity.
12. Rolling Lombok Back?
Short answer: Not at all really.
You may be worried there is a chance that you use Lombok in one of your projects, but later want to rollback that decision. You'd then have a maybe large number of classes annotated for it… what could you do?
I have never really regretted this, but who knows for you, your team or your organization. For these cases you're covered thanks to the delombok tool from the same project.
By delombok-ing your code you'd get autogenerated Java source code with exactly the same features from the bytecode Lombok built. So then you may simply replace your original annotated code with these new delomboked files and no longer depend on it.
This is something you can integrate in your build and I have done this in the past to just study the generated code or to integrate Lombok with some other Java source code based tool.
13. Conclusion
There are some other features we have not presented in this article, I'd encourage you to take a deeper dive into the feature overview for more details and use cases.
นอกจากนี้ฟังก์ชั่นส่วนใหญ่ที่เราแสดงยังมีตัวเลือกการปรับแต่งมากมายที่คุณอาจพบว่ามีประโยชน์ในการทำให้เครื่องมือสร้างสิ่งที่สอดคล้องกับแนวทางปฏิบัติของทีมของคุณในการตั้งชื่อ ฯลฯ มากที่สุดระบบการกำหนดค่าในตัวที่มีอยู่สามารถช่วยคุณได้เช่นกัน
ฉันหวังว่าคุณจะพบแรงจูงใจที่จะเปิดโอกาสให้ลอมบอกเข้าสู่ชุดเครื่องมือการพัฒนา Java ของคุณ ทดลองใช้และเพิ่มผลผลิตของคุณ!
โค้ดตัวอย่างสามารถพบได้ในโครงการ GitHub