简体   繁体   中英

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.

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

This is a question regard to the difference between "Is A" and "Has A".

Regards to "Is A", if class B inherits from interface A or class A, it is means B is one type of A, B should has the same behavior as A has, while these behaviors are defined by public member functions.

As "Has A", Class B just want to use the implementation of Class A, so B will hold the reference to A, instead of inheriting from A.

so for your case, it is a "Has A" relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM