Request for advice about class design, inheritance/aggregation - c#

I have started writing my own WebDAV server class in .NET, and the first class I'm starting with is a WebDAVListener class, modelled after how the HttpListener class works.
Since I don't want to reimplement the core http protocol handling, I will use HttpListener for all its worth, and thus I have a question.
What would the suggested way be to handle this:
Implement all the methods and properties found inside HttpListener, just changing the class types where it matters (ie. the GetContext + EndGetContext methods would return a different class for WebDAV contexts), and storing and using a HttpListener object internally
Construct WebDAVListener by passing it a HttpListener class to use?
Create a wrapper for HttpListener with an interface, and constrct WebDAVListener by passing it an object implementing this interface?
If going the route of passing a HttpListener (disguised or otherwise) to the WebDAVListener, would you expose the underlying listener object through a property, or would you expect the program that used the class to keep a reference to the underlying HttpListener?
Also, in this case, would you expose some of the methods of HttpListener through the WebDAVListener, like Start and Stop, or would you again expect the program that used it to keep the HttpListener reference around for all those things?
My initial reaction tells me that I want a combination. For one thing, I would like my WebDAVListener class to look like a complete implementation, hiding the fact that there is a HttpListener object beneath it.
On the other hand, I would like to build unit-tests without actually spinning up a networked server, so some kind of mocking ability would be nice to have as well, which suggests I would like the interface-wrapper way.
One way I could solve this would be this:
public WebDAVListener()
: WebDAVListener(new HttpListenerWrapper())
{
}
public WebDAVListener(IHttpListenerWrapper listener)
{
}
And then I would implement all the methods of HttpListener (at least all those that makes sense) in my own class, by mostly just chaining the call to the underlying HttpListener object.
What do you think?
Final question: If I go the way of the interface, assuming the interface maps 1-to-1 onto the HttpListener class, and written just to add support for mocking, is such an interface called a wrapper or an adapter?

