What is the value of Interfaces? - interface

Sorry to ask sich a generic question, but I've been studying these and, outside of say the head programming conveying what member MUST be in a class, I just don't see any benefits.

There are two (basic) parts to object oriented programming that give newcomers trouble; the first is inheritance and the second is composition. These are the toughest to 'get'; and once you understand those everything else is just that much easier.
What you're referring to is composition - e.g., what does a class do? If you go the inheritance route, it derives from an abstract class (say Dog IS A Animal) . If you use composition, then you are instituting a contract (A Car HAS A Driver/Loan/Insurance). Anyone that implements your interface must implement the methods of that interface.
This allows for loose coupling; and doesn't tie you down into the inheritance model where it doesn't fit.
Where inheritance fits, use it; but if the relationship between two classes is contractual in nature, or HAS-A vs. IS-A, then use an interface to model that part.
Why Use Interfaces?
For a practical example, let's jump into a business application. If you have a repository; you'll want to make the layer above your repository those of interfaces. That way if you have to change anything in the way the respository works, you won't affect anything since they all obey the same contracts.
Here's our repository:
public interface IUserRepository
{
public void Save();
public void Delete(int id);
public bool Create(User user);
public User GetUserById(int id);
}
Now, I can implement that Repository in a class:
public class UserRepository : IRepository
{
public void Save()
{
//Implement
}
public void Delete(int id)
{
//Implement
}
public bool Create(User user)
{
//Implement
}
public User GetUserById(int id)
{
//Implement
}
}
This separates the Interface from what is calling it. I could change this Class from Linq-To-SQL to inline SQL or Stored procedures, and as long as I implemented the IUserRepository interface, no one would be the wiser; and best of all, there are no classes that derive from my class that could potentially be pissed about my change.
Inheritance and Composition: Best Friends
Inheritance and Composition are meant to tackle different problems. Use each where it fits, and there are entire subsets of problems where you use both.

I was going to leave George to point out that you can now consume the interface rather than the concrete class. It seems like everyone here understands what interfaces are and how to define them, but most have failed to explain the key point of them in a way a student will easily grasp - and something that most courses fail to point out instead leaving you to either grasp at straws or figure it out for yourself so I'll attempt to spell it out in a way that doesn't require either. So hopefully you won't be left thinking "so what, it still seems like a waste of time/effort/code."
public interface ICar
{
public bool EngineIsRunning{ get; }
public void StartEngine();
public void StopEngine();
public int NumberOfWheels{ get; }
public void Drive(string direction);
}
public class SportsCar : ICar
{
public SportsCar
{
Console.WriteLine("New sports car ready for action!");
}
public bool EngineIsRunning{ get; protected set; }
public void StartEngine()
{
if(!EngineIsRunning)
{
EngineIsRunning = true;
Console.WriteLine("Engine is started.");
}
else
Console.WriteLine("Engine is already running.");
}
public void StopEngine()
{
if(EngineIsRunning)
{
EngineIsRunning = false;
Console.WriteLine("Engine is stopped.");
}
else
Console.WriteLine("Engine is already stopped.");
}
public int NumberOfWheels
{
get
{
return 4;
}
}
public void Drive(string direction)
{
if (EngineIsRunning)
Console.WriteLine("Driving {0}", direction);
else
Console.WriteLine("You can only drive when the engine is running.");
}
}
public class CarFactory
{
public ICar BuildCar(string car)
{
switch case(car)
case "SportsCar" :
return Activator.CreateInstance("SportsCar");
default :
/* Return some other concrete class that implements ICar */
}
}
public class Program
{
/* Your car type would be defined in your app.config or some other
* mechanism that is application agnostic - perhaps by implicit
* reference of an existing DLL or something else. My point is that
* while I've hard coded the CarType as "SportsCar" in this example,
* in a real world application, the CarType would not be known at
* design time - only at runtime. */
string CarType = "SportsCar";
/* Now we tell the CarFactory to build us a car of whatever type we
* found from our outside configuration */
ICar car = CarFactory.BuildCar(CarType);
/* And without knowing what type of car it was, we work to the
* interface. The CarFactory could have returned any type of car,
* our application doesn't care. We know that any class returned
* from the CarFactory has the StartEngine(), StopEngine() and Drive()
* methods as well as the NumberOfWheels and EngineIsRunning
* properties. */
if (car != null)
{
car.StartEngine();
Console.WriteLine("Engine is running: {0}", car.EngineIsRunning);
if (car.EngineIsRunning)
{
car.Drive("Forward");
car.StopEngine();
}
}
}
As you can see, we could define any type of car, and as long as that car implements the interface ICar, it will have the predefined properties and methods that we can call from our main application. We don't need to know what type of car is - or even the type of class that was returned from the CarFactory.BuildCar() method. It could return an instance of type "DragRacer" for all we care, all we need to know is that DragRacer implements ICar and we can carry on life as normal.
In a real world application, imagine instead IDataStore where our concrete data store classes provide access to a data store on disk, or on the network, some database, thumb drive, we don't care what - all we would care is that the concrete class that is returned from our class factory implements the interface IDataStore and we can call the methods and properties without needing to know about the underlying architecture of the class.
Another real world implication (for .NET at least) is that if the person who coded the sports car class makes changes to the library that contains the sports car implementation and recompiles, and you've made a hard reference to their library you will need to recompile - whereas if you've coded your application against ICar, you can just replace the DLL with their new version and you can carry on as normal.

