Tutorial :why is it recommended to define service contract as an interface



Question:

why is it recommended to define service contract as an interface. Any specific advantages over having them as classes?


Solution:1

The primary goal is separate definition of your service from implementation

The user of your service should not know anything about how you implemented your service, but he should know what operations he can do and how.

That's why its using an interface instead of class, because interface doesn't contain an implementation.

You can share your interface one time and then never worry for years even if you changing implementation of its methods every day. End users will not need to recompile the code that's using your service


Solution:2

Of course [there are several advantages] !

The main one is probably the ability to implement multiple classes which support said Interface and to use these classes interchangeably [with regards to the particular interface]. One of the direct uses of this is with Mock classes used for testing; This is also used with IoC (Inversion of Control) pattern, and more generally wherever we care about the "What" rather than the "Who", i.e. What matters is that whichever class is in place it behaves as per the contract (the API) regardless of "who" (which class) it is.

Another salient advantage of Interfaces is the ability to modularize behavior. For example your application may implement a concept which works, say, like a List (can be iterated over, supplies a number of items, etc.) and like a widget validator (some application specific thing). By having two interfaces "describing" this particular object, you can use instances of that class wherevever you'd use a List (and just that) and similarly you can use it as a widget validator (and just that) whereever these validator are needed. This is akin to multiple inheritance but more flexible.

In a nutshell (and some other answers started with this), the Interface defines the contract and the Class(es) implement(s) it.
Technically, a single class could do both of these things, i.e. you do not __need __ to have Interfaces, but it is very preferable to define APIs for most any behavior which may be implemented by several classes (whether multiple implementations of almost the same thing as with "mock classes", or very different classes but supplying one particular generic service/feature as say two very distinct Lists.)


Solution:3

Because an interface IS a contract and a class is the means to fulfill a contract. There can be many different ways to fulfill a contract based on the context, so It makes more sense to have the contracts as interfaces. which can have different implementations


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »