Question

So, this is a question of coding style more or less. I'm using Bean Validation here but the idea is the same for any interface that has simple implementations that aren't likely to get changed all that often.

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PhoneNumber.PhoneNumberValidator.class)
@Documented
public @interface PhoneNumber {
    String message() default "Must Be A Valid Phone Number";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};



    public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber, String>{

        public void initialize(PhoneNumber arg0) {}

        public boolean isValid(String phoneNumberStr, ConstraintValidatorContext unused) {
            return phoneNumberStr.replaceAll("[^\\d|x]", "").matches("\\d{10,12}(x\\d+$)?");
        }

    }

}

So, PhoneNumberValidator is the implementation of this particular validator (or producer method or interceptor, etc.) and there isn't much likelihood that we would change the implementation very often.

Is this a good way to provide cohesion to my code by putting the implementation and the interfaces close by or is this a code smell that is tightly coupling two pieces of code that shouldn't be coupled?

Have you been on projects that did things like this? If so, did it make things better or worse? If not, would you find this practice confusing?

Community Wiki'd since it's asking opinions.

Was it helpful?

Solution

I will often nest samll utility classes where they are being used. I think this is more straight forward than a producer because it is available in the same file and often involves less function calls. My "opinion" and practice has been similar to yours.

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