So that a given class can inherit from multiple sources, while still only inheriting from a single parent class.
Some programming languages (C++ is the classic example) allow a class to inherit from multiple classes; in this case, interfaces aren't needed (and, generally speaking, don't exist.)
However, when you end up in a language like Java or C# where multiple-inheritance isn't allowed, you need a different mechanism to allow a class to inherit from multiple sources - that is, to represent more than one "is-a" relationships. Enter Interfaces.
So, it lets you define, quite literally, interfaces - a class implementing a given interface will implement a given set of methods, without having to specify anything about how those methods are actually written.

Maybe this resource is helpful: When to Use Interfaces

It allows you to separate the implementation from the definition.
For instance I can define one interface that one section of my code is coded against - as far as it is concerned it is calling members on the interface. Then I can swap implementations in and out as I wish - if I want to create a fake version of the database access component then I can.
Interfaces are the basic building blocks of software components

In Java, interfaces allow you to refer any class that implements the interface. This is similar to subclassing however there are times when you want to refer to classes from completely different hierarchies as if they are the same type.

Speaking from a Java standpoint, you can create an interface, telling any classes that implement said interface, that "you MUST implement these methods" but you don't introduce another class into the hierarchy.
This is desireable because you may want to guarantee that certain mechanisms exist when you want objects of different bases to have the same code semantics (ie same methods that are coded as appropriate in each class) for some purpose, but you don't want to create an abstract class, which would limit you in that now you can't inherit another class.
just a thought... i only tinker with Java. I'm no expert.
Please see my thoughts below. 2 different devices need to receive messages from our computer. one resides across the internet and uses http as a transport protocol. the other sits 10 feet away, connect via USB.
Note, this syntax is pseudo-code.
interface writeable
{
void open();
void write();
void close();
}
class A : HTTP_CONNECTION implements writeable
{
//here, opening means opening an HTTP connection.
//maybe writing means to assemble our message for a specific protocol on top of
//HTTP
//maybe closing means to terminate the connection
}
class B : USB_DEVICE implements writeable
{
//open means open a serial connection
//write means write the same message as above, for a different protocol and device
//close means to release USB object gracefully.
}

Interfaces create a layer insulation between a consumer and a supplier. This layer of insulation can be used for different things. But overall, if used correctly they reduce the dependency density (and the resulting complexity) in the application.

