Andreas Wenger
unread,May 11, 2013, 2:09:48 PM5/11/13Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to project...@googlegroups.com
Hi,
Let me first say that Lombok is great. I especially love the withers that we recently discussed on, they are working like a charm.
My question for today: What is the best way in Lombok to check the validity of the fields within a class? I am aware of the @NonNull annotation, which is applied to the generated constructors and setters, but is there a more general approach?
Here is an example of a class using Lombok:
public class Canvas {
@NonNull private String title;
private int width;
private int height;
@NonNull private Color background;
public Canvas(String title, int width, int height, Color background) {
if (title == null || background == null)
throw new IllegalArgumentException();
checkWidth(width);
checkHeight(height);
this.title = title;
this.width = width;
this.height = height;
this.background = background;
}
private static void checkWidth(int width) {
if (width < 800)
throw new IllegalArgumentException("width must be >= 800");
}
private static void checkHeight(int height) {
if (height < 600)
throw new IllegalArgumentException("height must be <= 600");
}
public void setWidth(int width) {
checkWidth(width);
this.width = width;
}
public void setHeight(int height) {
checkHeight(height);
this.height = height;
}
}
I want to ensure that the width is always >= 800 and the height is always >= 600. As you can see, there are two problems: I have to reimplement the constructor and both setters, which is again lots of boilerplate code that could be avoided.
What I'd like to see is something like this:
public class Canvas {
@NonNull private String title;
@Checked private int width;
@Checked private int height;
@NonNull private Color background;
private static void checkWidth(int width) {
if (width < 800)
throw new IllegalArgumentException("width must be >= 800");
}
private static void checkHeight(int height) {
if (height < 600)
throw new IllegalArgumentException("height must be <= 600");
}
}
The (imaginary) @Checked annotation tells Lombok to execute the checkXxx(...) method when the field xxx is modified (constructor + setters). If not there, Lombok could generate a warning. There could also be a @Checked annotation on the class, which calls a check(...) method including all fields.
Is something like this planned for the next releases? Are there better solutions? Thanks for sharing your opinion.
Bye,
Andi