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.
Related
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.
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 believe we invent things for some reasons: OOP came because procedural programming didn't meet our needs; The same goes for the Interface, because other OOP features like Abstract didn't meet our needs.
There are plenty of articles and guides written about what an Interface IS, CAN DO and HOW TO USE IT, however, I'm wondering what the actual philosophy behind the of creation of Interface is? Why we need to have Interface?
Conceptually, an interface is a contract. It's a way of saying that anything implementing this interface is capable of doing these set of things.
Different languages have different things that interfaces can define, and different ways of defining them, but that concept remains.
Using interfaces allows you to not care how some particular task is completed; it allows you to just ensure that it is completed.
By allowing implementations to differ, and allowing the code to define just the smallest subset of what it needs, it allows you to generalize your code.
Perhaps you want to write a method to write a sequence of numbers on the screen. You don't want to go around writing methods for doing that for an array, a set, a tree, on any of the (many) other commonly used data structures. You don't need to care whether you're dealing with an array or a linked list, you just need some way of getting a sequence of items. Interfaces allow you to define just the minimal set of what you need, lets say a getNextItem method, and then if all of those data structures implement that method and interface they can use the one generalized method. That's much easier than writing a separate method for each type of data structure you want to use. (This isn't the only use of interface, just a common one.)
In Java, classes can inherit just from one class, but they can implement multiple interfaces. Interfaces are similar to abstract classes, but if a class extends an abstract class then that class can't extend any other class. Interfaces solve that problem, you can make a class extend an abstract class and implement many interfaces.
I completely agree with susomena, but that's not the only benefit you get, when using interfaces.
For example. In our current application, mocking plays an important role, regarding unit testing. The philosophy of unit testing is, that you should really just test the code of this unit itself. Sometimes, though, there are other dependencies, the "unit under test" (SUT) needs to get. And maybe this dependency has other dependencies and so forth. So instead of complicatetly building and configuring the dependency tree, you just fake this certain dependency. A lot of mocking frameworks need to be setup with the interface of the class, which the SUT depends on. It is usually possible to mock concrete classes, but in our case mocking of concrete classes caused weird behaviours of unit tests, because of constructor calls. But mocking interfaces didn't, because an interface hasn't got a constructor.
My personal philosophy of choosing an abstract class implementation is building an hierarchical class construct, where some default behaviour of the abstract base class is needed. If there isn't any default behaviour, the derived class should inherit, I don't see any points of not choosing an interface over an abstract class implementation.
And here an other (not too good) example of how to choose one over another technique. Imagine you got a lot of animal classes like Cat and Dog. The abstract class Animal might implement this default method:
public abstract void Feed()
{
Console.WriteLine("Feeding with meat");
}
That's alright, if you got a lot of animals, which just are fine with meat. For the little amount of animals, which don't like meat you'd just need to reimplement a new behaviour of Feed().
But what if the animals are a kinda gourmets? And the requirement was, that every animal gets its preferred food? I'd rather choose an interface there, so the programmer is forced to implement a Feed() method for every single type of IAnimal.
IMO the best text that describes interface is the ISP from Robert Martin.
The real power of interfaces comes from the fact that (1) you can treat an object as if it has many different types (because a class can implement different interfaces) and (2) treat objects from different hierarchy trees as if they have the same type (because not related classes can implement the same interface).
If you have a method with a parameter of some interface type (eg., a Comparable), it means this methods can accept any object that implements that interface "ignoring" the class (eg., a String or a Integer, two unrelated classes that implement Comparable).
So, an interface is a much more powerful abstraction than abstract class.
Interfaces were brought into OOP because of the sole reason of it's use in the producer consumer paradigm. Let me explain this with an example...
Suppose there is a vendor that supplies tyres to all the big shot automobile companies. The automobile comapny is considered to be the CONSUMER and the tyre vendor is the PRODUCER. Now te consumer instructs the producer of the various specifications in which a tyre has to be produced(such as the diameter, the wheel base etc.); And the producer must strictly adhere to all of these specs.
Let's have an analogy to OOP from this... Let us develop an application to implement a stack, for which you are developing the UI; and let us assume that you are using a stack library (as a .dll or a .class) to actually implement the stack. Here, you are the consumer and the person who actually wrote the stack program is the producer. Now, you specify the various specifications of the stack saying that it should have a provision to push elements and to pop elements and also a provision to peep at the current stack pointer. And you also specify the interface to access these provisions by specifying the return types and the parameters (prototype of functions) so that you know how to use them in your application.
The simplest way to achive this is by creating an interface and asking the producer to implement this interface. So that, no matter what logic the producer uses(u are not bothered about the implementation as long as your needs are met one way or the other), he will implement a push,pop and a peep method with exact return types and parameters .
In other words, you make the producer strictly adhere to your specs and the way to access your needs by making him implement your interface. You won't accept a stack by just any vendor, if he doesn't implement your interface; Because you cannot be sure if it'll suit your exact need.
class CStack implements StackInterface
{//this class produced by the producer must have all three method implementation
//interface defined by the consumer as per his needs
bool push(int a){
...
}
int pop(){
....
}
int peep(){
...
}
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Interface vs Base class
When should I choose inheritance over an interface when designing C# class libraries?
So I'm writing my first real program in C#. The program will scrape data from four different websites. My plan is to have one parent class that will look like this:
class Scraper
{
string scrapeDate(url);
string scrapeTime(url);
//&c.
}
Then I will have four classes that inherit from it.
The other option is to make Scraper an interface and have four classes implementing it.
What are the differences between these approaches?
Class inheritance represents an "is-a" relationship, e.g., a Tank is a Vehicle. If your situation doesn't at least meet this, choose interface over inheritance.
If the proposed base class doesn't provide default implementations for your methods, this would be another reason to choose interface over inheritance.
In C#, you can only inherit from one class but multiple interfaces. This would be yet another reason to choose interface over inheritance.
Get the idea?
Inheritance is, in my opinion, the better approach when it is possible. Implementing common features in a base class helps ensure that the underlying implementation is consistent, while implementing an interface guarantees only that the, well, interface is consistent. Inheritance wherever possible is one leg of the OOP tripod, and limits code duplication.
I use interfaces when I have objects that can't or shouldn't have a common base class, but need to be provide similar functionality. Classes that implement a common interface may (and probably do) expose additional functionality, may implement multiple interfaces, etc.
For instance: in one application, my data access layer is built around "provider" classes, which insulate business objects and database proxy objects from the database. In one instance, I have a provider which interacts with a SQL Server database and another for communicating with Oracle CRM On Demand (aka, Why God Why). The both implement an agnostic interface so that the client code doesn't care which data store it's dealing with, or the quirks of working with each.
The Oracle provider communicates with a hosted server via a collection of web services, manages connection sessions, batches requests, etc. The SQL provider uses a set of stored procedures. Although both interfaces accept the same data classes, the Oracle provider transforms the data to match their esoteric (to put it lightly) schema. With this implementation, I could easily add a provider to use an XML data store, a different RDBMS, or a stub/mock unit test.
In this situation, it doesn't make much sense for these things to have a common base class and, in a few instances, it's impossible.
Honestly, do both.
public interface IScraper
{
string ScrapeDate(string url);
}
public abstract class Scraper : IScraper
{
public string ScrapeDate(string url)
{
// default implementation
}
}
There's advantages either way, but those are difficult to quantify without knowing more about your requirements. However, there's no reason you can't do both. Having an interface for your class makes it mockable for testing purposes as well.
Something else to consider though; if the functionality for each of your derived classes are similar enough, it may be easier to simply have a single class that takes parameters to the constructor.
An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface.
A class can implement multiple interfaces.
A class can have only one direct base class.
Refering to Abstract Class versus Interface.
There are some similarities and
differences between an interface and
an abstract class:
A class may implement several
interfaces.
A class may inherit only one abstract
class.
An interface cannot provide any code,
just the signature.
An abstract class can provide
complete, default code and/or just the
details that have to be overridden.
An interface cannot have access
modifiers for the subs, functions,
properties etc everything is assumed
as public
An abstract class can contain access
modifiers for the subs, functions,
properties
Interfaces are used to define the
peripheral abilities of a class. In
other words both Human and Vehicle can
inherit from a IMovable interface.
An abstract class defines the core
identity of a class and there it is
used for objects of the same type.
If various implementations only share
method signatures then it is better to
use Interfaces.
If various
implementations are of the same kind
and use common behaviour or status
then abstract class is better to use.
If we add a new method to an Interface
then we have to track down all the
implementations of the interface and
define implementation for the new
method.
If we add a new method to an
abstract class then we have the option
of providing default implementation
and therefore all the existing code
might work properly.
No fields can be defined in interfaces
An abstract class can have fields and
constrants defined
Interfaces allows to define the structure of common behaviors.
Inheritance is useful if you can extract a common implementation of one or more specific behaviors.
Basically if several classes scrape a date the same way, it make sense to put scrapeDate in a base class; otherwise use only an interface and define the specific scrapeDate in every class that implement your interface.
If you have common functionality, you should use inheritance - the functionality will then be available in all child classes, and each child class can extend or override the parent class code.
If you have something consuming your classes, you would use interfaces to ensure that all of the classes implement the same methods and properties, but not necessarily the same functionality.
Main differences:
an interface has no implementation at all, whereas an abstract base class can implement common functionality
a class can only inherit from one base class, but it can implement multiple interfaces
In your case, it's likely that all your scraper classes will need some common features, so it makes sense to make them all inherit from a common base class
What you appear to have here is really best served as an Interface. If you were to have some common logic you wished to include or some common data members you wished to include then you would use a Base Class and inherit from it. What you are doing is requiring each child to implement a minimum set of logic.
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.