I'll answer your last question first: a class is an adapter if it implements some ITarget interface using a contained object matching some ISource -- an adapter from ISource to ITarget. In this case, there is no source interface, you're trying to add one in, so I'd call it a wrapper.
I'd be inclined to
Make a WebDavListener class which has all the methods it needs for its own behaviour, uses an HttpListener internally, and doesn't expose anything about that HttpListener.
If and when you need it, make IHttpListenerWrapper and HttpListenerWrapper as you suggest, and change the WebDavListener to take an IHttpListenerWrapper in its constructor. Assuming all the methods are the same, this should be a simple search-and-replace. You could even leave the original constructor in there and have it construct a wrapper and call the new constructor.
If and when you need it, make an IWebDavListener for it to implement, if you think you might want a dummy WebDAV listener for unit testing other things.
This sort of design issue is why I love refactoring tools like ReSharper: Extract Interface, Create Derived Implementation etc. make it much easier to make these sort of changes, so you can worry less about whether to do them now or later :-) (Assuming you are allowed to freely change the source later, of course, which depends how you're delivering things.)

Related

How should common references be passed around in an assembly?

I am trying to get rid off static classes, static helper methods and singleton classes in my code base. Currently, they are pretty much spread over the whole code, especially so for the utility classes and the logging library. This is mainly due to the need for mocking ability as well as object-oriented design and development concerns, e.g. extensibility. I might also need to introduce some form of dependency injection in the future and would like to leave an open door for that.
Basically, the problem I have encountered is about the method of passing the commonly used references around. These are objects that are used by almost every class in the code base, such as the logging interface, the utility (helper) class interface and maybe an instance of a class that holds an internal common state for the assembly which most classes relate to.
There are two options, as far as I'm aware. One is to define a class (or an interface) that stores the common references, a context if you will, and pass the context to each object that is created. The other option is to pass each common reference to almost every class as a separate parameter which would increase the number of parameters of the class constructors.
Which one of these methods is better, what are the pros and cons of each, and is there a better method for this task?
I generally go with the context object approach, and pass the context object either to an object's constructor, or to a method -- depending on which one makes the most sense.
The context object pattern can take a few forms.
You can define an interface that has exactly the members you need, or you can generate a sort of container class. For example, when writing loosely-coupled components, I tend to have each component I implement have a matching interface, so that it can be reimplemented if desired. Then I register the objects on a "manager" object, something like this:
public interface IServiceManager
{
public T GetService<T>();
public T RequireService<T>();
public void RegisterService<T>(T service);
public void UnregisterService<T>(T service);
}
Behind the scenes there is a map from type to object, which allows me to extremely quickly assemble a large set of diverse components into a working whole. Each component asks for the others by interface, and the manager object is what glues them together. (If you correctly author your components, you can even swap out one service for another while the process is running!)
One would register a service something along these lines:
class FooService : IFooService { }
// During process start-up:
serviceManager.RegisterService<IFooService>(new FooService());
There is more overhead with this approach than with the flat-interface approach due to the dictionary lookup, but it has allowed me to build very sophisticated systems that can be easily redeployed with different service implementations. (And, as is usual, any bottlenecks I encounter are never in looking up a service object from a dictionary, but somewhere else such as the database.)
You're going to get varied opinions, but generally passing a separate parameter to the constructor for each dependency is preferred for a few reasons:
It clearly defines the actual dependencies for a class - with a "context" you don't know which parts of the context are used without digging into the code.
Generally having a lot of parameters to a constructor is a design smell, so using constructor injection helps you sniff out design flaws.
When testing you can mock out individual dependencies versus having to mock an entire context
I would suggest passing as a parameter to the constructor. This has great advantage for both dependency injection and unit testability ( mocking).

How can I determine at runtime if an interface member is implemented?

I have an interface called IStructuredReader that reads some structured data from a file and displays it in a form. It has a member called Sync() that, when implemented, scans the data for a user-specified data pattern.
Some implementations of IStructuredReader don't have sync capability. Those implementations throw NotImplementedException for the Sync() method. I would like to be able to check for this method being implemented, so that I can dim the button on the form if it is not.
I can think of a number of ways that this could be done, all of which seem clumsy and complicated:
Separate the Sync method into its own interface, inherit it for those implementations that support the capability, and attempt to cast the reader object to it to identify the capability,
Write a NotImplementedAttribute, decorate the member with it, and check for the presence of the attribute using Reflection,
Add a HasSyncCapability boolean property to the interface.
Is there a canonical way this is done?
This sounds like you really should have two interfaces. Your Sync() method is obviously adding functionality over your base interface, which suggests that this is really a separate concern, as it's not a requirement of IStructuredReader. I would suggest adding a second interface for the types which support this, which would then be easy to check for in your view layer.
The canonical way is for the interface to expose the methods that will be implemented, so the cleanest solution I see is to create another interface called maybe Syncronizable with just that method. If your object implements that interface you know the method is there, and this is not clumsy at all. Using reflection or the extra attribute are indeed not as clean as solutions, but it doesn't mean you shouldn't go for those if it makes your life easier ;)

Is a proxy class the same as a class wrapper?

I have to access a legacy database that has "generic" tables in it and I do not have the authority to change it. Depending on the customer data that I'm working with, the relationships between the tables may differ. So, customerA may join to the order table by only their customer number while CustomerB may join to the order table by customer number and the date. CustomerC may not join to the order table at all but to a different table.
So, what I would like to do is to create an object graph for CustomerA and one for CustomerB and one for CustomerC. I thought about creating a wrapper class for each but have been researching proxies. That said, the examples that are written about Proxy classes make them look identical to a wrapper class. Thus my question, are proxy classes synonymous to wrapper classes.
Thank You.
No, they are not the same. Have a look at Proxy pattern and Wrapper pattern at Wikipedia.
Basically, a proxy is an object that looks the same as the original object (i.e. implements the same interfaces), but does something more.
Wrapper is an object that looks differently than the original object, but usually does the same.
There are a couple of ways of handling the problem at hand.
One is to map to a common domain model. This works fine if you have the same basic behavior, but might not serve you well in the particulars (different keys for different types of clients).
Another is to move the common bits down into a base class and then inherit for the different specifics in state (different properties) or the different behaviors (primary key only id, etc). Considering this is both differing behavior and state, this is a direction you can use.
Now, patterns. A proxy pattern is one where the new object can provide some of the behavior and state of another object, but is not the object. Think of it like what a person voting for you as a proxy means, and then relate it to software. I would not think of it like a wrapper, as a wrapper is normally used to present a different face from the underlying object. This can be due to the need to hide something in the underlying object or to add further behavior on top of the object. The proxy pattern will not help with the varying keys; Possible with the wrapper, although I am not convinced it is the simplest way to do this.
From wikipedia: "A proxy, in its most general form, is a class functioning as an interface to something else"
ProxyPattern
Proxy: is an "interface", it's a "blackbox", if you like, from which you request something and it gives you back what you want.
Wrapper: is a entity which basically hides a functionality by encapsulating, so hiding inside it a "real" component/another class/... by exposing to the caller its own methods, so the user of wrapper has no clue with which object it really works.
Hope this helps.
Regards.
Looking at the implementation a proxy and a wrapper class might be very similar. However the terms are often used in different meenings.
A proxy is an object that behaves like the real object, but isn't. Instead it forwards all calls to the real object, hiding the complexity of accessing the remote object. An example of proxy objects are the WCF clients genereated by Visual Studio. The client calls them as if they were the real service code, and the proxy handles the communication.
A wrapper is an object that for some reason hides another object. Usually this is done when interfaces are not compatible. An object with the right functionality, but the wrong interface, is wrapped in another object that translates the interface.

