Spasitel
Spasitel

Reputation: 169

Limit class property size

I'm looking for a way to limit the size of a class properties. Users can create new instances and I want to limit that some String property must have from n to m characters, or another Integer property must be a whole number from some range.

I haven't found any way to do this in the class definition, do I need to define my methods like:

public String checkInput (String input, int length) {
   if (input.length() > length) {
      return input.substring(0, length);
   } else return input;
}

Upvotes: 0

Views: 781

Answers (4)

osigida
osigida

Reputation: 23

Sounds like a job for bean validation: https://beanvalidation.org/2.0/spec/#builtinconstraints like @Min @Max for integer, @Pattern for strings

Upvotes: 0

roeygol
roeygol

Reputation: 5048

You can throw this exception inside your if condition:

throw new InvalidParameterException(MessageFormat.format("Insufficient param {0}!", param)));

Upvotes: 3

GhostCat
GhostCat

Reputation: 140623

The OOP way: define your own class to express that type, like:

public abstract class LengthRestrictedString {
  abstract int getMaxLength(); 

  private final String content;
  protected LengthRestrictedString(String content) {
    if (content!=null) {
     if (content.length() > getMaxLength()) {
       throw some exception;
     }
     this.content = content;

And then you can create specific subclasses that implement that abstract method to give a specific length, like:

public class PropertyString extends LengthRestrictedString {
  @Override 
  final int getMaxLength() { return 25; }
  ... constructor

or something similar. Now you can use the class PropertyString in all places where you want/expect such length restricted strings.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522751

Perhaps you could perform checks in the constructor, when the object is being instantiated. And you could make the fields final so that the user cannot alter them after the constructor finishes. Something like this:

public class yourClass {
    private final String data;

    public yourClass(String input) {
        data = input.substring(0, 100);
        // maybe log that the input is being truncated

        // or maybe throw new IllegalArgumentException
    }

    public String getData() {
        return data;
    }

    // no setter = data is immutable
}

In the example above, the string data is limited to a max size of only 100 characters. You could also throw an exception from the constructor, if you want to block the object from being created from a too-large input.

Upvotes: 0

Related Questions