Search code examples
javavalidationpojo

Java - Validation of values in setters


I think I might already know the answer but have chosen to ask to have it clarified.

I have a simple POJO with private variables, getters and setters.

Some of these are String variables where I only want to allow certain Strings to be used when they are initialised.

My question is simply - Should I put this validation in the POJO - perhaps in one of the setters or should this validation take place elsewhere before the setter is called?

The example below should only allow values gzip or compress

private String compressionType = null;

public void setCompressionType(String compressionType) {

    if( ! ( compressionType.equals("gzip") ) || ( compressionType.equals("compress") ) )
    {
        compressionType = "gzip"; //a chosen default
    }

    this.compressionType = compressionType;
}

Effectively setting a default value if someone types in "fred" or something daft.

My reason for asking this is purely because where I work I see this kind of thing quite often, it is accepted here but I'm not sure it should be.


Solution

  • The usual way of doing this now enum is a first class type is to use an enum:

    private CompressionType compressionType = null;
    
    public enum CompressionType {
        Compress,
        GZip;
    }
    
    public void setCompressionType(CompressionType compressionType) {
        this.compressionType = compressionType;
    }
    

    However, if the validation is heavy you could consider a factory or a decorator.