Question

Suppose you're concerned with clarity of your code and would like to make sure users of your api are crystal clear as to how objects are created. You make them do things like

new MomentInTime(new DayOfMonth(15), new HourOfDay(10), new MinuteOfHour(49), new SecondOfMinute(0));

Where each class DayOfMonth, HourOfDay is pretty much identical to one another, a value store of some kind.

Now, when the time comes for you to use the value, using Java's Calendar, should value be illegal, we will get some kind of RunTimeException. Great.

Now .. Is it possible for us to set up Min, Max boundaries in our IDE (Eclipse or Intellij) that would warn us that value we're about to send to a method will result in an error?

Is there a plug-in and an annotation that would work together that would allow for such a warning?

Something along the lines of @Boundaries {low=1, high=31} along with IDE actually recognizing it would be great.

Please let me know if something like this exists.

Was it helpful?

Solution

Have a look at Contracts for Java. It does have a rudimentary integration into Eclipse.

interface Time {
  ...

  @Ensures({
    "result >= 0",
    "result <= 23"
  })
  int getHour();

  @Requires({
    "h >= 0",
    "h <= 23"
  })
  @Ensures("getHour() == h")
  void setHour(int h);

  ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top