简体   繁体   中英

Composition vs Inheritance

I have a Validator interface with one method signature: public List<ParameterError> validateParameters(Parameters parameters); Various classes implement this interface.

There are also some common methods like isInteger , isInRange , etc. Should I have these methods in a ValidationHelper and use composition in the classes implementing the Validator interface, or should I make Validator an abstract class, put these methods there and use inheritance instead of composition?

I am assuming isInteger , isInRange etc. can be used even outside of the Validator classes if they are implemented generically. In that case, they should go into a separate util class, and that class should simply be called Utils rather than ValidationHelper . Classes/methods should always be named in the broadest context where you can use them.

Your helper methods are good candidates for static methods because they are pure functions and they are not expected to be polymorphic. You should use a utility class and put all such functions in it. This results in the least coupling: neither composition, nor inheritance; just pure dependency on the methods themselves.

I'd prefer composition over inheritance since the classes implementing Validator may not necessarily share an is-a relationship. They're more likely to be interested in the methods provided by the Validator interface.

Also, is it not possible to have the generic ( isInteger etc) methods implemented in the interface Validator and marked final ? They could even be made made static along the lines of this question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM