Best practice to set large amount of properties in C# base class from derived class

1.7k views Asked by At

I'm working on refactoring some legacy code, and have a large set of data objects that share the same properties and fields.

I'm also doing some reading on refactoring and at first glance it looks like I should use Extract Superclass. Is this a good idea when all I'm combining are properties? I mean they're really just fields with methods auto created so if we're talking about combining GetXYZ functionality that fits...?

With that in mind, let's assume all my objects share 5 common properties:

public string Name { get; private set; }
public string Status {get; private set; }
public int IDNumber { get; private set; }
public int LocationID { get; private set; }
public Location LocationObj { get; private set; }

What's the best way to set these from the subclasses? Also I'll change the private set to protected set.

1) Should I pass in the values/object and set the base class properties in each subclass constructor? This has some code duplication

2) Pass in the parameters and have the derived class call the base class constructor?

3) Create a protected method on the base class like SetBaseProperties? that takes all of them as parameters? (This seems a lot like #2 except a method vs ctor)

Any other methods I'm not aware of?

1

There are 1 answers

1
Cyral On BEST ANSWER

Method #1 is not a good idea, as it can easily be simplified by letting the base class handle it as you suggest.

Method #2 would reduce the amount of repeated code you need to write, and would leave all of the logic in the base class.

public SubItem(string name, string status, int id, int locID, Location loc) : base(name, status, id, locID, loc)

Method #3 is essentially the same idea, as you said, but using a constructor as opposed to a method guarantees these properties will be set. (You could easily forget to call the method).

Using properties and method #2 is your best bet. If your base class is just used to hold these common properties, and isn't used, remember to mark it abstract so it can't be instantiated. (Only implemented by derived classes)

If you have ReSharper, you can press Alt-Insert, C to create the derived constructor in your derived class. (I'm fairly certain VS does not have this feature by default)