Interface and Baseclass can be combined together? [closed] - oop

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
After reading Interface vs Base class I understand that Inheritance should be used where there exists a "is-a" relationship and interfaces should be used in "can-do" kind of places.
If that means, base class can only have business objects and interfaces will have only the contracts?
For e.g Dog class will have a base class Animal with properties like Eye,Nose,Leg etc and interface IAnimal will have "Run", "Jump" etc.
Will design applicable for all the scenarios?

The answers on that question you linked actually say it all. Especially the accepted answer and its first comment. You use an interface to declare the contract and a base class for shared implementation.
I'd consider it a common practice to define interfaces for (almost) everything. An interface can also contain getters and setters and therefore define its subtypes properties. If two or more classes that implement that interface share some implementation, you can moved that to a base class. That base class would then also implement the interface.

Your understanding is correct, but I think it relies more on good practices than actual language rules. Please consider the following:
In languages that support multiple inheritance (C++) interfaces are just classes with all methods virtual and abstract. See this question
Languages that don't allow multiple inheritance (Java), the most important difference is that a class can have no more than 1 superclass, but can implement an arbitrary number of interfaces. There are also differences in declaring variables (variables are implicitly static and final in Java interfaces) but it's still not a big leap to think of interfaces as of 100% abstract classes.
Java 8 introduced default methods (see this question), which can kind of blur the obvious distinction between those two.
So while technically it's not true neither that interfaces must only define the contract (default methods can implement a fallback behavior in a Java 8 interface) nor that abstract classes must define behavior (because a pure abstract class with no implementations can exist), the approach that you described is kind of reasonable and common in real world.

It depends.....
That's a good starting point but it is not right to say that it will be applicable in all scenarios. Systems keep changing and as part of refactoring (http://refactoring.com/catalog/) sometimes interfaces become subclasses and the other way round. Interfaces are good for Mix-ins which you mention as "can-do" kind of behavior and Inheritance where a group of classes share certain properties and possibly some behavior enabling reuse and avoiding code duplication (which is essentially what a IS-A relationship is). You can read more about it in Effective Java by Joshua Bloch (there is an item on Interfaces and Inheritance).
If we take your example, the methods "Run" and "Jump" can be either defined in Animal base class or they can go in an interface as you mention, in fact they can actually go in multiple interfaces too. So you might start off by building a inheritance hierarchy and later refactor them into interfaces as the system evolves.

Related

Do I need an interface if there is just one implementation? [duplicate]

This question already has answers here:
Java Interfaces Methodology: Should every class implement an interface?
(13 answers)
Closed 7 years ago.
I have been doing OOP for a quite while and I got confused with usages of interfaces after an argument with a colleague few days before.
Basically, I have been using interfaces when I apply design patterns, especially when there are multiple classes implementing common features.
In my application, there is Hibernate layer and few Sevices classes as example UserService, CompanyService, etc.
The question was whether we keep, separate interfaces also for each Service classes. Such as UserServiceContract, CompanyContract and etc.
My colleague argument was, there is no need to have interfaces.
I came across that in this tutorial also, the author has used interfaces. But there is no common interface that implements several classes only once.
example interface implentation
The benefit of using the interfaces was in this situation, it improves the code structure. Yes, there is IDE features that show what methods available for a class. But, I still want to get your guys idea too about this.
When you are talking design patterns and best coding practices, needing is not what you should be asking yourself. You do not need most of what you do, at least not immediately. Of course you do not know whether you will need different implementations of that contract until you actually do. So this is not a question of what you need right now. This is a question of what you will wish you had later.
What you have seen in the link you posted is the D in SOLID: the Dependency Inversion Principle:
Depend on abstractions, not on implementations.
You are better safe than sorry, you know.
EDIT: Also, I would advise against sufixes for interfaces (or prefixes). If you will be using the interface instead of the implementation, make the interface's name clean. A common choice would be, in your case, UserService for the interface and UserServiceImpl for the implementation.

