Search code examples
c#classabstract-classclass-design

No public members in abstract class


I'm constructing some code that interacts with a HTTP web service. To interact with it, you invoke "commands" on it, either with HTTP GET requests or with HTTP POST.

I want to create a base class (eg, ServiceCommand) that encapsulates and hides an HttpWebRequest object, but I'm not convinced I want it to offer any functionality publicly, only to subclasses.

Subclasses could be (for example) SearchCommand, or FetchCommand, and these would use the functionality offered by the protected methods in the base class.

Basically, my question is: Is it considered bad design to create classes that have only protected members, and no public ones.


Solution

  • General questions I ask myself with design:

    • What is it that this class IS. Remember that object oriented design is about objects. If you are creating a new object you need to be able to think about it as an individual entity (at least abstractly). If you are just providing functionality you might be better off creating an interface or extension methods.
    • Does this functionality already exist? No need to create a class to wrap a class that worked well.
    • Finally with private versus public - if you think that subclasses will need to access base class values create a protected member variable. This variable will work whether or not you have a public property in the base class. Once you do this - if you think the value would be useful externally, you can add a get/set in the base class. This ends up looking like:

      public abstract class BaseClass {
          protected object _member;
          public object MemberGet { return _member; }
      }
      
      public class InheritClass : BaseClass {
          // now the base class can "decide" to set the member or implement its own set rules
          public static void RoutineThatSetsMember(object value) { _member = value; }
      }
      

    I'm not sure if these are rules everyone uses but maybe it will help with general design (Or at least keep the conversation moving forward)!