I have been a Java Developer for almost 2 years, so not very long in terms of programming. Yet, I want to share with you some tips, libraries and other stuff that I found very helpful through these several months.

Streams API

Java 8 has been almost 5 years here with us, but I still don’t feel like everybody noticed the great things it gave us. One of them is Streams API. After hundreds for loops written, it is hard to start with streams. They are looking odd, counterintuitive. You have to try it several times and eventually you will get it. And when you do, I can promise, you will be really surprised and think “how did I live without it”

// Standard for loop
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List<String> filteredAsString = new ArrayList<>();
for (Integer number : numbers) {
    if (number > 3) {
        filtered.add(String.valueOf(number));
    }
}
return filteredAsString;

// Stream
return List.of(1, 2, 3, 4, 5, 6) // check also IntStream interface
            .filter(number -> number > 3) // lambda, another great Java 8 feature
            .map(String::valueOf) // method reference, another one ~DJ Khaled
            .collect(Collectors.toList());

Optional

“I call it my billion-dollar mistake…”. You know this quote? Tony Hoare said it. It is about null reference which he created. Just trust this guy this time. Don’t return null if you don’t have to (you don’t…). Let your co-workers know right away that the value they are expecting might not be delivered.

// person.email returning Email, email.address() returning String
Email email = person.email();
if (email != null) {
    String address = email.address();
    if (address != null) {
        recipients.add(address);
    }
}

// person.email returning Optional<Email>, email.address() returning Optional<String>
person.email()
      .flatMap(Email::address)
      .ifPresent(recipients::add);

Immutability

Treat your objects like your young, innocent children. Do not let the outside world have too big of an impact on them. Protect your objects, protect their values. Actually, there are only advantages to immutability: thread safety, your sanity’s safety, less bugs, garbage collector gratefulness and more.

// no no
public class ProductPrice {
    private Double amount;
    private String currency;

    public ProductPrice() {}

    public void setAmount(Double amount) { this.amount = amount; }
    public Double getAmount() { return amount; }
    public void setCurrency(String currency) { this.currency = currency; }
    public String getCurrency() { return currency; }
}

// or the same no no, but much shorter
public class ProductPrice {
    public Double amount;
    public String currency;
}

// better, immutable one
final class ProductPrice {
    private final BigDecimal amount;
    private final Currency currency; // value objects are cool (immutable as well of course)

    ProductPrice(BigDecimal amount, Currency currency) {
        this.amount = amount;
        this.currency = currency;
    }

    // eventual getters, or business methods 
}

Lombok

This “little” library has its flaws. Harder debugging, it may not be working, because you forgot to enable Annotation Processing again, but at the end of the day it will probably save much of your time. Annotations I use the most: @Value, @Data, @Slf4j (or other logs), @AllArgsConstructor, @SneakyThrows. They recently even added val and var keywords!

// without lombok
final class Post {
    private final Author author;
    private final String title;
    private final Content content;

    Post(Author author, String title, Content content) {
        this.author = author;
        this.title = title;
        this.content = content;
    }

    Author author() { return author; }
    String title() { return title; }
    Content content() { return content; }

    //toString...
    //hashCode...
    //equals...
}

// with lombok
@Value
@Accessors(fluent = true)
class Post {
    Author author;
    String title;
    Content content;
}

Vavr

Do you remember Guava? It’s similar and as powerful as guava was/is. It brings functional features to the java world. Built from scratch, immutable and functional Collections API, way better Option class, Tuples, Either, Try, pattern matching… just start using it.

Spock framework

Do you write tests for your code? Just kidding, it’s obvious you do, right? JUnit 4/5 is cool, you can use it with other fancy libraries like Mockito, PowerMock, AssertJ, or even go one step further and switch to TestNG. But, what if I tell you to simply remove all those dependencies, add groovy support and Spock Framework? This framework is in my opinion, the best testing framework existing right now! With the power of groovy DSL, tests in Spock are elegant, powerful, easy to read and understand.

// JUnit 4, AssertJ, JUnitParams
@Test
@Parameters({
    1, 2, 3
    -1, -2, -3
    -1, 1, 0
    0, 0, 0
    1, -1, 0
})
public void addingTwoNumbers(int first, int second, int expectedResult) {
    // when adding numbers
    int result = calculator.add(first, second);
    // then 
    assertThat(result).isEqualTo(expectedResult);
}
// Spock :)
def 'adding two numbers'() {
    when: 'adding numbers'
        def result = calculator.add(first, second)
    then:
        result == expected
    where:
        first | second | expected
            1 |      2 |        3
           -1 |     -2 |       -3
           -1 |      1 |        0
            0 |      0 |        0
            1 |     -1 |        0
}

IntelliJ IDEA


The IDEs King. If you are using anything else for Java development, try IntelliJ for a week or two. It has free Community Edition version. I bet you will not go back to this sad Eclipse (or NetBeans, really..?). Even if you are some Vim wizard, just give it a try (it has a built-in vim editor anyway). JetBrains’s IDE can be used totally mouse-free, it has super fast searching, great debugger, tons of plugins (for other languages too) and much more. Very comfortable tool and fast to work with.

Bonus tip

Move to Kotlin 🙂

 

Some links:
What’s new in Java 8
Java 8 to Java 11
Lombok
Immutability in Java
Vavr
Spock framework
JUnit vs Spock
IntelliJ IDEA
Kotlin
Java vs Kotlin fancy comparison