In OOP what are the different meanings of interface in the different contexts they apply to [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I'm a bit new to object oriented programming. On my journey I have come across something that has had me confused for a few days now. It is the term "interface" and how it has different meanings in different contexts and even different programming languages. I want to understand "interface" but when I do my research I seem to get different definitions as if it has multiple meanings.
Would someone kindly give me a concise definition of interface in each context (just the main ones)?
I purchased a book called the object oriented thought process by Matt Weisfeld where some of them have been identified which are below:
Graphical user interface
The interface to a class is basically the signatures of its methods
Objective-C code can be broken up into physically separate modules called interface and impelentation
A Java-style interface and an Objective-C protocol are basically the contract between a parent class and a child class
(Are there any more uses/definitions of the term interface in OOP than those identified above?)
If someone would kindly explain the different contexts of the term interface in OOP it would be highly appreciated.
Short answer:
Your 4th bullet point probably comes closest to the generally accepted notion of what OOP interfaces are: contracts between parties that need to interact with one another. Such contracts define the means (a) provided by one party, and (b) required by the other, in order to do so.
Long answer:
Very generally speaking, an interface is a thing that allows two (possibly very different) entities to interact with each other; it enables them to work together while at the same time allowing them to stay apart. The interface is the "common ground" that both parties agree on.
(Can be as simple as a door lock: Both the lock and any key able to work it must "fit together" in one place; you could call that place the interface.)
How does this general definition apply to your list?
Graphical user interface
A GUI allows humans and computer programs to interact. It does not require the computer to become fully human (and listen with ears, talk with the mouth, smile, etc.), neither does it require of the human to become a computer program itself. (UIs from past decades excluded. :)
"The interface to a class is basically the signatures of its methods"
The (publicly visible) methods and their exact signatures are the only means by which other types are going to be able to interact with that class, so in that sense, they together form that class' interface.
Also, a general description of each constructor and method is typically a part of the interface as well as a short general description of the purpose of the class and each of its methods. And of course, the name of the class itself -- pretty important.
"Objective-C code can be broken up into physically separate modules called interface and [implementation]"
I don't know Objective-C well enough to comment on that, but many languages have a module system that allows you to partition your codebase into separate, functionally independent modules. These usually don't have to expose all their types and functions to outsiders; each module may carefully declare what can be seen by other modules. As above, all that is chosen to be exposed is the "interface", because it will be the only way to interact with whatever is in the module. That "whatever is in the module" stays hidden; it's called the "implementation", and outsiders should not have to know about it.
"A Java-style interface and an Objective-C protocol are basically the contract between a parent class and a child class"
This is perhaps what comes closest to the generally accepted notion of interfaces in OOP: That they are contracts between parties that want to interact. See short answer at the beginning of this question.
Basically, a Java interface allows us to describe a group of methods and their exact signatures, but it won't allow us to provide the implementation. Therefore it's a pure interface; it cannot be called directly. It only describes how one could interact with a class that actually implemented it. (The two parties do not necessarily have to be "parent" and "child".)
Ideally, an interface should not just state what one class has to offer; it should also describe what a typical consumer will need, thereby keeping the interface focused in a well-encapsulated system. (I am referring to the Single-Responsibility Principle here.)
Interface is a concept of abstraction and encapsulation. It is basically a contract you should comply to or given to ie, Interface is just a contract between two parties so that they know how they will interact with each other. An interface generally defines how you can interact with a class, the methods that it supports.
An interface contains only the signatures of the methods. The methods dont have anything neither interface can do anything. It is just a pattern.
Now in this anAbstarctMethod() is the Interface which is defined and it only has signatures but it doesnot have the implementation. Now when the class ASubClass implements the ineterface then the actual implementation is provided to the interface.
As far as Graphical user Interface is concerned I dont think that may necessarily be Object Oriented Programming. The wiki says that a graphical user interface is just a user interface through which you can interact with the electronic devices through icons and other indicators.
The Java doc has given a good example for this:-
Methods form the object's interface with the outside world; the
buttons on the front of your television set, for example, are the
interface between you and the electrical wiring on the other side of
its plastic casing. You press the "power" button to turn the
television on and off.
A good example from here:-
An interface is a description of the actions that an object can do...
for example when you flip a light switch, the light goes on, you don't
care how, just that it does. In Object Oriented Programming, an
Interface is a description of all functions that an object must have
in order to be an "X". Again, as an example, anything that "ACTS LIKE"
a light, should have a turn_on() method and a turn_off() method. The
purpose of interfaces is to allow the computer to enforce these
properties and to know that an object of TYPE T (whatever the
interface is ) must have functions called X,Y,Z, etc.
You may also check Why Use Interfaces?
Another powerful design technique is to have a single class implement
multiple interfaces. If you do this, you will have objects that
support multiple interfaces and, therefore, multiple behaviors. When
used together with run-time type inspection, this becomes very
powerful.
In OOP, the term "interface" means basically all the method signatures for all the messages that can be sent to objects of a class. So in Objective-C, it would be all the method declarations in the header file.
The term "Graphical User Interface" is not using the word "interface" in an OO context.
Item #2 on your list is an OO interface.
Item #3 is referring to the .h and .m files.
Item #4 refers to the keyword 'interface' in the Java language and equating it to the keyword 'protocol' in the objective-C language.
General meaning:
An Interface is essentially something that interacts with something else
For example: An interface can be with a python application and the Skype-API (thought off the top of my head xD)
An interface is a form of multiple inheritance (without the 'alleged' complications that brings) (it's a controversial subject)
OO is founded on the "is a" relationship, MI (multiple inheritance) allows an object to be several things. Interfaces define a way for them to be these things, without an implementation.
They are "what you must to _to be a _ whatever".

Are interfaces redundant if using abstracts as an interface?

I'm reading through Design Patterns by GoF and I'm starting to wonder. Are interfaces redundant if you're using an abstract as the interface in languages like C#? Let's put multiple inheritance aside for a moment, as I understand you can only achieve that (in C#) through interfaces.
I'm trying to apply this logic to DDD in C#. Almost every example and implementation I've ever seen uses interfaces. I'm starting to wonder why. Could the abstract class be used instead? It seems to me that this would be a more robust solution, but then again I could be missing something, which is why I'm asking here.
Summary:
Question 1: In the context of OOP with a language that only supports single inheritance, if designed properly what are some uses
of interfaces over the abstract class?
Question 2: In the context of DDD, if designed properly what are the uses of interfaces over the abstract class?
Note:
I've read through all the similar questions listed, but none seem to give me an answer. If I missed one, please let me know.
For question 1: regardless of support for multiple inheritance interfaces are contract specifications, abstract classes are base classes.
Interfaces provide a way for a class to specify a set of capabilities ( think IDisposable, IEnumerable, etc ) and it's recommended that they obey the Interface Segregation Principle.
Abstract classes should implement a concept that can be extended, or that can have different implementations depending on the context ( think HttpContextBase, AbstractButton etc ).
The biggest difference between interfaces and abstract classes is conceptual. You can argue that, except inheritance, an interface is the same as an abstract class with only abstract methods, but conceptually they represent different things.
As for question 2: in the context of DDD interfaces are implementations details. I dare say you can do DDD and not use interfaces or abstract classes, or even inheritance. As long as you have your bounded contexts, aggregates, entities and VOs well defined.
In conclusion, when you try to express a contract use an interface, when you want to indicate that your class has some capability, implement an interface. When you have a concept for which you can provide more implementations depending on context, use a base class ( abstract or not ).
When you think about it like this, the decision of the language makers ( c# ) to allow only single inheritance, but allow implementation of multiple interfaces makes a lot of sense.
The advantage of Interfaces is precisely that there is no multiple-inheritance. By using an Interface you can allow classes like Forms, UserControls, Components, etc to participate in interactions that would otherwise be diffucult/impossible.
I recommend doing both. I usually create an interface, and (if possible) then create an abstract class that inherits that interface to provde any common or default implementaion of that interface. This gives you the best of both worlds.
interfaces are not redundant. an interface is independent of implementation while abstract classes are implementation. code that uses an interface does not have to be changed or recompiled if some implementation class changes.
the advantage is above. if you are doing ddd, start out with concrete classes and write some tests. refactor common stuff into base classes (some will be abstract). if there is a reason to make an interface go ahead and do so. repeat until done.

OOP software design problem [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
There are two classes:A and B.
And I need to implement a function whoViewed,
I have two options,make it an member function of A and B.Which smells a little duplicate.
Another choice is to make it a separate class:Viewer,but it's more abstract.
If you were me,which way will you choose?
To make it more general:
what will you do when you need to get statistic information across different classes(like get the latest viewed 10 entities{which can be A or B} from database) within the scope of OOP.
I would recommend not using inheritance and instead go with composition. Create a class called ViewMonitor which will handle the shared functionality. The odds are that there is no logical way to design an inheritance structure.
Obviously duplicating the whoViewed() method in 2 places is bad, so that option is off the table. You have a third option: Create a parent class that implements whoViewed() and have A and B inherit from it. The famous Gang of Four Design Patterns book recommends favoring composition over inheritance. So this would suggest making the Viewer class you mentioned in the question. Given the limited context provided in your question, I would suggest taking the GoF's advice and going with the Viewer class.
Incidentally, if you expect the implementation of whoViewed() to be different in A and B, you could make Viewer an interface and implement the interface in A and B.
if WhoViewed in A and B has the exact same functionality, make a class, from which they can inherit.
If the implementation of the method is different for both classes, of if they already inherit from another class, use an interface for A and B.
I would not suggest to introduce inheritance here, because it is serious decision, require that both classes to be truly polymorphic in all aspects.
In this case - make implementation in the third class, make this class a member of A and B, and then delegate call to the whoViewed method to this member.
In a pseudo code:
class C
{
WhoViewed();
}
Class A{
C m_C;
WhoVied{
m_c.WhoViwed();
}
In the B do the same as in A.
If speaking in OOD language - replace inheritance with delegation.
I would use composition and delegate to an external object. Your problem sounds like a cross cutting concern, hence AOP could be an option for you.
Depending on the language you could use Mixins (Ruby) or Traits (Scala).
This seems more like an AOP problem and should be solved using an aspect.
If you can think of the "who Viewed" as an aspect that you can then store the latest viewed 10 entities from database.
You would then intercept the calls to your entities and store the required metadata off in an easy to locate location.
if whoViewed() implementation is same for both then I would like to have a seperate helper class or an abstract class which is inherited by both A and B.
if whoviewed() implementation is ways apart write them in their respective classes.

What's the difference between an interface and an abstract class? [duplicate]

This question already has answers here:
Closed 13 years ago.
Duplicate:
When to use an interface instead of an abstract class and vice versa?
Probably one of the most famous software developer job interview questions.
What would be your answer?
EDIT: I'm trying to find out how you would answer this in a real-life situation. Please try to formulate your answer as you would on a real job interview (be complete, but don't be too long, post no links of course).
An interface only describes the actual signature of its methods etc. Any class implementing that interface must then provide an explicit implementation.
An abstract class can contain a partial implementation of its methods etc.
An abstract class can have member variables, an interface cannot (or, in C++, should not).
In Java, an "Interface" is a well-defined syntactical element, while in C++ it's merely a design pattern.
Interfaces provide definitions of methods that must be implemented by a class. The purpose of interfaces is to allow you to generalise specific functionality regardless of implementation. You may have an IDatabase interface that has an Open/Close method. The class that implements that interface may be connecting to a MySQL database or MS Access database. Irrespective of how it accomplishes this task, the goal is still the same...Open database, close database.
Abstract classes are base classes that contain some abstract methods. They cannot be instantiated they are to be derived from. The purpose of an Abstract class is to allow you to define some generic functionality and sub-class to implement more specific functionality where appropriate.
So in summary, you should use interfaces when the implementation of each class differs completely. Use abstract classes when you have some similar behaviour but need to implement parts differently.
Hope that helps.
I would say that the difference is language dependent, but that in C++ at least, abstract classes are the means by which interfaces are implemented.
As far as job interviews are concerned, I've always heard that the key point is that an interface is a contract; an interface, while not implementing it itself, guarantees functionality.