I wish to support Electron's answer as the most valid answer.
Object oriented programming facilitates the declaration of contracts.
A class declaration is the contract. The contract is a commitment from the class to provide features according to types/signatures that have been declared by the class. In the common oo languages, each class has a public and a protected contract.
Obviously, we all know that an interface is an empty unfulfilled class template that can be allowed to masquerade as a class. But why have empty unfulfilled class contracts?
An implemented class has all of its contracts spontaneously fulfilled.
An abstract class is a partially fulfilled contract.
A class spontaneously projects a personality thro its implemented features saying it is qualified for a certain job description. However, it also could project more than one personality to qualify itself for more than one job description.
But why should a class Motorcar not present its complete personality honestly rather than hide behind the curtains of multiple-personalities? That is because, a class Bicycle, Boat or Skateboard that wishes to present itself as much as a mode of Transport does not wish to implement all the complexities and constraints of a Motorcar. A boat needs to be capable of water travel which a Motorcar needs not. Then why not give a Motorcar all the features of a Boat too - of course, the response to such a proposal would be - are you kiddin?
Sometimes, we just wish to declare an unfulfilled contract without bothering with the implementation. A totally unfulfilled abstract class is simply an interface. Perhaps, an interface is akin to the blank legal forms you could buy from a stationary shop.
Therefore, in an environment that allows multiple inheritances, interfaces/totally-abstract-classes are useful when we just wish to declare unfulfilled contracts that someone else could fulfill.
In an environment that disallows multiple inheritances, having interfaces is the only way to allow an implementing class to project multiple personalities.
Consider
interface Transportation
{
takePassengers();
gotoDestination(Destination d);
}
class Motorcar implements Transportation
{
cleanWindshiedl();
getOilChange();
doMillionsOtherThings();
...
takePassengers();
gotoDestination(Destination d);
}
class Kayak implements Transportation
{
paddle();
getCarriedAcrossRapids();
...
takePassengers();
gotoDestination(Destination d);
}
An activity requiring Transportation has to be blind to the millions alternatives of transportation. Because it just wants to call
Transportation.takePassengers or
Transportation.gotoDestination
because it is requesting for transportation however it is fulfilled. This is modular thinking and programming, because we don't want to restrict ourselves to a Motorcar or Kayak for transportation. If we restricted to all the transportation we know, we would need to spend a lot of time finding out all the current transportation technologies and see if it fits into our plan of activities.
We also do not know that in the future, a new mode of transport called AntiGravityCar would be developed. And after spending so much time unnecessarily accommodating every mode of transport we possibly know, we find that our routine does not allow us to use AntiGravityCar. But with a specific contract that is blind any technology other than that it requires, not only do we not waste time considering all sorts of behaviours of various transports, but any future transport development that implements the Transport interface can simply include itself into the activity without further ado.

None of the answers yet mention the key word: substitutability. Any object which implements interface Foo may be substituted for "a thing that implements Foo" in any code that needs the latter. In many frameworks, an object must give a single answer to the question "What type of thing are you", and a single answer to "What is your type derived from"; nonetheless, it may be helpful for a type to be substitutable for many different kinds of things. Interfaces allow for that. A VolkswagonBeetleConvertible is derived from VolkswagonBeetle, and a FordMustangConvertible is derived from FordMustang. Both VolkswagonBeetleConvertible and FordMustangConvertible implement IOpenableTop, even though neither class' parent type does. Consequently, the two derived types mentioned can be substituted for "a thing which implements IOpenableTop".

Related

Excluding member functions and inheritance, what are some of the most common programming patterns for adding functionality to a class?

