C# Inheritance – Best Practices When Inheriting Static Classes Isn’t Possible

cclass-designinheritancerefactoring

I am developing a project in C# and due to a design decision it is not possible to have a static class inherit another static class. But I have, in my opinion, a case where this would make sense.

I have a music player which is able to play music from many different music sources: local files, YouTube, SoundCloud, Jamendo, etc. I have currently one static class for each of these sources with static methods such as retrieving the top tracks, searching for tracks, etc.

Naturally, a lot of code is shared among all these classes so I wanted to refactor and put all common code into a more generic MusicSource class. But C# doesn't allow me to do that.

What would be the best practice here? I want to get rid of all my redundant code and make it easier to create new music sources.

Best Answer

Those "music source" classes sound more like non-static classes which you happen to only want one instance of. They are two different things!

Here are some reasons why you might want to make them non-static:

  • If they have (or might eventually have) some internal state. e.g. Cached login credentials, or cached lists of the top 10 tracks. Stateful static classes are a bad idea! They are basically a poor implementation of a singleton.
  • If you're going to have a lot of music sources, you may well want to perform some actions on all of them. e.g. Find a particular track from any source. With static classes you're going to need a line for each class. If you've got non-static classes you can just loop over a collection of them.

There's a great answer here which gives more reasons and goes into more detail.

Related Topic