I tried the SOLID architecture within my last project.
I have an Interface called ILog and a class Logthat implemented ILog. (In my understanding that should be done to follow the Open/Closed principle)
In order to stay open for extensions I implemented the front end via List<ILog> instead of with the firm implementation List<Log>.
Serializing the List<ILog> is no problem, but deserializing is. I understand why of course, because the deserializer does not know which implementation class it should use.
Question:
How to know into which concrete type to deserialize an object that was serialized through an interface reference?
Serializing the List is no problem, but deserializing is.
If you are deserializing you necessarily need to somehow communicate to your serializer which conrete representation of your interface to use. In case of Json.NET you could use the JsonConstructorAttribute (see also this answer) or resolvers in combination with dependency injection.
Question: What does it help me to work with List if I have to define the specific implementation-class for data storage / data import anyways?
Interfaces decouple your code from the actual implementation, which results in various benefits. For example in terms of unit testing they make mocking easier (since you can satisfy the interface with a mocked instance instead of being forced to use the "real" class). Also Interfaces allow you to benefit from covariance/contravariance, which you wouldn't have with a classes in C#. For further reading on the benefits of interfaces, have a look at the various answers to this question or see this blog post.
The above being said, interfaces always introduce a certain level of overhead/abstraction and you need to evaluate per case/situation, whether they make sense or not.
What would be the best way to handle the data-storage of interface objects or are they only used at runtime?
You necessarily need to store concrete representations, which means at the time of persistance, you need to decide which concrete implementation to use for storage (and later deserialization).
Related
I have some integrations (like Salesforce) that I would like to hide behind a product-agnostic wrapper (like a CrmService class instead of SalesforceService class).
It seems simple enough that I can just create a CrmService class and use the SalesforceService class as an implementation detail in the CrmService, however, there is one problem. The SalesforceService uses some exceptions and enums. It would be weird if my CrmService threw SalesforceExceptions or you were required to use Salesforce enums.
Any ideas how I can accomplish what I want cleanly?
EDIT: Currently for exceptions, I am catching the Salesforce one and throwing my own custom one. I'm not sure what I should do for the enums though. I guess I could map the Salesforce enums to my own provider-agnostic ones, but I'm looking for a general solution that might be cleaner than having to do this mapping. If that is my only option (to map them), then that is okay, just trying to get ideas.
The short answer is that you are on the right track, have a read through the Law of Demeter.
The fundamental notion is that a given object should assume as
little as possible about the structure or properties of anything else
(including its subcomponents), in accordance with the principle of
"information hiding".
The advantage of following the Law of Demeter is that the resulting
software tends to be more maintainable and adaptable. Since objects
are less dependent on the internal structure of other objects, object
containers can be changed without reworking their callers.
Although it may also result in having to write many wrapper
methods to propagate calls to components; in some cases, this can
add noticeable time and space overhead.
So you see you are following quite a good practise which I do generally follow myself, but it does take some effort.
And yes you will have to catch and throw your own exceptions and map enums, requests and responses, its a lot of upfront effort but if you ever have to change out Salesforce in a few years you will be regarded a hero.
As with all things software development, you need to way up the effort versus the benefit you will gain, if you think you are likely never to change out salesforce? then is it really needed? ... for you to decide.
To make use of good OOP practices, I would create a small interface ICrm with the basic members that all your CRM's have in common. This interface will include the typical methods like MakePayment(), GetPayments(), CheckOrder(), etc. Also create the Enums that you need like OrderStatus or ErrorType, for example.
Then create and implement your specific classes implementing the interface, e.g. class CrmSalesForce : ICrm. Here you can convert the specific details to this particular CRM (SalesForce in that case) to your common ICrm. Enums can be converted to string and the other way around if you have to (http://msdn.microsoft.com/en-us/library/kxydatf9(v=vs.110).aspx).
Then, as a last step, create your CrmService class and use in it Dependency Injection (http://msdn.microsoft.com/en-us/library/ff921152.aspx), that's it, pass a type of ICrm as a parameter in its constructor (or methods if you prefer to) . That way you keep your CrmService class quite cohesive and independent, so you create and use different Crm's without the need to change most of your code.
Whenever I want to stub a method in an otherwise trivial class, I most often extract an interface.
Now if the constructor of that class is public and isn't too complex or dependent on complex types, it would have the same effect to just make the method in question virtual and inherit.
Is this preferable over extracting an interface? If so, why?
Edit:
class Parser
{
public IDictionary<string, int> DoLengthyParseTask(Stream s)
{
// is slow even with using memory stream
}
}
There are two ways: Either extract an interface or make the method virtual. I actually prefer interfaces, but that could lead to an explosion of IParser Parser tuples...
You need to consider what you are trying to accomplish outside of your unit testing. Do not let your tool dictate your design.
Dealing in interfaces can help decouple your code, but these should be natural points of separation in your code (e.g. business logic or data access). Making methods virtual makes sense if you are going to inherit and overwrite those methods.
In your case, I would attempt to test the behavior that uses DoLengthyParseTask and not the method directly. This will provide a more robust test suite as well. You need to carefully consider whether this method really needs to be public(meaning it can and should be referenced outside its own assembly).
Interfaces just make a contract for you, basically a promise that your implementation will provide access to a specified set of contact points (methods, properties, etc), with no specification of behaviour. You are free to do whatever you want as long as you honor the promise.
A base class on the other hand, in addition of a contract, specifies at least some behaviour that is coded in the class (unless everything is abstract, but that is another story). Making a method virtual still enables you to call in the implementation of the base, and still provide your own code along with it.
This inheritance of behaviour is basically the reason why multiple inheritance is a no-no in modern OOP, and multiple interface implementation is relatively common.
That said, you need to weight whether you just want to extract a contract, or you want to extract some behaviour as well, and the answer should be obvious for a specific case.
As for the IParser / Parser pairs, first they are great for unit testing and for dependency injection, and second, they do not charge you for class creation, so feel free to create as many as you want.
By programming to an interface you get benefits of ease of mocking/stubbing in unit testing and loosely coupled code (and as a result, much higher flexibility), literally for free (the only drawback is more artifacts to manage).
Interfaces and inheritance are two separate things and it's not a good idea to use them interchangeably, even though it's possible. By marking method virtual you're essentially telling others not only they're free to change (override) this method in their implementations, but that you actually expect them to (and are you?).
Such design comes with rather heavy consequences, so unless you explicitly need it - you shouldn't use it. Try sticking to programming to interface instead.
One of good object oriented design principles state that you should program to an interface (design by contract, Liskov Substitution Principle) and prefer composition over inheritance (not only your classes should implement interfaces/abstract classes, but also consist of such implementations).
It's worth noticing that your Parser example makes perfect candidate to be hidden behind abstraction (be it interface or base class). From its consumer point of view it doesn't matter how the data is created - for now you might think it's XML stream only, but requirements tend to change (and/or grow), and you might soon find yourself implementing binary file parser, data stream mining parser and what-not-else. Do it properly now, save yourself time and trouble later.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Interface vs Abstract Class (general OO)
I can see their advantage in coordination of a developing team, or code that might be further developed by others.
But if not, is there a reason to use them at all? What would happen if I omit them?
Abstract – I'll be able to instantiate it. No problem. If it doesn't make sense – I won't.
Interface – I have that functionality declared in all classes deriving from it anyway.
Note: I'm not asking what they are. I'm asking whether they're helpful for anything but coordination.
Both are what I call contracts and can be used in the following fashion by an individual developer:
Abstract
Allows for polymophism of differing derived implementations.
Allows one to create base functionality which can be dictated or not that the derived class be required to implement.
Allows for a default operation to be runtime consumed if the derived does not implement or required to implement.
Provides a consistency across derived objects which a base class pointer can utilize without having to have the actual derived; hence allows generic operations on a derived object from a base class reference similar to an Interface in runtime operation.
Interface
Allows a generic pattern of usage as a defacto contract of operation(s).
This usage is can be targetted to the process in hand and allows for the
surgically precise operations for that contract.
Used to help with
factory patterns (its the object returned), mocking of data during
unit tests and the ability to replace an existing class (say from a
factory returning the interface) with a different object and it
doesn't cause any consumer of the factory any pain of refactoring due to the adherence of the interface contract.
Provides a pattern of usage which can be easily understood away from the static of the rest of the class's implementation.
Long story short are they required to get a job done? No.
But if you are into designing systems which will have a lifespan of more than one cycle, the upfront work by said architect will pay off in the long run whether on a team or by an individual.
++Update
I do practice what I preach and when handing off a project to other developers it was nice to say
Look at the interface IProcess which all the primary business classes adhere to. That process defines a system of goals which can help you understand the purpose and the execution of the business logic in a defined way.
While maintaining and adding new functionality to the project the interfaces actually helped me remember the flow and easily add new business logic into the project.
I think if you're not coordinating with others, it does two things
helps keep your from doing weird things to your own code. Imagine
your write a class, and use it in multiple projects. You may evolve
it in one project so that it is unrecognizable from it's cousin in
another project. Having an abstract class or interface makes you
think twice about changing the function signatures.
it gives you flexibility going forward - plenty of classic examples here. Use
the generic form of the thing you're trying to accomplish, and if
you decide you need a different kind later (streamreaders are a
great example, right?) you can more easily implement it later.
Abstract - you can instantiate a child of it, but what is more important, it can has its own non abstract methods and fields.
Interface - more "rough" one in regard of abstract, but in .NET you can have multiple inheritance. So by defining interface you can lead consumer of your interface(s) to subscribe to different contracts(interfaces), so present different "shapes" of specified type.
There are many reasons to use either construct even if you are not coordinating with anyone. The main use is that both actually help express the developper intent, which may help you later figure out why you choose the design you actually chose. They also may allow for further extensibility.
Abstract class allow you to define one common implementation that will be shared across many derived classes while delegating some of the behavior to the child classes. It allows the DRY (don't repeat yourself) principle to avoid having the same code repeated everywhere.
Interfaces expresses that your class implements one specific contract. This has a very useful uses within the framework, among which:
Use of library functionality that necessitate the implementation of some Interface. Examples are IDisposable, IEquatable, IEnumerable...
Use of constraints in generics.
Allow mocking of interfaces (if you do unit testing) whithout having to instanciate a real object.
Use of COM objects
Closed. This question is opinion-based. It is not currently accepting answers.
Closed 7 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I have a function that returns same kind of objects (query results) but with no properties or methods in common. In order to have a common type I resorted using an empty interface as a return type and "implemented" that on both.
That doesn't sound right of course. I can only console myself by clinging to hope that someday those classes will have something in common and I will move that common logic to my empty interface. Yet I'm not satisfied and thinking about whether I should have two different methods and conditionally call next. Would that be a better approach?
I've been also told that .NET Framework uses empty interfaces for tagging purposes.
My question is: is an empty interface a strong sign of a design problem or is it widely used?
EDIT: For those interested, I later found out that discriminated unions in functional languages are the perfect solution for what I was trying to achieve. C# doesn't seem friendly to that concept yet.
EDIT: I wrote a longer piece about this issue, explaining the issue and the solution in detail.
Although it seems there exists a design pattern (a lot have mentioned "marker interface" now) for that use case, i believe that the usage of such a practice is an indication of a code smell (most of the time at least).
As #V4Vendetta posted, there is a static analysis rule that targets this:
http://msdn.microsoft.com/en-us/library/ms182128(v=VS.100).aspx
If your design includes empty interfaces that types are expected to implement, you are probably using an interface as a marker or a way to identify a group of types. If this identification will occur at run time, the correct way to accomplish this is to use a custom attribute. Use the presence or absence of the attribute, or the properties of the attribute, to identify the target types. If the identification must occur at compile time, then it is acceptable to use an empty interface.
This is the quoted MSDN recommendation:
Remove the interface or add members to it. If the empty interface is being used to label a set of types, replace the interface with a custom attribute.
This also reflects the Critique section of the already posted wikipedia link.
A major problem with marker interfaces is that an interface defines a contract for implementing classes, and that contract is inherited by all subclasses. This means that you cannot "unimplement" a marker. In the example given, if you create a subclass that you do not want to serialize (perhaps because it depends on transient state), you must resort to explicitly throwing NotSerializableException (per ObjectOutputStream docs).
You state that your function "returns entirely different objects based on certain cases" - but just how different are they? Could one be a stream writer, another a UI class, another a data object? No ... I doubt it!
Your objects might not have any common methods or properties, however, they are probably alike in their role or usage. In that case, a marker interface seems entirely appropriate.
If not used as a marker interface, I would say that yes, this is a code smell.
An interface defines a contract that the implementer adheres to - if you have empty interfaces that you don't use reflection over (as one does with marker interfaces), then you might as well use Object as the (already existing) base type.
You answered your own question... "I have a function that returns entirely different objects based on certain cases."... Why would you want to have the same function that returns completely different objects? I can't see a reason for this to be useful, maybe you have a good one, in which case, please share.
EDIT: Considering your clarification, you should indeed use a marker interface. "completely different" is quite different than "are the same kind". If they were completely different (not just that they don't have shared members), that would be a code smell.
As many have probably already said, an empty interface does have valid use as a "marker interface".
Probably the best use I can think of is to denote an object as belonging to a particular subset of the domain, handled by a corresponding Repository. Say you have different databases from which you retrieve data, and you have a Repository implementation for each. A particular Repository can only handle one subset, and should not be given an instance of an object from any other subset. Your domain model might look like this:
//Every object in the domain has an identity-sourced Id field
public interface IDomainObject
{
long Id{get;}
}
//No additional useful information other than this is an object from the user security DB
public interface ISecurityDomainObject:IDomainObject {}
//No additional useful information other than this is an object from the Northwind DB
public interface INorthwindDomainObject:IDomainObject {}
//No additional useful information other than this is an object from the Southwind DB
public interface ISouthwindDomainObject:IDomainObject {}
Your repositories can then be made generic to ISecurityDomainObject, INorthwindDomainObject, and ISouthwindDomainObject, and you then have a compile-time check that your code isn't trying to pass a Security object to the Northwind DB (or any other permutation). In situations like this, the interface provides valuable information regarding the nature of the class even if it does not provide any implementation contract.
What is need of interfaces in c# ? as we are writing abstract method in interfaces. instead of that we can directly implement those methods in class.
Interfaces don't support implementation, so you cannot supply any default implementations as you can with abstract classes. Additionally, interfaces are not restricted to hierarchies, so they are more flexible than abstract classes.
You do not need to use interfaces in C#. They are useful and appropriate in some circumstances, but not in all circumstances. A handy rule of thumb that I use is that if, in your project, you only have one class that implements an interface, you do not need that interface.
Note: one possible counter to this rule of thumb is that you may need to write a second implementing class in the future, which may justify the use of the interface. I do not necessarily agree, as I think a considerable amount of time in programming is wasted anticipating future scenarios which never materialize.
You may want to read up on polymorphism.
For myself, I find a lot of use out of interfaces when I have similar objects but completely different implementations of the same methods.
Additionally, you can implement multiple interfaces but inherit only one abstract class. I find this very useful because my business objects have a better representation.
When writing any N-Tiered application which separates out business logic from the presentation I think you will start to find many uses for interfaces.
Interface is needed exactly as described in books: to define a contract between components. They are one of the best ways to expose certain functionality to other modules while preserving encapsulation.
For example:
1) try, without an interface, to expose some piece of functionality implemented in assembly 'A', to assembly 'B', with no actual implementation visible to assembly 'A'.
2) Even worse - if we consider .NET remoting scenarios, where the server must expose certain
functionality to the client, while the functionality is implemented and hosted on the server side. In this case an assembly is published to a client, where interfaces for the server-hosted classes are defined.
Think of Interfaces as contracts.
You create a contract that a class must follow. For example, if our Dog object must have a Walk method, it's defining class must implement this method.
In order to force every dog class (inherited or not) to implement this method, you must make them adhere to a contract i.e assign an interface which specifies that method.
An interface is a construct that enforces particular classes to follow strict rules of implementation.
The reason for this is that you end up with Dog objects (inherited or not) that now, by default, have a Walk method. This means you can pass these objects as parameters, safe in the knowledge that you can call the Walk method on any Dog class (inherited or not) and it will deffinately be implemented.
If you want to write testable code, you will usually need to employ interfaces. When unit testing, you may have ClassA which depends upon ClassB which Depends upon ClassC etc, but you only want to test ClassA. You certainly don't want to create a ClassC to pass to a ClassB just to instantiate ClassA.
In that case, you make ClassA depend upon IClassB (or some more generic name, most likely that does not imply anything about the ClassB implementation) and mock out IClassB in your tests.
It is all about dependency management for me.
You need interfaces when you want to think of a disparate set of classes as all being the same type of object. Say, for example, you have a set of classes that all read their configuration from a file. One way to handle this is to have all the classes implement the appropriate methods to read a configuration from a file. The trouble with this is that then any code that uses those classes and wants to configure them needs to know about all the different classes so that it can use the methods on them.
Another way is to have them all derive from a single base class. That way any code using the classes need only know about the base class -- it can treat any of the derived classes as the base class and use those methods defined in the base class to do the configuration. This isn't so bad, but it has the major drawback -- since C# doesn't support multiple inheritance -- of limiting your inheritance chain. If you want to be able to have the same sort of ability for some of the classes, but not all of them for a different set of behavior, you're stuck implementing it for all of them anyway. Not good.
The last way is to use interfaces to define the behavior. Any class wanting to implement the behavior need only implement the interface. Any class wanting to use the behavior need only know about the interface and can then use any class that implements it. Classes can implement any interface or even multiple interfaces so you have granular "allocation" of behavior among classes. You can still use base classes and inheritance hierarchies to provide the main behavior of a class in a shared way, but the class is also free to implement other interfaces to give itself more behavior and still retain the convenience of classes that use it to know only about the interface.
Interfaces allow implementers to use their own base class. With abstract classes, implementers are forced to use the given base class to implement the interface even if it actually makes more sense for the implementer to use a project-specific base class.
Interfaces are used to define the behaviour/properties of classes without specifying the implementation. If you begin thinking about classes as fulfilling roles rather than just being a bundle of methods and properties then you can begin assigning multiple roles to classes using interfaces - which is not possible using straight inheritance in C# as you can only inherit from a single class. By making clients of the classes depend on the interfaces (roles) rather than the class itself your code will be more loosely coupled and probably better designed.
Another benefit of this is if you are writing unit tests they are more likely to be focussed on behaviour rather than state. Coding against interfaces makes it very easy to make mock/stub implementations for this type of testing.
Not everything will need interfaces - but most things with behaviour probably (i.e. more than just a bundle of data) should have them IMHO as you'll always have two implementations: a real one in your application and one or more fake ones in your tests.
Interface is a contract that defines the signature of the functionality. So if a class is implementing
a interface it says to the outer world, that it provides specific behavior.
Example if a class is
implementing ‘Idisposable’ interface that means it has a functionality to release unmanaged
resources. Now external objects using this class know that it has contract by which it can dispose
unused unmanaged objects.
As presented by GoF 1st principle: Program to an interface not an implementation.
This helps in many ways. It's easier to change the implementation, it's easier to make the code testable and so on...
Hopes this helps.