There're likely no more than 2-4 widely used approaches to this problem.
I have a situation in which there's a common class I use all over the place, and (on occasion) I'd like to give it special abilities. For arguments sake, let's say that type checking is not a requirement.
What are some means of giving functionality to a class without it being simply inheritance or member functions?
One way I've seen is the "decorator" pattern in which a sort of mutator wraps around the class, modifies it a bit, and spits out a version of it with more functions.
Another one I've read about but never used is for gaming. It has something to do with entities and power-ups/augments. I'm not sure about the specifics, but I think they have a list of them.
???
I don't need specific code of a specific language so much as a general gist and some keywords. I can implement from there.
So as far as I understand, you're looking to extend an interface to allow client-specific implementations that may require additional functionality, and you want to do so in a way that doesn't clutter up the base class.
As you mentioned, for simple systems, the standard way is to use the Adaptor pattern: subclass the "special abilities", then call that particular subclass when you need it. This is definitely the best choice if the extent of the special abilities you'll need to add is known and reasonably small, i.e. you generally only use the base class, but for three-to-five places where additional functionality is needed.
But I can see why you'd want some other possible options, because rarely do we know upfront the full extent of the additional functionality that will be required of the subclasses (i.e. when implementing a Connection API or a Component Class, each of which could be extended almost without bound). Depending on how complex the client-specific implementations are, how much additional functionality is needed and how much it varies between the implementations, this could be solved in a variety of ways:
Decorator Pattern as you mentioned (useful in the case where the special entities are only ever expanding the pre-existing methods of the base class, without adding brand new ones)
class MyClass{};
DecoratedClass = decorate(MyClass);
A combined AbstractFactory/Adaptor builder for the subclasses (useful for cases where there are groupings of functionality in the subclasses that may differ in their implementations)
interface Button {
void paint();
}
interface GUIFactory {
Button createButton();
}
class WinFactory implements GUIFactory {
public Button createButton() {
return new WinButton();
}
}
class OSXFactory implements GUIFactory {
public Button createButton() {
return new OSXButton();
}
}
class WinButton implements Button {
public void paint() {
System.out.println("I'm a WinButton");
}
}
class OSXButton implements Button {
public void paint() {
System.out.println("I'm an OSXButton");
}
}
class Application {
public Application(GUIFactory factory) {
Button button = factory.createButton();
button.paint();
}
}
public class ApplicationRunner {
public static void main(String[] args) {
new Application(createOsSpecificFactory());
}
public static GUIFactory createOsSpecificFactory() {
int sys = readFromConfigFile("OS_TYPE");
if (sys == 0) return new WinFactory();
else return new OSXFactory();
}
}
The Strategy pattern could also work, depending on the use case. But that would be a heavier lift with the preexisting base class that you don't want to change, and depending on if it is a strategy that is changing between those subclasses. The Visitor Pattern could also fit, but would have the same problem and involve a major change to the architecture around the base class.
class MyClass{
public sort() { Globals.getSortStrategy()() }
};
Finally, if the "special abilities" needed are enough (or could eventually be enough) to justify a whole new interface, this may be a good time for the use of the Extension Objects Pattern. Though it does make your clients or subclasses far more complex, as they have to manage a lot more: checking that the specific extension object and it's required methods exist, etc.
class MyClass{
public addExtension(addMe) {
addMe.initialize(this);
}
public getExtension(getMe);
};
(new MyClass()).getExtension("wooper").doWoop();
With all that being said, keep it as simple as possible, sometimes you just have to write the specific subclasses or a few adaptors and you're done, especially with a preexisting class in use in many other places. You also have to ask how much you want to leave the class open for further extension. It might be worthwhile to keep the tech debt low with an abstract factory, so less changes need to be made when you add more functionality down the road. Or maybe what you really want is to lock the class down to prevent further extension, for the sake of understand-ability and simplicity. You have to examine your use case, future plans, and existing architecture to decide on the path forward. More than likely, there are lots of right answers and only a couple very wrong ones, so weigh the options, pick one that feels right, then implement and push code.
As far as I've gotten, adding functions to a class is a bit of a no-op. There are ways, but it seems to always get ugly because the class is meant to be itself and nothing else ever.
What has been more approachable is to add references to functions to an object or map.

IoC for a list of named objects

I'm looking for advice on this problem and whether service locator and class naming conventions are an ok solution (I tend to avoid these anti-patterns), and potential performance ramifications.
An app has a collection of objects implementing the same interface, distinguished by name. For example:
public interface IDog {
void Bark();
}
public class Pug: IDog {
public void Bark() {
// Pug bark implementation
}
}
public class Beagle: IDog {
public void Bark() {
// Beagle bark implementation
}
}
In the code, when you need an IDog, you only know a string name that is passed to you, for example "Pug" or "Beagle". In this case the string may contain special characters (example: <breed:pug />)
There are a few proposed solutions that have come about:
Using reflection, find the implementation needed where the string name == implementation name.
Add an addribute to each class, use reflection where string name == attribute property. Ex [DogBreed("Pug")]
Add a Breed property to the IDog interface. Inject a IList into a factory class, and have it retrieve the matching dog. Ex.
Private IList _dogs;
Public DogFactory(IList<IDog> dogs) {
_dogs = dogs;
}
Public IDog GetDog(string dogBreed) {
return _dogs.First(x => x.Breed == dogBreed);
}
1 and 2 use service locator. 1 uses an implied naming convention that you will only know by seeing the reflection code. 3 the concern is that all of the objects will be built in memory even though you only need a single implementation.
I personally have leaned towards #3 in the past. Object creation should be cheap. However, this is a legacy web app and objects down the chain may have heavy initialization cost. This application uses Unity for IoC.
Option 1.
This option sounds like the Partial Type Name Role Hint idiom. If you inject the list of candidates and find the appropriate Strategy among those candidates, it's just plain old Constructor Injection, and has nothing to do with Service Locator (which is a good thing).
Option 2.
This option sounds like the Metadata Role Hint idiom. Again, if you inject the list of candidates via the constructor, Service Locator is nowhere to be seen.
Option 3.
This options sounds like a variation of the Role Interface Role Hint idiom. Still supports use of good old Constructor Injection.
Personally, I tend to favour Partial Type Name Role Hint because this design doesn't impact the implementation of any business logic. All the selection logic becomes a pure infrastructure concern, and can be defined independently of the implementations and clients.
When it comes to the cost of composing the relevant object graphs, there are ways to address any issues in clean ways.

