Skip to content

Instantly share code, notes, and snippets.

@ufuk ufuk/LazyDeveloper.java
Last active Jun 27, 2019

Embed
What would you like to do?
Just another reason to why you shouldn't use Lombok, in another saying another reason to why you should write unit tests: You have two fields in your class. Fields are in the same type. You use @AllArgsConstructor to auto-generate your all args constructor. It works for a moment, until you change the order of the field.
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class LazyDeveloper {
private String firstName;
private String lastName;
}
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
public class LazyDeveloperTest {
@Test
public void testAllArgsConstructor() {
LazyDeveloper lazyDeveloper = new LazyDeveloper("John", "Doe");
assertThat(lazyDeveloper.getFirstName(), equalTo("John"));
assertThat(lazyDeveloper.getLastName(), equalTo("Doe"));
}
}
@koraytugay

This comment has been minimized.

Copy link

commented Oct 7, 2016

Hi Ufuk, what is the problem here?

@ufuk

This comment has been minimized.

Copy link
Owner Author

commented Oct 7, 2016

If you change the order of fields, for example:

...
@AllArgsConstructor
public class LazyDeveloper {

    private String lastName;

    private String firstName;

}

Code will be compiled but test will fail, so your expectation will not be satisfied. Because first param of the newly auto-gerenated constructor will be "lastName".

I think that is a great risk when you use Lombok but don't write unit tests.

@Kidlike

This comment has been minimized.

Copy link

commented Jun 1, 2018

sorry for the grave-digging, but I just wanted to clarify for anyone that stumbles upon this.

Your "problem" could be easily replicated with plain java:

public LazyDeveloper(String lastName, String firstName){}
public LazyDeveloper(String firstName, String lastName){}

There's no signature change; code will still compile fine; you still need unit tests.
I understand that it's simpler to do such mistakes with Lombok, but,
such constructors are dangerous anyway in large projects, they should be avoided regardless of using Lombok or not.
It also goes without saying that you need junit tests regardless of using Lombok or not :)

@ufuk

This comment has been minimized.

Copy link
Owner Author

commented Aug 23, 2018

@Kidlike great addition, thank you. I encountered such a situation when using Lombok and just noted it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.