Should a parent class reference child classes?

Good morning,

I have inherited some inherited code at work, and it uses a rather unusual design pattern. The only link I could find on the forums in a similar fashion was here . The situation is that the original designer has a generic parent class (not abstract) that has a static factory method that directly references child classes.

Here is an example of this coding style found in several places in legacy code:

public static LoggerFactory getLoggerFactory(LogType type) { switch (type) { case LOG4J: return Log4JLoggerFactory.getInstance(); case LOGBACK: return LogBackLoggerFactory.getInstance(); default: throw new RuntimeException("No logger factory defined for type " + type); } } 

Where Log4JLoggerFactory and LogBackLoggerFactory extend LoggerFactory.

It seems to me that this is really alien to me, but before I significantly changed the code, is there any purpose or benefit for this design template (is there even a formal name for it)?

Any thoughts or advice are appreciated. Thanks!

EDIT: after reading Yishai's answer, I thought for a link to a Wikipedia article on a strategy template . Thank you all for your answers!

+3
source share
4 answers

This is a very standard template in Java and a general way to implement a strategy template. You see it in the standard API all the time (calendar vs GregorianCalendar, NumberFormat vs DecimalFormat, etc.).

Given that with Injection Dependency all the rage, such a template can really be replaced by a dedicated Factory class with a dedicated Factory interface, but in the absence of a larger constructive reason, I believe that the example you give is a very reasonable design choice.

+11
source

This is good practice and is called the Factory Method .

The advantage is that you return some specific implementation, but hide it through a common interface or base class. Thus, the client is not concerned about implementation details, but works with the most basic class.

+4
source

Maybe they configured this way to use Log4J in one environment and Logback in another? I know that sometimes developers prefer the tool for local development, but when the time comes for deployment, you need to use everything that the company approves / approves of.

0
source

Whether this is good or bad practice depends on the situation. For example, when the β€œparent” knows how to create all the children, this can be good practice. When the parent does not know this, this solution will only cause problems.

Testability is another problem: if a parent has many children, it can be difficult to create a parent separately from the children, but again it depends.

0
source

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


All Articles