Base Classes "Entity" and "ValueObject" in Domain-Driven Design

Do you always create these two abstract base classes as the basis of any new project in DDD?
I've read that Entity should have two things. First, an identity property, probably of a generic type. Second, an Equals() method that determines whether it's the same as another Entity. Anything else? Any other natural methods or rules of thumb?
I like to have a common abstract ancestor for all my Domain objects but that is a matter of preference and overall infrastructure requirements.
After that, yes I have abstract classes for Entity and Value objects.
Don't forget that also overriding Equals for Value objects to return equality based on equal property state can be important.
Also people frequently overlook the value of packages. Put all these core base classes in their own "kernel" library and don't be reluctant to split your domain model into multiple assemblies instead of winding up with a single large "Domain Library".
If you're using .NET/C#, I've published a set of DDD interfaces and classes for public use. Take a look to see what typically goes inside them. The embedded code comments should hint towards their usage.
You can [download it here][1]. Project is dead now.
I've never needed the Equals() method in my applications thus far. Your mileage may vary though.
However, I create empty interfaces and use them as descriptors:
public interface IAggregateRoot {}
public interface IEntity {}
public interface IValueObject {}
public class Order : IAggregateRoot
{
...
}
public class State : IValueObject
{
...
}

When are object interfaces useful in PHP? [duplicate]

This question already has answers here:
What is the point of interfaces in PHP?
(15 answers)
Closed 8 years ago.
From php.net:
Object interfaces allow you to create code which specifies which methods
a class must implement, without having to define how these methods are handled.
Why should I need to do that? Could it be a kind of 'documentation'?
When I'm thinking about a class I have to implement, I know exactly which methods I should code.
What are some situations where interfacing a class is a "best practice"?
Short answer: uniform interfaces and polymorphism.
Longer answer: you can obviously just create a class that does everything and indeed you'd know what methods to write. The problem you have with using just concrete classes, however, is your lack of ability to change. Say you have a class that stores your users into a MySQL database, let's call it a UserRepository. Imagine the following code:
<?php
class UserRepositoryMysql {
public function save( User $user ) {
// save the user.
}
}
class Client {
public function __construct( UserRepositoryMysql $repos ) {
$this->repos = $repos;
}
public function save( User $user ) {
$this->repos->save( $user );
}
}
Now, this is all good, as it would actually work, and save the User to the database. But imagine your application will become populair, and soon, there is a question to support PostgreSQL as well. You'll have to write a UserRepositoryPostgresql class, and pass that along instead of UserRepositoryMysql. Now, you've typehinted on UserRepositoryMysql, plus you're not certain both repositories use the same methods. As an aside, there is little documentation for a potential new developer on how to implement his own storage.
When you rewrite the Client class to be dependent upon an interface, instead of a concrete class, you'll have an option to "swap them out". This is why interfaces are useful, obviously, when applied correctly.
First off, my php object coding is way behind my .net coding, however, the principles are the same. the advantages of using interfaces in your classes are many fold. Take for example the case where you need to return data from a search routine. this search routine may have to work across many different classes with completely different data structures. In 'normal' coding, this would be a nightmare trying to marry up the variety of different return values.
By implementing interfaces, you add a responsibility to the clsses that use them to produce a uniform set of data, no matter how disparate they may be. Another example would be the case where you are pulling data from different 'providers' (for example xml, json, csv etc, etc). By implementing an interface on each class type, you open up the possibilities to extend your data feeds painlessly by adding new classes that implement the interface, rather than having a mash-up of switch statements attempting to figure out what your intentions are.
In a word, think of an interface as being a 'contract' that the class 'must' honour. lnowing that means that you can code with confidence for that given scenario with only the implementation detail varying.
Hope this helps.
[edit] - see this example on SO for a fairly simple explanation:
An interface is a concept in Object Oriented programming that enables polymorphism. Basically an interface is like a contract, that by which classes that implement it agree to provide certain functionality so that they can be used the same way other classes that use the interface
purpose of interface in classes
The first case that comes to my mind is when you have a class that uses certain methods of another class. You don't care how this second class works, but expects it to have particular methods.
Example:
interface IB {
public function foo();
}
class B implements IB {
public function foo() {
echo "foo";
}
}
class A {
private $b;
public function __construct( IB $b ) {
$this->b = $b;
}
public function bar() {
$this->b->foo();
}
}
$a = new A( new B() );
$a->bar(); // echos foo
Now you can easily use different object passed to the instance of class A:
class C implements IB {
public function foo() {
echo "baz";
}
}
$a = new A( new C() );
$a->bar(); // echos baz
Please notice that the same bar method is called.
You can achieve similar results using inheritance, but as PHP does not support multiple inheritance, interfaces are better - class can implement more than one interface.
You can review one of PHP design patterns - Strategy.
Say you're creating a database abstraction layer. You provide one DAL object that provides generic methods for interfacing with a database and adapter classes that translate these methods into specific commands for specific databases. These adapters themselves need to have a generic interface, so the DAL object can talk to them in a standardized way.
You can specify the interface the adapters need to have using an Interface. Of course you can simply write some documentation that specifies what methods an adapter needs to have, but writing it in code enables PHP to enforce this interface for you. It enables PHP to throw helpful error messages before a single line of code is executed. Otherwise missing methods could only be found during runtime and only if you actually try to call them, which makes debugging a lot harder and code much more unreliable.

