Geeks With Blogs

  • elinden Finally on the ground in las Vegas after the worst American expresses rewards experience and 3 airlines Never book a flight on frontier air about 997 days ago
  • elinden Watching Mob Wives with Viggle Sun | 7PM | VH1 Get real rewards just for watching TV. #MobWives #viggle about 1072 days ago
  • elinden Watching For Rent with Viggle Sun | 4:30PM | Home & Garden Get real rewards just for watching TV. #HGTVForRent #viggle about 1072 days ago
  • elinden Watching Baylor vs. Kentucky with Viggle Sun | 1PM | CBS Get real rewards just for watching TV. #Kentucky #Baylor #viggle about 1073 days ago
  • elinden Watching Late Night With Jimmy Fallon with Viggle Fri | 11:37PM | NBC Get real rewards just for watching TV. #LNWJF #viggle about 1074 days ago
  • elinden Watching In Plain Sight with Viggle Fri | 9PM | USA Get real rewards just for watching TV. #InPlainSight #viggle about 1074 days ago

Evan Linden Helping to create great programmers one at a time

An argument for Interface based design and programming
For software to survive in the ever-changing jungle of the production environment, it must have three distinct characteristics: reusability, maintainability, and extensibility.
Interface-based programming exists outside the world of COM. It is a programming discipline that is based on the separation of the public interface from implementation. It was pioneered in languages such as C++ and Smalltalk by software engineers who discovered that using distinct interfaces could make their software, especially large applications, easier to maintain and extend. The creators of Java saw the elegance of interface-based programming and consequently built support for it directly into their language.
Interfaces solve many problems associated with code reuse in object-oriented programming. This document will discuss what some of these problems are. In particular, when you program in a style consistent with classic OOP, a client can build inflexible dependencies on a class definition. These dependencies can make it difficult to maintain or extend the class without breaking the client. It becomes tedious or impossible to improve the code for an object over time. Certain problems are also associated with a popular OOP language feature known as implementation inheritance. This powerful but often misused feature is vulnerable to similar dependency problems, which compromise an application's maintainability and extensibility. Since most 3GL languages support implementation inheritance, this document will discuss its strengths and limitations in order to address some of the problems that interface-base programming was created to solve.

Separating the Interface from the Implementation
Object composition offers another way to achieve reuse without the tendency toward tight coupling. Object composition is based on black-box reuse, in which implementation details of a class are never revealed to the client. Clients know only about an available set of requests (the what). Objects never expose internal details of the response (the how).
Black-box reuse is based on formal separation of interface and implementation. This means the interface becomes a first-class citizen. An interface is an independent data type that is defined on its own. This is an evolution of classic OOP, in which a public interface is defined within the context of a class definition.
At this point, you are probably thinking that this is all pretty vague. You're asking yourself, "What exactly is an interface?" Unfortunately, it's hard to provide a concise definition that conveys the key concepts of an entirely new way to write software. An interface can be described in many ways. You can get up to speed pretty quickly on the syntax for defining, implementing, and using interfaces. However, the implications that interfaces have on software design are much harder for the average programmer to embrace. Learning how to design with interfaces usually takes months or years.
At its most basic level, an interface is a set of public method signatures. It defines the calling syntax for a set of logically related client requests. However, while an interface defines method signatures, it cannot include any implementation or data properties. By providing a layer of indirection, an interface decouples a class from the clients that use it. This means an interface must be implemented by one or more classes in order to be useful. Once an interface has been implemented by a class, a client can create an object from the class and communicate with it through an interface reference.
You can use an interface to create an object reference but not the object itself. This makes sense because an object requires data properties and method implementations that cannot be supplied by an interface. Because it is not a creatable entity, an interface is an abstract data type. Objects can be instantiated only from creatable classes known as a concrete data types.
From a design standpoint, an interface is a contract. A class that implements an interface guarantees the objects it serves up will support a certain type of behavior. More specifically, a class must supply an implementation for each method defined by the interface. When communicating with an object through an interface reference, a client can be sure the object will supply a reasonable response to each method defined in the interface.
More than one class can implement the same interface. An interface defines the exact calling syntax and the loose semantics for each method. These loose semantics give each class author some freedom in determining the appropriate object behavior for each method. For instance, if the IDatabase interface defines a method named ExecuteSql(string commandText), different class authors can supply different responses to the same request, as long as each somehow reinforces the concept of running a sql statement. The OracleDatabaseConnector class can implement ExecuteSql() in a different way than either MSSqlDatabaseConnector or SybaseDatabaseConnector. This means that interfaces provide the opportunity for polymorphism. Interfaces are like implementation inheritance in the sense that they let you build applications composed of plug-compatible objects. However, interfaces provide plug-compatibility without the risk of the tight coupling that can occur with implementation inheritance and white-box reuse.

Note that this is an example only I am not sure I could ever justify doing this or argue that this is a good thing unless your are forced into it. I felt compelled to implement this due to usage restrictions in a corporate environment. In an effort to foster reuse (topic for another time… How and when to write for reuse) and comply with some misinterpreted security policies a wrapper was written around .Net native Data Access to “Protect” developers from themselves and to hide database connection strings from developers at runtime in the IDE. DON’T ASK HOW that’s a story for another day.

