buckpal icon indicating copy to clipboard operation
buckpal copied to clipboard

Suggestion for the SelfValidating abstract class

Open ivdmeer opened this issue 2 years ago • 2 comments

Hi,

I've read your book Get Your Hands Dirty on Clean Architecture and I liked it very much. In your book you showed an interesting class called SelfValidating which inspired me. I wanted to thank you for it and share my thought on this.

I have refactored this abstract class io.reflectoring.buckpal.common.SelfValidating into an interface that other classes can implement. The Interface version has a default method validateSelf that works the same as your version of the abstract class. By using this interface you're able to perform a validateSelf call and still be able to extend another class if that is required.

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public interface SelfValidating<T> {

	/**
	 * Evaluates all Bean Validations on the attributes of this
	 * instance.
	 */
	default void validateSelf() {
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		Validator validator = factory.getValidator();

		Set<ConstraintViolation<T>> violations = validator.validate((T) this);
		if (!violations.isEmpty()) {
			throw new ConstraintViolationException(violations);
		}
	}
}

Example class implementing this interface:

class Example implements SelfValidating<Example> {

	@NotBlank
	private final String name;

	public Example(String name) {
		this.name = name;
		validateSelf();
	}

	public String getName() {
		return name;
	}
}

Kind regards.

ivdmeer avatar Oct 28 '22 13:10 ivdmeer

Hey 👋,

nice idea! You might consider building the ValidatorFactory only once.

See: https://github.com/thombergs/buckpal/issues/33

benjaminknauer avatar Oct 28 '22 13:10 benjaminknauer

Thanks for the tip. I Will check to see if i can make it work.

ivdmeer avatar Oct 29 '22 17:10 ivdmeer