What is the point declaring variables at the end of class?

I saw multiple examples in MSDN that uses to declare the internal fields at the end of the class. What is the point?
I find this a little embarrassing, because each time Visual Studio adds a method it adds it to the end of the class, so there is need every time to move it...
class A
{
public A(){}
// Methods, Properties, etc ...
private string name;
}
class A
{
private string name;
public A(){}
// Methods, Properties, etc ...
}
In C++, it makes sense to put the public interface of the class at the top, so that any user of the class can open up your header file and quickly see what's available. By implication, protected and private members are put at the bottom.
In C# and Java, where interface and implementation are completely intertwined, people would probably not open your class's source code to see what's available. Instead they would rely on code completion or generated documentation. In that case, the ordering of the class members is irrelevant.
If it's obvious the variable has been declared, and the code is by way of an example, then arguably this gets you to the bit being demonstrated quicker - that's all I can think of.
Add-ins like ReSharper will allow you to standardise and automatically apply this layout at the touch of a key combination, by the way, if it is what you want.
Many programmers strive for self-documenting code that helps clients to understand it. In C++ class declaration, they would go from most important (i.e. what is probably most frequently inspected) to least important:
class Class {
public:
// First what interest all clients.
static Class FromFoobar(float foobar); // Named constructors in client code
// often document best
Class(); // "Unnamed" constructors.
/* public methods */
protected:
// This is only of interest to those who specialize
// your class.
private:
// Of interest to your class.
};
Building on that, if you use Qt, the following ordering might be interesting:
class SomeQtClass : public QObject {
public:
signals: // what clients can couple on
public slots: // what clients can couple to
protected:
protected slots:
};
Then the same down for protected and private slots. There is no specific reason why I prefer signals over slots; maybe because signals are always public, but I guess the ordering of them would depend on the situation, anyhow, I keep it consistent.
Another bit I like is to use the access-specifiers to visually seperate behaviour from data (following the importance ordering, behaviour first, data last, because behaviour is the top-interest for the class implementor):
class Class {
private:
void foobar() ;
private:
float frob_;
int glob_;
};
Keeping the last rule helps to prevent visual scattering of class components (we all know how some legacy classes look like over time, when variables and functions are mixed up, not?).
I don't think there is any valid reason for this. If you run Code Analysis on a class declared like this you'll get an error as private fields should be declared on top of classes (and below constants).