DEV Community

Discussion on: "Builder Pattern" generator for Java

Collapse
 
michelemauro profile image
michelemauro • Edited

Interesting tool. It's a pain to write these things by hand.

However, a note (or you may call it a feature request): with these templates, there is no check done by the builder that all or a mandatory subset of parameters have been given a value. You could use Optional<> to encode arguments that may not be necessary to construct the object; after all, one of the use cases of the Builder pattern is managing construction-time validation of the constructor arguments.

Another idea: there is at least another implementation style for the pattern; the one in which each step is encoded in a Class (or better, an Interface) so that the user must follow a precise call sequence in building the object. I.e:


class Point { 
  final int x, y; 
  private Point(int x, int y) {
    this.x = x; this.y = y;
  }

  static class PointY {
    final int x;
    PointY(int x) {
      this.x = x;
    }
    Point py(int y) {
      return new Point(x, y);
    }
  }

  static PointY px(int x) { 
    return new PointY(x); 
  } 
};

The Point class can only be instantiated in this way:

Point pt= Point.px(42).py(20);

This style may be useful when you want to thightly constrain how an object is created.

Collapse
 
moaxcp profile image
John Mercier

I like the idea of using Optional but I thought it caused problems when declaring a field as Optional. Was this something in Effective Java? I'm not so sure it is an issue but it is possible to wrap the object in the getter instead.

Collapse
 
riversun profile image
riversun

Thanks for your helpful comments.

I added @NotNull annotation to specify required properties and not required ones.
They are used for null checks in build methods.
What do you think?
The tool works with @Required and @NonNull as aliases for @NotNull as well.

Your "Another idea" is also interesting as a design that forces the coder to set the required parameters in order.

Best.