projectlombok / lombok

Very spicy additions to the Java programming language.
https://projectlombok.org/
Other
12.82k stars 2.38k forks source link

[FEATURE] Make it possible to configure the access level of toBuilder #2746

Open kobiakov opened 3 years ago

kobiakov commented 3 years ago

Builder(toBuilder = true) is a great feature for making copies of large objects, modifying them along the way.

The method is convenient when practicing "rich domain models", more or less like this (very sketchy code ahead):

@Builder(toBuilder = true)
@Value
class Garage {
    ...
    Garage parkCar(Car car) {
         Garage copy = toBuilder().addCar(car).build();
         copy.checkInvariants();
         return copy;
    }

    private void checkInvariants() {
        if (this.parkedCars.size() > this.capacity) {
             throw new TooManyCarsException();
        }
    }
}

The problem is that currently there's no way to reduce visibility of #toBuilder(). Which defeats the point in a way, making it possible to construct an object in an illegal state (from the business logic point of view), bypassing the "official" ways of construction.

Adding a modifier, something like @Builder(toBuilder = true, toBuilderAccess = AccessLevel.PRIVATE), would be very beneficial.

P.S.: Thanks for the great job you are doing and all the effort! :)

grimly commented 3 years ago

You may check your invariants in the constructor. The only issue then is that you have to write the constructor yourself.