The Two Faces of Inheritance
Inheritance is an objected-oriented concept that models an "IS A" relationship between two entities. So far, this article has used the term implementation inheritance instead of the more generic term inheritance because extending a super class with a sub class is only one way to leverage an "IS A" relationship. When a class implements an interface, it also takes advantage of an "IS A" relationship. For instance, if a class OracleDatabaseConnector implements the interface IDatabase, it is correct to say that an OracleDatabaseConnector "IS A" Database. You can use an OracleDatabaseConnector object in any situation in which an IDatabase-compatible object is required.
Interface-based programming is founded on a second form of inheritance known as interface inheritance. This means that inheritance does not require the reuse of method implementations. Instead, the only true requirement for inheritance is that a sub class instance be compatible with the base type that is being inherited. The base type that is inherited can be either a class or a user-defined interface. In either situation, you can use the base-type references to communicate with objects of many different types. This allows both forms of inheritance to achieve polymorphism.
Both forms of inheritance offer polymorphism, yet they differ greatly when it comes to their use of encapsulation. Implementation inheritance is based on white-box reuse. It allows a sub class to know intimate details of the classes it extends. This allows a sub class to experience implicit reuse of a super class's method implementation and data properties. Implementation inheritance is far more powerful than interface inheritance in terms of reusing state and behavior. However, this reuse comes with a cost. The loss of encapsulation in white-box reuse limits its scalability in large designs.
As the term black-box reuse suggests, interface inheritance enforces the concepts of encapsulation. Strict adherence to the encapsulation of implementation details within classes allows for more scalable application designs. Interface-based programming solves many of the problems associated with white-box reuse. However, to appreciate this style of programming, you must accept the fact that the benefits are greater than the costs. This is a struggle for many programmers.
When a class implements an interface, it takes on the obligation to provide set methods. Sub class authors must write additional code whenever they decide to implement an interface. When you compare this to implementation inheritance, it seems like much more work. When you inherit from a class most of your work is already done, but when you inherit from an interface your work has just begun. At first glance, implementation inheritance looks and smells like a cheeseburger, while interface inheritance looks like a bowl of steamed broccoli. You have to get beyond the desire to have the cheeseburger to reach a higher level of interface awareness. The key advantage of interface inheritance over implementation inheritance is that it is not vulnerable to the tight coupling that compromises the extensibility of an application.

Why Use Interfaces?
When developers learn how to use interfaces in an application, they often wonder, "Why would I ever want to do that?" or "Why should I care?" Programming with class-based references seems far more natural compared to the additional complexity required with user-defined interfaces. The previous example would have been far easier if the client code programmed against public methods and properties of the OracleDatabaseConnector class instead of the IDatabase interface. User-defined interfaces seem like extra work without any tangible benefits.
There are several significant reasons why a programmer should care about interfaces. The first reason is that interfaces are the foundation of Services they define the contract. In a services environment clients can use class-based references but imagine the power contract based programming. Instead of class objects you access and program to their published interface the contract is immutable the objects are not. This provides a greater degree of isolation and protection from changes in the service and a high degree of flexibility through interface references. I know this sounds like the fundamentals of COM. Isn’t COM dead? Yes is died with a whimper and a cheer but the rules we lived with port directly to the WebServices and SOA enabled world. If you embrace interface-based programming, you will become a much stronger programmer.
Another reason why you should care about interfaces is that they can offer power and flexibility in software designs. Using interfaces in your programming becomes valuable when you don't have a one-to-one mapping between a class and a public interface. There are two common scenarios. In one scenario, you create an interface and implement it in multiple classes. In the other scenario, you implement multiple interfaces in a single class. Both techniques offer advantages over application designs in which clients are restricted to using references based on concrete classes. While interface-based designs often require more complexity, the sky is the limit when it comes to what you can do with them.
Consider a case in which many classes implement the same interface. For example, assume the classes CSecurityProvider, CSettingsProvider, and CNotificationsProvider all implement the interface IProvider.

An application can maintain a collection of IProvider-compatible objects using the following code:

Well thats neat but how is that of use? I can accomplish the same thing with a generic collection or an array of object type. Yes your right but where is the value add? How do you know what is in your generic collection or array of objects?
First lets assume that the interface defines a method/contract of GetData() and that an array of providers is provided in the constructor of the containing class. Lets also assume for this example that each Provider needs to call the GetData method in the constructor of the containing class. A simple for loop can be used to accomplish this for all the IProviders.

Another scenario could be that you only want to call the GetData method on the SecurityProvider and verify the user is authorized before continuing. Now our simple loop has become a bit more complex.There are two ways to accomplish this I would recommend the second for simplicity,elegance and clarity.
Example 1

Example 2

This has by no means been an exhaustive discussion of interfaces but I think you can begin to see the value and power that design by interface can bring to you applications.

Posted on Tuesday, June 3, 2008 10:17 PM Best Practice , Design , Architecture | Back to top

Comments on this post: Using Interfaces - Design by Contract

# re: Using Interfaces - Design by Contract
Requesting Gravatar...
Great article! Finally, I've found answers to my questions. Thank you!
But, do you really think that black-box reuse shall always dominate over the black-box reuse? However, in the large layers having lots of components (and sub-components) there won't be any chance to pull up base state (and base behavior) into the base class. What do you think regarding use of abstract classes instead of interfaces? They represent contract as well as interfaces do, but also allow to achieve goals aforesaid?
Left by AnatoliyR on Nov 18, 2010 2:58 AM

# I want to know...
Requesting Gravatar...
I was actually given a task that. please elaborate with example . how can we use interfaces to build an scalable application..
Actually i think i should start to tell you from beginning. I was having an initial interview. Where i was asked to elaborate the interfaces. I told them all , that i know. But interviewer said. there is one point missing. After my interview he was happy and recommend me right after the interview. But i have another test and for that i was given the above task.
Coould anyone please tell me. how may we use interfaces for scalable applicatio
Left by Ehsan ul haq on Jan 27, 2011 3:26 PM

Your comment:
 (will show your gravatar)

Copyright © Evan Linden | Powered by: | Join free