I am working in a project that has several modules made by different teams.
I must use the repositories and the code-first entity classes from other modules (referencing the dll), but I can't access the code and I can't modify it.
I want to protect myself from changes in the structure of the external code, and I want to add functionality to those classes.
What is the best approach?
I am thinking about making something like a service layer; get the external data, adding some functionality and parse to my own classes to avoid extra dependence on the external assemblies in my code.
If some day the external classes change, I only need to modify this service layer.
What do you think? Other ways for doing it? I can only change my module.
Thanks a lot!
The teams must work together!
It is a good idea to work against interfaces instead of concrete classes. Classes should implement different interfaces representing their different facets. Maybe the classes themselves can be split into smaller ones having only one responsibility.
See: Interface segregation principle.
See: Single responsibility principle.
If you are using only a portion of an object, there is no point in making you dependent on the whole object. If you work against an interface representing the very aspects of the class you are working with, it is less likely that changes on other parts will affect you. But the teams must sit together and define those interfaces.
I cannot come up with a sophisticated method that could better fit the situation but what you need is some kind of abstraction. You could create a wrapper object or this could be as simple as following:
public class MyType
{
// Your own implementation
// Properties
// And methods
public static MyType Create(TheirEntity entity)
{
// Create an instance of your type from their object
}
// Or provide a conversion operator, it could be implicit if you'd like
public static explicit MyType(TheirEntity entity)
{
// Implement a conversion here
}
}
If you still want to use repositories from external libraries, why don't you inherit from the classes you want to extend? If you don't need to add properties or fields, I'd use extension methods. Those would allow you to use your project specific functionality on external classes.
Related
This question already has answers here:
Interface vs Base class
(38 answers)
Closed 9 years ago.
what is the main utility of Interface. we know that we can implement dynamic behaviour using interface but i guess it is not only the utility. so i like to know when we have to write interface and when we need to go for abstract class.
show me 5 or 10 most important uses of interface in real life scenario.
another main use is coming to my mind that project manager or team lead will implement basic skeleton through interface and other developer follow it.
so please guys show me with sample code few most important use of interface which we can do with abstract class or concrete class.
one guy told me like this way which is not very clear to me
interfaces are defined contracts between classes or structs, consumers can exchange the implementation by a different one as long as the same contract is met that is the method names and signature that compose a specification that classes and structs can work against rather than working against a concrete implementation.
The important part about interfaces is to know when to use them and as a matter of fact it's quite simple, when you want two or more unrelated objects to have the same common functionality but not necessarily the same implementation you will want to use interfaces; otherwise, when you have related objects that have a shared functionality and implementation then you may consider to use an abstract class instead of an interface.
this thing is not clear specially
when you want two or more unrelated objects to have the same common functionality but not necessarily the same implementation you will want to use interfaces; otherwise, when you have related objects that have a shared functionality and implementation then you may consider to use an abstract class instead of an interface.
it would be nice if anyone explains with sample code when to go for interface & when abstract class.
show me few best important area which is always handle with interface with sample code or best interface uses with sample code.thanks
Some of microsoft recommendation from this link
If you anticipate creating multiple versions of your component,
create an abstract class. Abstract classes provide a simple and easy
way to version your components. By updating the base class, all
inheriting classes are automatically updated with the change.
Interfaces, on the other hand, cannot be changed once created. If a
new version of an interface is required, you must create a whole new
interface.
If the functionality you are creating will be useful across a wide
range of disparate objects, use an interface. Abstract classes
should be used primarily for objects that are closely related,
whereas interfaces are best suited for providing common
functionality to unrelated classes.
If you are designing small, concise bits of functionality, use
interfaces. If you are designing large functional units, use an
abstract class.
If you want to provide common, implemented functionality among all
implementations of your component, use an abstract class. Abstract
classes allow you to partially implement your class, whereas
interfaces contain no implementation for any members.
I won't answer all you questions. I just want to give you some hints.
The main difference between an interface and an abstract class is, that a c# class can implement multiple interfaces even if they declare the same members. And it can even implement those equally named members differently by implementing the interface explicitly.
If you derive from an abstract class, you also "inherit" al its dependencies. For example if a method in an abstract class uses another class from a different assembly, you have to reference that assembly. --> Compile order --> No parallel build
Mocking in unittest can be trickier when using abstract classes with base functionality
Let's take for instance some Data Access Objects which can retrieve data from a DB, a SAOP Service, a REST Service or even an XML file.
You would use Interfaces to ensure what kind of operations they offer to the rest of the application. You can also say that those interfaces describe the Domain and how they interact with it.
public interface IUserDao
{
User GetUserById(int id);
void AddUser(User u);
....
}
This IUserDao can be implemented by using WCF, Entity Framework, XmlDocuments, and many other techniques, the controller or other parts of the application don't care about the details as long as they have those abstracted methods to retrieve and add a user.
On the other hand the same Data Access Objects can have a base class which can for instance initialize some connections or open the XmlDocument, ...
public abstract BaseDao
{
public Connection GetNewConnection()
{
....
}
// or similar functions which are used by DAOs accessing the same data source (DB, XML, ...)
}
So as it was described, you can use interfaces to hide implementation details and bring the implementation to a more absract level, this way, less skilled developers or developers more interested in the domain specific aspects (some specific calculation, ...) can contribute without the need to understand how exactly they need to retrieve and store the data from / to the database.
Also it is easier to exchange functionality, for instance you can start with a simple xml file but soon you'll realize that you'll need a whole DB - you can keep the interfaces and implement the classes with DB access.
On the other hand abstract classes share basic functionality (technical functionality), which is so basic that it is used by many classes but shouldn't be instantiated alone. You could exchange Abstract Classes for some utility classes with static methods, but than you would loose the advantages of OOP.
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).
I'm building a public API for our application, using C#. I have a set of facade classes on top of DTOs used with a WCF client. It allows the API consumer to fetch, update, create, etc., from a database application. Standard stuff: Customer has a collection of Orders, Order has a collection of Line Items, etc.
The facade classes all derive from a common base class and override methods that do validation, reading/writing the DTOs, and other plumbing stuff, all using various internal types. I'm using a factory for creating new objects and fetching existing ones.
The question now is how best to expose the classes through the API while minimizing exposure of implementation details.
Interfaces seem like the obvious approach as the simplest way to limit what's exposed (and may in the end be necessary anyway, as a COM-compatible interface is under consideration). The problem with the interface approach is that internally my code will be dependent on particular implementations of the interfaces.
Suppose I have an ICustomer interface exposing my CustomerFacade, and IOrder exposing OrderFacade. Externally, ICustomer has a collection of IOrders. But internally, the CustomerFacade has a collection of OrderFacades. If the client application adds a new IOrder to a customer, I have to check that the IOrder is really an OrderFacade previously created from my factory, and not some other object outside my control that implements IOrder. That's because internally I need an order to be able to do a lot more than what an IOrder can do.
Practically speaking this doesn't much matter--users of the API are not going to be trying to create their own Order implementations. But it feels inelegant to me, like an abuse of what the interface contract is supposed to mean.
Exposing the facade classes directly isn't great, because the entire class hierarchy has to get exposed, along with the internal types used by protected methods, and that clutters up the API with types that the consumer won't be using and doesn't need to know about.
The other alternative I can think of is another layer of encapsulation: An Order that contains a private OrderFacade and only exposes the members that should be public. But this seems like a lot of extra code for limited benefit.
I considered abstract base classes but that doesn't work any better than exposing the facade classes, due to the inheritance structure. For example, if I have a ServiceItem that inherits from CatalogItem, introducing an abstract ServiceItemBase in between still requires me to expose all the protected methods in CatalogItem.
Any recommendations on these approaches, or an alternative I haven't looked at?
That seems pretty complex. I don't know the business problems you're trying to solve, so I don't know why there's the need for the various facades. If users will be using your api for data manipulation, you could consider using commands to modify the data, and queries to return DTO's that contain only the data the client will need.
http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321545613
This is a great book that might help.
You could also expose abstract classes with no public constructors instead of interfaces. This has the additional advantage that abstract classes can be extended as a non-breaking change, which is not true for interfaces.
Using the internal access modifier enables the hiding of members that should not be visible outide the implementing assembly.
so in my application I've got several different customers being "serviced". Each customer has their own implementations of various classes that are all based on interfaces.
With the latest customer being added, I've noticed there will be a lot of duplication of code from another customer but the other customer is in no other way related to them.
I've already got a default implementation for several other customers and roll new ones as i need them.
My question is how do i refactor this and still keep the code clean? If i were a dev new to this code base i would want each customer to either use the default or their own implementation of these classes... but that's a lot of duplication.
Consider using an abstract base class with abstract or virtual members. Abstract members are essentially equivalent to interface members (they have no build-in behavior, they only guarantee the method exists) whereas virtual members have a default implementation which can be overridden by derived classes.
Your question is really too vague to answer in full, but here's how you can leverage inheritance.
If you want all classes to use the same implementation of a member then that member can be implemented in the base-class.
If you want each class to have its own implementation of a member then you can either use a base-class with abstract members, or an interface.
If you want some classes to use the same implementations and others to use different implementations then implementing the default behavior in the base-class and override it as needed.
My main point is that OOP there is a spectrum of how much or little functionality is in base/abstract/concrete classes. There's no silver-bullet answer, sometimes your base classes will be skeletons and sometimes they'll be fully fleshed-out; it all depends on the specific problem at hand.
Is there some way that you could create a base class, then a specific implementation for each customer and then using some type of Dependency Injection have that load classes or functionality as needed. You want to really have a DRY system so as to avoid headaches and typos or other similar human mistakes.
You may use either inheritance (put common logic to the base class) or aggregation (spread that logic among other classes and make use them from your customers).
I'd recommend the visitor pattern:
http://en.m.wikipedia.org/wiki/Visitor_pattern
As well as the mediator pattern:
http://en.m.wikipedia.org/wiki/Mediator_pattern
Reason being that it sounds like you may benefit from decoupling, or at least more-loose-coupling, the business logic from your classes, based on what you are saying.
It's a bit difficult to know what to suggest without a better understanding of the code... but some things that have worked for me in similar situations include:
Use a Strategy, for the duplicated code. I've had most success where the strategy is encapsulated within a class implementing a known interface (one class per alternate strategy). Often in such cases I use some form of Dependency Injection framework (typically StructureMap) to pass the appropriate strategy/strategies to the class.
Use some sort of template class (or template methods) for the common item(s).
Use a Decorator to add specific functionality to some basic customer.
STW suggested that I should offer some clarification on what I mean by "Strategy" and how that differs from normal inheritance. I imagine inheritance is something you are very familiar with - something (typically a method - either abstract or virtual) in the base class is replaced by an alternate implementation in the derived class.
A strategy (at least the way I typically use it) is normally implemented by a completely different class. Often all that class will contain is the implementation for a single replaceable operation. For example if the "operation" is to perform some validation, you may have a NullValidationStrategy which does nothing and a ParanoidValidationStrategy which makes sure every McGuffin is the correct height, width and specific shade of blue. The reason I usually implement each strategy in its own class is because I try and follow the Single Responsibility Principle which can make it easier to reuse the code later.
As I mentioned above, I typically use a Dependency Injection (DI) framework to "inject" the appropriate strategy via the class constructor, but a similar results may be obtained via other mechanisms - e.g. having a SetSomeOperationStrategy(ISomeOperation StrategyToUse) method, or a property which holds the strategy reference. If you aren't using DI, and the strategy will always be the same for a given customer type, you could always set the correct choices when the class is constructed. If the strategy won't be the same for each instance of a given customer type, then you probably need some sort of customer factory (often a factory method will be sufficient).
I'd go with the answer of spinon (got my vote at least), but it's to short so let me elaborate:
Use your interfaces for the default implementation and then use dependency injection. Most tools allow you to define a scope or some criteria how to resolve something.
I assume that you do know the client at some early point of the program. So for ninject you just might want to define a "Module" for each client and load that into the kernel, depending on the client.
So I'd create a "no customization" Module and create a "ClientX" Module for every special case that uses ´Bind.To()` instead.
You end up with
a base implementation that is clean/default
a single place change for a new client (got a new one? Great. Either it works with the default or just needs a single Module that maps the interfaces to other classes)
The rest of the code shouldn't mind and get the dependencies via injection (constructor, property, whatever is easiest to go for. Constructor would probably be the nicest way) and has no special treatment at all.
You could even use a conditional binding in Ninject link text to solve the binding issue without different modules at all (although, depending on the number of clients, this might get messy and should better be separated).
I was going to suggest aggregation, as #the_joric suggests, over inheritance, but your description makes it sound like your application is already reasonably well-factored - that there aren't a lot of small classes waiting to be extracted from your existing classes. Assuming that's the case, for any given interface, if you have a perfect class for the new customer already written and ready to go, I would say go ahead and use it. If you're worried about that, for some reason, then take that perfect class, make it abstract, and create empty subclasses for your existing customer and your new customer - and if it's not quite a perfect fit, then that's the way I would go.
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.