Home  /  Questions  /  Question



Sep 02, 2010


How to get a better class design

Hi

I have Request classes, say X, Y, Z. These classes will have some common attributes and some unique attributes.
I tried to put the common attributes in an abstract class (AbstractRequest) and subclasses (XRequest, YRequest, ZRequest). 

But the problem I face is this: while creating instances, I need to create instances of subclasses and not abstract class.
This is not generic.  Any suggestions as to what I can do?

OO



1,128   99.9
Sep 02, 2010

 Hi,

This is usually what I do, I try to use interfaces a lot since it makes it
easier for me to switch out any implementation details. So to speak, the
interface specifies the contract. I hope this is what you're looking for, if
not, don't hesitate to ask again
public interface IRequest {  
      string GenericProp1 {get; set;}  
      int GenericProp2 {get;set;}  

      void GenericMethod();  
    }  

Now, If some code is used in most of the Request implementations you
could create an abstract class that implements this code.

public abstract class BaseRequest : IRequest {  
     // Implement some code specific to all that
     // will use the abstract BaseRequest class.
   }  

Next step is to implement the concrete classes.

public class RestRequest : BaseRequest {
  // Implementation goes here
  }  

public class WcfRequest : BaseRequest {  
    // Implementation goes here
  }  

The final step is to call this code somewhere to use it.

public void SomeMethod() {
IRequest request = new RestRequest();
Validate(request)
}
public void Validate(IRequest request) {  
   // Do some stuff on the request object.  
 }  

The next step would be to use dependency injection to
and let the DI framework of your choice inject the class' dependencies
instead of using the new keyword to create your objects.

Good Luck!