DEV Community

Discussion on: Casting stinks. Generic classes are worse.

Collapse
scotthannen profile image
Scott Hannen • Edited on

This answer is going to be a little bit fuzzy and vague. One suggestion is to start by writing a single implementation end-to-end without using inheritance, then another, and then apply the inheritance if and when it makes sense. Starting with inheritance often paints us into a corner.

In the case of a class like this:

public class SedanAssemblyLine : VehicleAssemblyLine
{
  public string SedanMakersUnionType { get; set; }
  public abstract Vehicle Build(VehicleAssemblyLineInstructions instructions)
  {
    // TODO: Implementaton here
    throw new NotImplementedException();
  }
}

Inheriting from VehicleAssemblyLine suggests polymorphism. But if the class is going to be cast as its base type then where will the SedanMakersUnionType fit in?

Also, we typically use a factory to create a class when we need it. That means that in any given scenario we need one instance of a specific class. If we're trying to create numerous instances of multiple objects of varying types, what needs them?

I realize it's just an example. But perhaps what I'm trying to say is that it's better if we start from something simple that achieves one instance of exactly what we need when we need it. This sort of problem happens when we work the other way, trying to create a "generic" solution for a requirement that hasn't been clearly defined.

I understand because I've gotten to the same point many, many times.

I hope the title of this post - The Generic Rabbit Hole of Madness - doesn't seem derogatory, because that's not the intent. But this seems like a perfect case of that. I wrote the post because I've done it so many times.

Collapse
anotherdevblog profile image
Matthew Watkins Author

Yeah I saw that post come out a few days after mine and immediately added it to my Pocket list-- thanks! :)