c# when to program to an interface?

Ok the great thing about programming to an interface is that it allows you to interchange specific classes as long as the new classes implement everything in that interface.
e.g. i program my dataSource object to an interface so i can change it between an xml reader and a sql database reader.
does this mean ideally every class should be programmed to an interface?
when is it not a good idea to use an interface?
When the YAGNI principle applies.
Interfaces are great but it's up to you to decide when the extra time it takes developing one is going to pay off. I've used interfaces plenty of times but there are far more situations where they are completely unnecessary.
Not every class needs to be flexibly interchanged with some other class. Your system design should identify the points where modules might be interchangeable, and use interfaces accordingly. It would be silly to pair every class with an additional interface file if there's no chance of that class ever being part of some functional group.
Every interface you add to your project adds complexity to the codebase. When you deal with interfaces, discoverability of how the program works is harder, because it's not always clear which IComponent is filling in for the job when consumer code is dealing with the interface explicitly.
IMHO, you should try to use interfaces a lot. It's easier to be wrong by not using an interface than by using it.
My main argument on this is because interfaces help you make a more testable code. If a class constructor or a method has a concrete class as a parameter, it is harder (specially in c#, where no free mocking frameworks allow mocking non-virtual methods of concrete classes) for you to make your tests that are REAL unit tests.
I believe that if you have a DTO-like object, than it's overkill to use an interface, once mocking it may be maybe even harder than creating one.
If you're not testing, using dependency injection, inversion of control; and expect never to do any of these (please, avoid being there hehe), then I'd suggest interfaces to be used whenever you will really need to have different implementations, or you want to limit the visibility one class has over another.
Use an interface when you expect to need different behaviours used in the same context. I.e. if your system needs one customer class which is well defined, you probably don't need to use an ICustomer interface. But if you expect a class to comply to a certain behaviour s.a. "object can be saved" which applies to different knids of objects then you shoudl have the class implement an ISavable interface.
Another good reason to use an interface is if you expect different implementations of one kind of object. For example if ypu plan an SMS-Gateway which will route SMS's through several different third-party services, your classes should probably implent a common interface s.a. ISmsGatewayAdapter so your core system is independent from the specific implementation you use.
This also leads to 'dependecy injection' which is a technique to further decouple your classes and which is best implemented by using interfaces
The real question is: what does your class DO? If you're writing a class that actually implements an interface somewhere in the .NET framework, declare it as such! Almost all simple library classes will fit that description.
If, instead, you're writing an esoteric class used only in your application and that cannot possibly take any other form, then it makes no sense to talk about what interfaces it implements.
Starting from the premise of, "should I be implementing an interface?" is flawed. You neither should be nor shouldn't be. You should simply be writing the classes you need, and declaring what they do as you go, including what interfaces they implement.
I prefer to code as much as possible against an interface. I like it because I can use a tool like StructureMap to say "hey...get me an instance of IWidget" and it does the work for me. But by using a tool like this I can programatically or by configuration specify which instance is retrieved. This means that when I am testing I can load up a mock object that conforms to an interface, in my development environment I can load up a special local cache, when I am in production I can load up a caching farm layer, etc. Programming against an interface provides me a lot more power than not programming against an interface. Better to have and not need than need and not have applies here very well. And if you are into SOLID programming the easiest way to achieve many of those principles sort of begins by programming against an interface.
As a general rule of thumb, I think you're better off overusing interfaces a bit than underusing them a bit. Err on the side of interface use.
Otherwise, YAGNI applies.
If you are using Visual Studio, it takes about two seconds to take your class and extract an interface (via the context menu). You can then code to that interface, and hardly any time was spent.
If you are just doing a simple project, then it may be overkill. But on medium+ size projects, I try to code to interfaces throughout the project, as it will make future development easier.

What are some advantages to using an interface in C#?

I was forced into a software project at work a few years ago, and was forced to learn C# quickly. My programming background is weak (Classic ASP).
I've learned quite a bit over the years, but due to the forced nature of how I learned C#, there are a lot of basic concepts I am unclear on.
Specifically, an interface. I understand the basics, but when writing an app, I'm having a hard time figuring out a practical use of one. Why would one want to write an interface for their application?
Thanks
Kevin
An interface says how something should work. Think of it as a contract or a template. It is key to things such as Inverson of Control or Dependancy Injection.
I use Structure Map as my IoC container. This allows me to define an interface for all of my classes. Where you might say
Widget w = new Widget();
I would say
IWidget w = ObjectFactory.GetInstance<IWidget>();
This is very powerful in that my code isn't saying necessarily what a Widget truely is. It just knows what a Widget can do based on the interface of IWidget.
This has some great power to it in that now that I am using an IoC container I can do a couple more nifty things. In my unit tests where I need to use a Widget I can create a mock for Widget. So say that my Widget does something very powerful by way of connecting to a database or a web service, my mock can simulate connecting to these resources and return to me stubbed data. This makes my test run faster and behave in a way that is more reliable. Because I am using StructureMap I can tell StructureMap to load the real implementation of my Widget during production use of my code and the mocked version of the Widget during testing either programatically or by configuration.
Also, because I am using an IoC container I can provide cool new features to my application such as writing three different ways to cache data. I can have a local developer box cache using a tool such as Lucene.NET for a local cache. I can have a development server use the .NET cache which runs great on one box. And then I can have a third option for my production servers use a cache layer such as MemCache Win32 or Velocity. As long as all three caching implementations conform to the same interface, their actual implementation doesn't concern me (or my code) at all. I simply ask StructureMap to go get the current environments implementation and then go to work.
If you follow Dependency Injection at all then interfaces come in handy here also with an IoC container such as StructureMap in that I can declare the usage of a class by way of an Interface in the constructor of my class.
public class Widget(IWidgetRepository repository, IWidgetService service) : IWidget
{
//do something here using my repository and service
}
And then when I new up an instance of Widget by way of StructureMap such as this
IWidget widget = ObjectFactory.GetInstance<IWidget>();
Notice that I am not specifying the repository or service in the constructor. StructureMap knows by way of the interfaces specified in the constructor how to go get the appropriate instances and pass them in too. This makes very powerful and clean code!
All from the simple definition of Interfaces and some clever usage of them!
One Simple Answer: Use interfaces to program against the contract rather than the implementation.
How could that possibly help? Starting to use interfaces will (hopefully) get you in the habit of coupling classes more loosely. When you code against your own concrete classes, it's easy to start poking the data structures without a strict separation of concerns. You end up with classes which "know" everything about the other classes and things can get pretty tangled. By limiting yourself to an interface, you only have the assurance that it fulfills the interface's contract. It injects a sometimes helpful friction against tight coupling.
The basic case is the "IWriter" case.
Suppose you are making a class that can write to the console, and it has all kinds of useful functions like write() and peek().
Then you would like to write a class that can write to the printer, so instead of reinventing a new class, you use the IWriter interface.
Now the cool thing about interfaces is you can write all your writing code, without knowing what is your writing target beforehand, and then can when the user decides (at runtime) weather he wants to write to the console or the printer, you just define the object as a console/printer writer and you don't need to change anything in your writing code, because they both use the same front end (interface).
An example. Consider an MDI application that shows reports, there's basically 2 different report types. A chart, and a grid. I need to Save these reports as PDF and I need to mail them to someone.
The event handler for the menu the user clicks to save a report to PDF could do this:
void ExportPDF_Clicked(...) {
if(currentDocument is ChartReport) {
ChartReport r = currentDocument as ChartReport;
r.SavePDF();
} else if(currentDocument is GridReport) {
GridReport r = currentDocument as GridReport;
r.SavePDF();
}
}
I'll rather make my ChartReport and GridReport implement this interface:
public interface Report {
void MailTo();
void SavePDF();
}
Now I can do:
void ExportPDF_Clicked(...) {
Report r = currentDocument as Report;
r.SavePDF();
}
Similar for other code that need to do the same operation(save it to a file,zoom in,print,etc.) on the different report types.
The above code will still work fine when I add a PivotTableReport also impelmenting Rpoert the next week.
IOC and Dependency injection have already been mentioned above, and I would urge you to look at them.
Largely, however, interfaces allow a contract to be specified for an object that doesn't require an inheritance model.
Lets say I have class Foo, that has functions x and y and property z, and I build my code around it.
If I discover a better way to do Foo, or another sort of Foo requires implementation, I can, of course, extend a base Foo class to FooA, FooB, MyFoo etc, however that would require that all Foos have the same core functionality, or, indeed that any future Foo creators have access to the base Foo class and understand its internal workings. In C#, that would mean future Foos could not inherit from anything else but Foo, as C# does not support multiple inheritance.
It would also require me to be aware of possible future states of Foo, and try not to inhibit them in my base Foo class.
Using an interface IFoo simply states the 'contract' that a class requires to work in my Foo framework, and I don't care what any future Foo classes may inherit from or look like internally, as long as they have fn x fn y and z. It makes a framework much more flexible and open to future additions.
If, however, Foo requires a large amount of core at its base to work that would not be applicable in a contract scenario, that is when you would favour inheritance.
Here is a book that talks all about interfaces. It promotes the notion that interfaces belong to the client, that is to say the caller. It's a nice notion. If you only need the thing that you're calling to implement - say - count() and get(), then you can define such an interface and let classes implement those functions. Some classes will have many other functions, but you're only interested in those two - so you need to know less about the classes you're working with. As long as they satisfy the contract, you can use them.
good article.
An interface is a contract that guarantees to a client how a class or struct will behave.
http://www.codeguru.com/csharp/csharp/cs_syntax/interfaces/article.php/c7563
This might be the clearest easiest way of explaining that I have come across:
"The answer is that they provide a fairly type-safe means of building routines that accept objects when you don't know the specific type of object that will be passed ahead of time. The only thing you know about the objects that will be passed to your routine are that they have specific members that must be present for your routine to be able to work with that object.
The best example I can give of the need for interfaces is in a team environment. Interfaces help define how different components talk to each other. By using an interface, you eliminate the possibility that a developer will misinterpret what members they must add to a type or how they will call another type that defines an interface. Without an interface, errors creep into the system and don't show up until runtime, when they are hard to find. With interfaces, errors in defining a type are caught immediately at compile time, where the cost is much less."
Couple of things, when you inherit from an interface it forces you to implement all the methods defined in the interface. For another, this is also a good way to bring in multiple inheritance which is not supported for regular classes.
http://msdn.microsoft.com/en-us/library/ms173156.aspx
Simple answer based on first principles:
A program is a universe with its own metaphysics (the reality/substance/stuff of the code) and epistemology (what you can know/believe/reason about the code). A good programming language tries to maximize the metaphysical flexibility (lets you make the stuff easily) while ensuring epistemic rigor (makes sure your universe is internally consistent).
So, think of implementation inheritance as a metaphysical building block (the stuff that makes up your little universe of code) and interface inheritance as an epistemic constraint (it allows you to believe something about your code).
You use interfaces when you only want to ensure that you can believe something. Most of the time that's all you need.
You mentioned having difficulty finding a practical use for interfaces.. I've found that they come into their own when building extensible applications, for example a plugin-based app where a third-party plugin must conform to specific rules.. These rules can be defined by an interface.
You could make it so that when the plugin is loaded, it must have an Init method that takes a class that implements IServices interface.
public interface IServices
{
DataManager Data { get; set; }
LogManager Log { get; set; }
SomeOtherManager SomeOther { get; set; }
}
public class MrPlugin
{
public void Init(IServices services)
{
// Do stuff with services
}
}
So.. If you have a class that implements the IServices interface, and then you instantiate it once, you can pass it to all the plugins upon initialisation and they can use whatever services you have defined in the interface.

Categories

Resources