dimanche 3 mai 2020

Should I avoid using annotations?

In my project I’m loading configuration from a json file (using gson) and as you probably know, missing fields will be populate with an empty string.

Some of the fields are mandatory and other must be greater then X, and I want to validate it.

The simple (and ugly) way is to use if condition for each property, like:

if (StringUtils.isEmpty(sftpConfiguration.getHostName)) {
   logger.error (“hostName property is mandatory”);
  // etc.
}

but, I have more than one field and more and more properties will added in the future, therefore I built two annotations, called NorNullEmpty and GreaterThen (with value property) and I run throw the fields like this:

public static boolean validateWithAnnotation(Object object) throws IllegalAccessException {
    boolean result = true;
    Field[] classFields = object.getClass().getDeclaredFields();

    for (Field field : classFields) {
        if (field.getAnnotation(NorNullEmpty.class) != null) {
            if (field.getType() == String.class) {
                field.setAccessible(true);
                String value = (String) field.get(object);
                if (StringUtils.isEmpty(value)) {
                    result = false;
                    logger.error("Property {} is mandatory but null or an empty.", field.getName());
                }
                field.setAccessible(false);
            } else {
                logger.warn("@NorNullEmpty annotation is working on String type only.");
            }
        } else if (field.getAnnotation(GreaterThan.class) != null) {
            Class<?> fieldType = field.getType();
            if (fieldType == long.class || fieldType == Long.class) {
                field.setAccessible(true);
                Long val = field.getLong(object);
                if (val <= field.getAnnotation(GreaterThan.class).value()) {
                    result = false;
                    logger.error("Property {} value is {} and it must be greater than {}.", field.getName(), val, field.getAnnotation(GreaterThan.class).value());
                }
                field.setAccessible(false);
            }
        }
    }

    return result;
}

When I did a code review with a collage he very afraid from the annotations use, “it’s very risky and very expensive cost”..

I’ll be glad to know what you think, should I use a simple-stupid if for each field? continue with the reflection? or I should validate the fields using other way?

Note: NOT using Spring / Hibernate.





Aucun commentaire:

Enregistrer un commentaire