When to hide the inheritance hierarchy in a particular class?

Whenever I am in a situation where I have a factory returning an implementation of an abstract base class for the user based on some parameter of the "low level" type, such as a protocol or external resource format, I am always tempted to convert the abstract class to a concrete class with internal factory strategy so that users can simply pass the implementation type to the constructor and work directly with the base class.

I noticed that the .Net infrastructure decided to implement Socket this way (instead of creating a DatagramSocket, you pass SocketType when building). What are some guidelines for making decisions when it is acceptable to smooth a hierarchy into one particular class?

+6
source share
2 answers

I think the point is, "how much low-level information should a client know?"

If you choose the first solution (abstract base class), you hide more detailed information about the client class. Thus, the client can completely ignore low-level details (protocol, external resource format). When the goal is to completely hide implementation details and types used inside this implementation, I prefer this approach.

Otherwise, if the client already knows some details of the low-level implementation (for example, the client knows that the socket it will use is UDP, and he also WANTS to know this information), then the abstract base class approach may be replaced by an internal "strategy" factory ".

+3
source

In the spirit of “prefer composition over inheritance”, I always choose the strategy + factory method of inheritance. This gives me several advantages: * most of the time, each strategy can be tested in isolation, without worrying about the class that will use it. * in the same vein, a client class can be tested with a mock strategy * strategies can be designed so that they can be built using a decorator template, for example, which provides greater flexibility without causing an explosion of subclasses.

In general, if the outer semantics of all your subclasses are the same (as they should be), follow the strategy route.

+2
source

Source: https://habr.com/ru/post/886414/


All Articles