1

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?

Ani
  • 111,048
  • 26
  • 262
  • 307
Oleg Oshkoderov
  • 500
  • 1
  • 4
  • 17

2 Answers2

6

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).

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Ben, inheritance is always has violation of the Open-Closed princilpe, as sub classes couldn't be fully protected agains't changes in base class. But this isn't the reason to call it violation. So could you please clarify where is the dengerous exactly? – Oleg Oshkoderov Jun 20 '12 at 20:16
  • @Oleg: This isn't just "sub classes are not protected against changes in the base class". They shouldn't be, sub classes are strongly coupled to the base class. What's going on here is that the base class is using techniques for generic programming (pure virtual functions, virtual dispatch) without adding any flexibility. The base class cannot be used with anything that isn't a file, so the abstraction has no benefit. – Ben Voigt Jun 20 '12 at 20:49
0

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.

Colin D
  • 5,641
  • 1
  • 23
  • 35