Posts

Showing posts with the label Java Best Practices

Java Records in Functional Programming

Java Records in Functional Programming Java isn’t traditionally a functional programming (FP) language, but with the introduction of Records in Java 14+ (stable since Java 16), it’s become easier to write FP-inspired, data-oriented code. In this article, we’ll explore how Records support key functional programming principles like immutability , value-based semantics , and pure data modeling . 📦 What Are Java Records? Records are a concise way to declare immutable data carriers in Java. They auto-generate: Constructor Getters equals() and hashCode() toString() public record User(String name, int age) {} This class is equivalent to a verbose POJO, but it’s immutable and much cleaner. 🧠 Why Records Fit Functional Programming Functional programming promotes writing pure functions that avoid mutable state. Here’s how records align: ✅ Immutability – Record fields ar...

Lombok vs Records: When to Use What?

Lombok vs Records: When to Use What? With Java's continuous evolution, two powerful tools for reducing boilerplate code have emerged: Lombok and Records . But when should you choose one over the other? In this post, we'll break down their strengths, differences, and which scenarios they shine in. 🔧 Lombok: Auto-generating Boilerplate Code Lombok is a Java library that uses annotations to auto-generate boilerplate code like getters, setters, equals/hashCode, toString, and constructors. It’s widely used in legacy codebases to reduce verbosity while maintaining flexibility. Popular Lombok Annotations @Getter / @Setter – auto-generates getters and setters @ToString – generates the toString() method @EqualsAndHashCode – generates equals() and hashCode() methods @Builder – enables builder pattern @Value – creates immutable objects with final fields When to Use Lombok ...

Lombok – Reduce Boilerplate in Java

Lombok – Reduce Boilerplate in Java Writing boilerplate code in Java — like getters, setters, constructors, and builders — can get repetitive. Project Lombok simplifies this with annotations that auto-generate code at compile-time, keeping your classes clean and focused. 🔧 Setup To use Lombok, add this dependency to your project: ➡️ Maven <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> <scope>provided</scope> </dependency> ➡️ Gradle compileOnly 'org.projectlombok:lombok:1.18.30' annotationProcessor 'org.projectlombok:lombok:1.18.30' 📦 Example Without Lombok public class User { private String name; private int age; public User() {} public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } ...