Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion for the SelfValidating abstract class #35

Open
ivdmeer opened this issue Oct 28, 2022 · 2 comments
Open

Suggestion for the SelfValidating abstract class #35

ivdmeer opened this issue Oct 28, 2022 · 2 comments

Comments

@ivdmeer
Copy link

ivdmeer commented Oct 28, 2022

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.

@benjaminknauer
Copy link
Contributor

Hey 👋,

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

See: #33

@ivdmeer
Copy link
Author

ivdmeer commented Oct 29, 2022

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

@ivdmeer ivdmeer closed this as completed Oct 29, 2022
@ivdmeer ivdmeer reopened this Oct 29, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants