Lombok: [FEATURE] make builder class and methods also private if constructor is private

Created on 12 Apr 2020  路  2Comments  路  Source: projectlombok/lombok

Describe the feature
When having this:

public class User {

@Builder
private User(String name, Task task){

}
}

or this

public class User {

@Builder
private static User build(String name, Task task){

}
}

then lombok generates public generated builder classes (methods) instead of private.

Lombok should look at the constructor or static method defined visbility (for example, private or public) and use this for its builders.

Most helpful comment

Disclaimer: I'm not a Lombok team member, so just an opinion here.

Sometimes you want the builder to be the only way of instantiating your class, together with customizing the fields of the builder. In this case, you would do exactly that: define a private constructor and put @Builder on it.
So there is a use case for the current behavior, too.
It's difficult to decide which use case is the more common one.

However, changing Lombok's behavior here would be a breaking change. Furthermore you can use @Builder(access = AccessLevel.PACKAGE) to set the access level. So although your request sounds reasonable, I think it's better to stick with the current behavior.

All 2 comments

Disclaimer: I'm not a Lombok team member, so just an opinion here.

Sometimes you want the builder to be the only way of instantiating your class, together with customizing the fields of the builder. In this case, you would do exactly that: define a private constructor and put @Builder on it.
So there is a use case for the current behavior, too.
It's difficult to decide which use case is the more common one.

However, changing Lombok's behavior here would be a breaking change. Furthermore you can use @Builder(access = AccessLevel.PACKAGE) to set the access level. So although your request sounds reasonable, I think it's better to stick with the current behavior.

Agree with Jan. There is a valid use-case for the current behaviour, and a way to change it, so there is no sense in breaking backwards compatibility

Was this page helpful?
0 / 5 - 0 ratings