I often see the code like this:

public abstract class AbstractDataReader
{
    public void Read()
    {
        var reader = new StreamReader(FileName);
        ........
    }

    protected abstract string FileName
    {
        get;
    }
}

public class DataReader : AbstractDataReader
{
    protected override string FileName
    {
        get { return "data.txt"; }
    }
}

As for me it seams as anti-pattern, as DataReader class has no logic, I can't use AbstractDataReader without inheriting from it, it's also weird that I have to inherit the class just to specify parameter and also I works slower then just putting that parameters through the constructor.

But I can't find the name of this anti-pattern.

Does anybody know it?

有帮助吗?

解决方案

Yes, it's an anti-pattern. The abstract class has already mandated how the derived class will work, there's no advantage here to a class hierarchy over a single class.

If the abstract class instead called a pure virtual function to get the StreamReader, it would make sense. Then different derived classes could attach to a file, or a network stream, or dynamically generated data.

The anti-pattern here is "violation of the Open-Closed principle" (the second part of SOLID).

其他提示

Yes/No.

To me this looks like an attempt to abstract setter injection, which I am not sure is a good idea. It makes things unclear and leads to the code posted, but setter injection itself is not an anti-pattern.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top