Skip to content

Suggestion for the SelfValidating abstract class #35

Description

@ivdmeer

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions