OOP Task (class hierarchy, inheritance, interface, etc.) - java

Since I am trying to learn more about OOP (Java) I'm working my way through some literature where I found this 'task'. Unfortunately I am having kind of a hard time since I am pretty new to OOP and I don't have any sample solution to this. Maybe some of you can give me some input so can work my way through this.
Define a class hierarchy for these classes:
quadrilateral
convex quadrilateral
trapezoid
parallelogram
rhombus
rectangle
square
Create an instance of each class if possible
Define reasonable attributes and methods in each class
Overload and override methods
Write reasonable constructors for each class
Use modifiers (abstract, static, final, public, protected and private) in a meaningful way
How could an interface be used for this task?
01 Class hierarchy
Okay, this is simple math and you can find tons of information on the hierarchy of quadrilaterals everywhere. Here is what I did:
Creating Objects of each class is no big deal, but I still have some problems with understanding all the OOP-techniques. There are some points where I don't know what would be the better way to do it... (e.g. the square which inherits from two classes, which in java is simply not possible). Also, formulas (like calculating the surface area) would be overwritten all the time anyhow (since they are different most of the time), so why would I need inheritance anyway? Couldn't I just use an interface, use it in all of those classes an force them to implement these formulas?
Greetings - Vulpecula

In real life, you probably would be better off using an interface. Deep inheritance structures like that are often frowned upon; it's generally considered good to 'prefer composition over inheritance' (http://en.wikipedia.org/wiki/Composition_over_inheritance). You might for instance have a 'quadrilateral' interface that defines 'surface area' and 'perimeter', and then have the other shapes satisfy that interface.
If this is a homework question however, then you should probably base the class hierarchy on whatever examples your textbook/teacher have provided previously. It's not about designing robust software, it's about proving to your teacher that you learned how to do things in whatever way they think you should do them.

An abstract class as the base of a moderately complicated hierarchy is not as flexible as an interface. A class--abstract or not--forces a specific type of implementation.
Without thinking too hard about it, here's one way to start:
public interface Quadrilateral {
int getTopMillimeters();
int getLeftMillimeters();
int getRightMillimeters();
int getBottomMillimeters();
}
From this raw data, you could also define
getTopLeftAngle(), getTopRightAngle(), ...
which would all compute their values based on the lengths.
I too would emphasize composition over inheritance. The end-effect can indeed be a complex inheritance structure.
For me, composition is heirarchy of "Composer" classes, which do NOT implement the interface. Such as
public class QuadrilateralComposer {
private final int iTopMM;
private final int iBtmMM;
...
public QuadrilateralComposer(int i_topMM, int i_bottomMM, ...) {
if(i_topMM < 1) {
throw new IllegalArgumentException...
}
if(i_bottomMM < 1) {
throw new IllegalArgumentException...
}
...
iTopMM = i_topMM;
iBtmMM = i_bottomMM;
...
}
public int getTopMillimeters() {
return iTopMM;
}
...
Which is then composed by an abstract class:
public class AbstractQuadrilateral implements Quadrilateral
private final QuadrilateralComposer qc;
public AbstractQuadrilateral(int i_topLen, int i_bottomLen, ...) {
gc = new QuadrilateralComposer(i_topLen, i_bottomLen, ...);
}
public int getTopLength() {
return gc.getTopLength();
}
...
Abstract classes never extend other abstract classes, they only use internal Composers (and actually implement the interface). On the other end, Composers only extend Composers, and use other composers internally.
(Three notes: Protected functions are in the Composer as public function_4prot() and are implemented as protected function(), which call the _4prot version. And sometimes the abstract class can indeed implement everything in the interface. In this case, it would be concrete [non-abstract] and be named "SimpleXYZ", instead of "AbstractXYZ". Finally, static utility functions reside in the Composer.)
If EVERY interface is designed in this way, then ANY class can easily implement ANY interface, regardless which class they must actually extend. If abstract classes extend other abstract classes, that is a lot more work for classes that need to implement the interface, but happen to--and have to--extend something else.
This is not what you asked, but learning this concept changed my code for the WAY better. Seeing it mentioned in the accepted answer made me think through all of it. I've actually been slowly drifting away from inheritance to composition over the past few years, and after reading Effective Java, it was the final nail in the inheritance coffin, as it were.

Okay, the plan now is that I am trying to resolve this without any interface first. So here's the map of inheritance:
I am ignoring the fact, that the square is not only a rectange but also a rhombus.
The abstract class (quadrilateral) will define (but not implement) methods for calculating 'surface area' and 'perimeter'. Overriding methods is easy since every shape has different formumals for calculation but I am not really sure where I could use the overloading feature.
One more thing: Using an interface, would this be the desired way?

Related

Generalize a pair of method without lossing static typing checks

I am working with a pet project trying to practice (pure?) OO and can not figure out how to factorize a common behavior from a couple of classes.
public Solution improve(Solution initialSolution)
{
stopCondition.setInitialSolution(initialSolution);
Solution nextSolution = initialSolution;
do
{
nextSolution = nextSolutionGenerator.generate(nextSolution);
}
while(!stopCondition.isStopConditionReached());
return nextSolution;
}
As you can see, generate is common to both BinaryNextSolutionGenerator and PermutationNextSolutionGenerator. I know that Solution generate(Solution solution) should be in NextSolutionGenerator, however I do not want to lose the type verification at compile time if I send a PermutationSolution instance into a BinaryNextSolutionGenerator instance.
Looks like I have to use generic programming or my design is fundamentally wrong (or is a common tradeoff?), but I would prefer some experienced opinion before.
BTW, generate only calls doGenerate because I am planning to add some common logging code in there.
Make/refactor Solution and Generator to interfaces.
a "good place" for generics would be to refactor Integer getVariable(int idx) to <V extends java.lang.Number> getVariable(int idx)
another "good generic place" is the (exact) type of Soultion "generator.generate"...
Introduce abstract implementations of that interfaces! And put there as much common code as you can (public Solution<V> generate() {...}), enforce needed methods (<S extends Solution<V>> proteced abstract S doGenerate(S prev);) AbstractGenerator is also the place, where you would put the imporve (and public generate) methods.
Extend these abstract classes and implement the enforced methods (with concrete implementations of the solutions)
same with solution builder: work with abstraction, extension
...
https://github.com/xerx593/soq54317950 explains my points better... also outlined improve() and StopCondition<V extends Number, S extends Solution>.

How does an Interface in Java work?

I'm self learning Java, and I'm stuck on a chapter about Interfaces. I simply cannot understand how they work in Java.
I believe I understand perfectly what Interface means and how they apply in everyday situations and technology.
But when it comes to Java, code-wise and logic-wise, I'm stuck. I don't get it. How does the concept work?
Say I have 3 objects, and 1 interface object. 2 Objects are ObjectCalculatingA, ObjectCalculatingB, ObjectMathFunctions, and ObjectInterface.
Supposedly in ObjectInterface there must be some sort of reference to the ObjectMathFunctions, so that ObjectCalculatingA and B can just access the math functions in ObjectMathFunctions without writting them all again in A and B.
Am I right?
An interface exists to facilitate polymorphism. It allows declaring a contract that any class that implements the interface must honor. And so it is a way to achieve abstraction and model complexity by looking for commonality between things.
An example? How about shapes? All shapes have an area, right? So you could have the following classes:
Square
Circle
Then let's say you have another class that allows you to collect shapes, and return the total area:
for (Shape shape in shapes)
{
area += shape.area() //This is polymorphism
}
In the example above, we don't care whether the shape is a square or a circle. We can accept either. We only care that it implements the Shape interface. Each object will provide their own custom implementation of area - these internal details aren't important, only that it honors the area contract . See now how we're managing complexity? We can use the class without having to worry about all of the things that go on inside. At this point what it does is important to us, not how it does it, which lets us focus on the problem at hand not getting distracted by complex details.
This polymorphism is one of the reasons why object oriented programming was considered such a powerful evolutionary step in programming. The other key foundation concepts in Object Oriented Programming are:
Encapsulation
Inheritance
. . . you'll also need to learn these.
Abstract Base Class vs Interface
As a comment said, another way to achieve polymorphism is to use an Abstract Base Class. Which should you choose?
Use an interface class implementing it will have its own hierarchy and dependencies. For example a media player. A Movie Player and a Sound Player might have totally different base classes, so use an interface.
Use an Abstract base class when you have some commonality between things, but the specifics vary. For example a message parsing framework.
In simple lay mans language. Interface is a contract and classes implementing the interface need to adhere to the contract. There can be many implementations for same interface and users can select which implementation they wish to use. For more detailed information I suggest you read book like HeadFirst JAVA.
Once you begin software development you will understand that many a times you would come across an already implemented piece of code which you feel is not properly implemented. But at the same time a colleague of yours feels its correctly implemented and serves his purpose. This is where interfaces come into play. Your colleague who feels this implementation works for him can continue using the current one whereas you can implement your new implementation but you need to make sure that it adheres to the interface so that in future if your implementation is better, your colleague will have an oion to switch over.
List<String> myList = new ArrayList<String>();
In above example arraylist is on of the implementations of the List interface. Consider this example, ArrayList is not suiting your requirments so you can do the following.
myList = new LinkedList<String>();
This is the power of 'Coding to interface'
From your example, it shows that you lack a basic understanding of Object-Oriented Programming. You are trying to learn how to run without having learned to stand up yet.
In your example, you assume there is a class ObjectMathFunctions. This is not Object-oriented at all, classes should model a real concept.
1. Learn about objects / classes
You should first learn how classes and objects work. A class is not just any arbitrary division of code, it models something real. Examples: Car, Wheel, etc.
2. Learn about inheritance
After you understand that, learn about inheritance: a Car has a getWeight() method. A Wheel has a getWeight() method as well. Hmm, maybe they are both subdivisions of a broader concept: PhysicalThings. Every PhysicalThing has a getWeight() method.
After this, learn about overriding methods in subclasses, learn about abstract classes, etc.
3. Learn about interfaces
Now you will understand that an interface is very similar to an abstract class. You will have done some exercises where you already encountered the problem "This is a PhysicalThing, but it is also CanExplode (e.g. wheel of car, dynamite, etc). This single inheritance model is annoying, how do I fix this?".
If you know that a class can consist of both data and the functions that operate on the data, then an interface is just a list of the functions that a class has to implement.
Take a light switch interface, ILightSwitch ...
public interface ILightSwitch {
void turnOn();
void turnOff();
}
A class implements an interface if it implements those functions above.
e.g. A LightSwitch class might be
public class LightSwitch implements ILightSwitch {
boolean on = false;
void turnOn() { on = true; }
void turnOff() { on = false; }
}
The LightSwitch class implements the ILightSwitch interface.

In what situation do I need to extend a class? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm learning java and was wondering in what situation you would want to extend a class like here is suggested:
http://5upcodes.blogspot.fi/2013/08/java-inheritance.html
Thanks!
My favorite example of inheritance is the shapes example. All squares are shapes, but not all shapes are squares.
Assume you have a class called "shape". All shapes have perimeter, area etc. These would be the data members of your shapes class.
lets say you wanted to create a class called circle. circle could extend your shape class, so that it would still have the data members of the shape class, and you could add elements that are specific to the circle, such as a radius. (a square wouldn't have a radius).
The circle class would be said to "inherit" from the shape class, because it has all of the features of a shape, and also new features specific only to the circle class.
When you want to create a class that is generally similar to the super class(the class being extended), you extend it and customize it. Overwriting some of it's functions, and/or add functions.
This is a "is-a" scenario, one of the three OOP pillars (inheritance, encapsulation, polymorphism). If you have a class Animal, then you may want to extend a Dog class from Animal. A dog is an animal, but not the other way around. All animals have cells, but dogs have other features aside from that. That'd be a pretty basic idea of it.
The OOP good practice is to program towards interfaces. But in some cases you can take advantage using inheritance: for example, when your top class has a well-defined behavior (i mean concrete code), which all the child classes will inherit - this reduces code, complexity and give you a better maintenance scenario.
In the other hand, if your model is too abstract (the basic behavior is not very clear), then you should think about using interfaces.
And if you're creating real-life software, don't forget design patterns - someone may already solved your problem.
For simple reason we extend one class two another and the funda is called as INHERITANCE.
Say,if you want to create a program in which there are two vehicle class i.e.- Car and Boat, which has similar properties except some.
public class Vehicle
{
void engine()
}
protected class Car extends Vehicle
{
void tyres()
}
protected class Boat extends Vehicle
{
void propeller()
}
You see both vehicle has engines but has different modes as one moves with the help of tyres and another with propeller.
So, two avoid re-writing code of method engine, we inherited it in sub-classes.
Hope, this will help ya !
Extending class is one of basics of OOP, along with interfaces. Lets say, you have general class called Building. It has members like area, city where building is (or coordinates) etc.
Now, with extend, you can specify house to "Cottage", "SkyScraper" etc. They will have functionality of parent + something more (eg. number of levels for SkyScaraper).
The primary reason to use inheritance is to extend behavior of the base class.
For instance, if you're making a video game you might have a Character class that contains all the code needed for a character to navigate the world and do whatever else they do.
You could then extend Character with Player and NPC, so that Player (representing the player character) contains the logic that allows the person playing the game to control their character, and NPC (representing a Non-Player-Character) contains the logic allowing the computer to control the other characters. This way, all of the logic core to every character is encapsulated in the Character class, and the subclasses only have the logic needed to extend specific behavior.
For example, the Character class might have a method for movement.
protected void MoveToLocation(x, y)
{
//movement logic goes here
}
And then the Player class might contain a mouselistener to move the player to wherever is clicked.
public void mouseClicked (MouseEvent mouseEvent)
{
MoveToLocation(mouseEvent.getX(), mouseEvent.getY());
}
And NPC will figure it out on its own somehow
protected void decideWhereToGo()
{
int destinationX, destinationY;
//logic for determining destination
MoveToLocation(destinationX, destinationY);
}
Because they both inherit from Character they both know how to MoveToLocation, and if you ever want to change how that is done you only have to modify the code in one place and every Character (whether they are a Player or NPC they are still a Character by way of inheritence) will have the updated behavior.
When you extend a class, you have a parent-child relation between the original one and the new, extending one.
The child class, the one extending the parent class, will have each and every member of the parent class, without the need to declare them again. Even the private members, though you won't be able to access them directly.
You extend a class when you want the new class to have all the same features of the original, and something more. The child class may then either add new functionalities, or override some funcionalities of the parent class.
You may also use extension when you want to have a set of classes that are related and share some common functionality, but with different implementation when it comes to the details. For example, usually for graphical interfaces you have a Control class, which has functionalities related to rendering and positioning. Then you have its children called Button, Textbox, Combo etc. All have some implementation in common, but each is different in their details.
Make sure to study about interfaces, too. Sometimes you want a lot of related classes so that they have a common set of members, but no shared functionality. In cases like that, it may be better to implement an interface than to extend a common class. An interface is like a class, but with no implementation in it (it serves only to tell you which members its implementors should have).
Generally extending a class is so that you are creating class based on something. For example, in order to create an activity, you must extend Activity. If your class is to setup a IntentService, then you must extend your class to use IntentService.
public class AClassNameHere extends Activity implements OnClickListener {
public class ClassName extends IntentService{
You can extend the superclass to Override super class method to be specific to sub class
example:
In case your superclass is a generic class with generic behaviour, eg Animal class can be a generic class like
class Animal{
private String name;
public String getVoice(){
return "Animal";
}
}
Now you need to create say a class Cat which is of Type Animal but with different voice then you just extend the superclass Animal and just override the getVoice() method
like
class Cat extends Animal{
public String getVoice(){
return "mew";
}
}
Now if you have code like this:
Animal cat= new Cat();
cat.getVoice();//it will return "mew"
Practically this you can use in number of situations like
1. Extending an existing framework class to your custom class.
2. If you are developing any framework you can expose some classes which you want the user to customize.
But overriding introduces IS-A relationship.
There are three major drawbacks with inheritance. Even though the relationship is an "is a" relationship, consider these three while deciding to inheriting a class.
Partial inheritance is not possible. You can't extend partially.
It is statically linked. Inheritance relationship is static. You can't change that relationship at runtime.
You can't restrict the behavior through inheritance. (That is possible in C++ through private inheritance. But not in java )
Almost never. It's best only to extend classes that have been actively designed for it. Most class implementors give no thought to what will happen if people extend their classes. There are all manner of issues.
Composition is your best friend.
Vulnerabilities include
you can no longer correctly implement equals() or hashCode() in subclasses
you are violating encapsulation, and now rely on the internals of another class
you are vulnerable to changes in the parent class
you are required to accept any new methods that get added to the parent class
you must worry about the Liskov Substitution Principle, which can lead to subtle bugs
Josh Bloch, in his excellent book Effective Java, 2nd Edition, talks about this in several places, including items 8, 16 and 17.

Why to use Interfaces, Multiple Inheritance vs Interfaces, Benefits of Interfaces?

I still have some confusion about this thing. What I have found till now is
(Similar questions have already been asked here but I was having some other points.)
Interface is collection of ONLY abstract methods and final fields.
There is no multiple inheritance in Java.
Interfaces can be used to achieve multiple inheritance in Java.
One Strong point of Inheritance is that We can use the code of base class in derived class without writing it again. May be this is the most important thing for inheritance to be there.
Now..
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Then why to make interfaces ?
NOTE : I have found one case in which interfaces are helpful. One example of it is like in Runnable interface we have public void run() method in which we define functionality of thread and there is built in coding that this method will be run as a separate thread. So we just need to code what to do in thread, Rest is pre-defined. But this thing also can be achieved using abstract classes and all.
Then what are the exact benefits of using interfaces? Is it really Multiple-Inheritance that we achieve using Interfaces?
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
We can't. Interfaces aren't used to achieve multiple inheritance. They replace it with safer, although slightly less powerful construct. Note the keyword implements rather than extends.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
They are not. With interfaces a single class can have several "views", different APIs or capabilities. E.g. A class can be Runnable and Callable at the same time, while both methods are effectively doing the same thing.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Interfaces are kind-of multiple inheritance with no problems that the latter introduces (like the Diamond problem).
There are few use-cases for interfaces:
Object effectively has two identities: a Tank is both a Vehicle and a Weapon. You can use an instance of Tank where either the former or the latter is expected (polymorphism). This is rarely a case in real-life and is actually a valid example where multiple inheritance would be better (or traits).
Simple responsibilities: an instance of Tank object in a game is also Runnable to let you execute it in a thread and an ActionListener to respond to mouse events.
Callback interfaces: if object implements given callback interface, it is being notified about its life-cycle or other events.
Marker interfaces: not adding any methods, but easily accessible via instanceof to discover object capabilities or wishes. Serializable and Cloneable are examples of this.
What you are looking for are trait (like in Scala), unfortunately unavailable in Java.
Interfaces are collection of final static fields and abstract methods (Newly Java 8 added support of having static methods in an interface).
Interfaces are made in situations when we know that some task must be done, but how it should be done can vary. In other words we can say we implement interfaces so that our class starts behaving in a particular way.
Let me explain with an example, we all know what animals are. Like Lion is an animal, monkey is an animal, elephant is an animal, cow is an animal and so on. Now we know all animals do eat something and sleep. But the way each animal can eat something or sleep may differ. Like Lion eats by hunting other animals where as cow eats grass. But both eat. So we can have some pseudo code like this,
interface Animal {
public void eat();
public void sleep();
}
class Lion implements Animal {
public void eat() {
// Lion's way to eat
}
public void sleep(){
// Lion's way to sleep
}
}
class Monkey implements Animal {
public void eat() {
// Monkey's way to eat
}
public void sleep() {
// Monkey's way to sleep
}
}
As per the pseudo code mentioned above, anything that is capable of eating or sleeping will be called an animal or we can say it is must for all animals to eat and sleep but the way to eat and sleep depends on the animal.
In case of interfaces we inherit only the behaviour, not the actual code as in case of classes' inheritance.
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Implementing interfaces is other kind of inheritance. It is not similar to the inheritance of classes as in that inheritance child class gets the real code to reuse from the base class.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
It is said because one class can implement more than one interfaces. But we need to understand that this inheritance is different than classes' inheritance.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Implementing an interface puts compulsion on the class that it must override its all abstract methods.
Read more in my book here and here
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Unfortunately, in colloquial usage, the word inheritance is still frequently used when a class implements an interface, although interface implementation would be a preferable term - IMO, the term inheritance should strictly be used with inheritance of a concrete or abstract class. In languages like C++ and C#, the same syntax (i.e. Subclass : Superclass and Class : Interface) is used for both class inheritance and interface implementation, which may have contributed to the spread of the misuse of the word inheritance with interfaces. Java has different syntax for extending a class as opposed to implementing an interface, which is a good thing.
Q2 If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
You can achieve the 'effect' of multiple inheritance through composition - by implementing multiple interfaces on a class, and then providing implementations for all methods, properties and events required of all the interfaces on the class. One common technique of doing this with concrete classes is by doing 'has-a' (composition) relationships with classes which implement the external interfaces by 'wiring up' the implementation to each of the internal class implementations. (Languages such as C++ do support multiple concrete inheritance directly, but which creates other potential issues like the diamond problem).
Q3 Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Interfaces allow existing classes (e.g. frameworks) to interact with your new classes without having ever 'seen' them before, because of the ability to communicate through a known interface. Think of an interface as a contract. By implementing this interface on a class, you are contractually bound to meet the obligations required of it, and once this contract is implemented, then your class should be able to be used interchangeably with any other code which consumes the interface.
Real World Example
A 'real world' example would be the legislation and convention (interface) surrounding an electrical wall socket in a particular country. Each electrical appliance plugged into the socket needs to meet the specifications (contract) that the authorities have defined for the socket, e.g. the positioning of the line, neutral and earth wires, the position and colouring of the on / off switch, and the conformance the the electrical voltage, frequency and maximum current that will be supplied through the interface when it is switched on.
The benefit of decoupling the interface (i.e. a standard wall socket) rather than just soldering wires together is that you can plug (and unplug) a fan, a kettle, a double-adapter, or some new appliance to be invented next year into it, even though this appliance didn't exist when the interface was designed. Why? Because it will conform to the requirements of the interface.
Why use interfaces?
Interfaces are great for loose coupling of classes, and are one of the mainstay's of Uncle Bob's SOLID paradigm, especially the Dependency Inversion Principle and Interface Segregation Principles.
Simply put, by ensuring that dependencies between classes are coupled only on interfaces (abstractions), and not on other concrete classes, it allows the dependency to be substituted with any other class implementation which meets the requirements of the interface.
In testing, stubs and mocks of dependencies can be used to unit test each class, and the interaction the class has with the dependency can be 'spyed' upon.
KISS
I have searched for days, nay weeks trying to understand interfaces and seem to read the same generic help; I'm not trying to disparage the contributions, but i think the light-bulb just clicked so I'm chuffed :))
I prefer to Keep It Simple Stupid, so will proffer my new found view of interfaces.
I'm a casual coder but i want to post this code i wrote in VB.NET (the principle is the same for other languages), to help others understand interfaces.
If i have it wrong, then please let others know in follow up comments.
Explanation
Three buttons on a form, clicking each one saves a different class reference to the interface variable (_data). The whole point of different class references into an interface variable, is what i didn't understand as it seemed redundant, then its power becomes evident with the msgbox, i only need to call the SAME method to perform the task i need, in this case 'GetData()', which uses the method in the class that's currently held by the interface reference variable (_data).
So however i wish to get my data (from a database, the web or a text file), it's only ever done using the same method name; the code behind that implementation...i don't care about.
It's then easy to change each class code using the interface without any dependency...this is a key goal in OO and encapsulation.
When to use
Code classes and if you notice the same verb used for methods, like 'GetData()', then it's a good candidate to implement an interface on that class and use that method name as an abstraction / interface.
I sincerely hope this helps a fellow noob with this difficult principle.
Public Class Form1
Private _data As IData = Nothing
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
_data = New DataText()
MsgBox(_data.GetData())
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
_data = New DataDB()
MsgBox(_data.GetData())
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
_data = New DataWeb()
MsgBox(_data.GetData())
End Sub
End Class
Public Interface IData
Function GetData() As String
End Interface
Friend Class DataText : Implements IData
Friend Function GetData() As String Implements IData.GetData
Return "DataText"
End Function
End Class
Friend Class DataDB : Implements IData
Friend Function GetData() As String Implements IData.GetData
Return "DataDB"
End Function
End Class
Friend Class DataWeb : Implements IData
Friend Function GetData() As String Implements IData.GetData
Return "DataWeb"
End Function
End Class
Old question. I'm suprised that nobody quoted the canonical sources: Java: an Overview by James Gosling, Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four or Effective Java by Joshua Bloch (among other sources).
I will start with a quote:
An interface is simply a specification of a set of methods that an object responds to. It does not include any instance variables or implementation. Interfaces can be multiply-inherited (unlike classes) and they can be used in a more flexible way than the usual rigid class
inheritance structure. (Gosling, p.8)
Now, let's take your assumptions and questions one by one (I'll voluntarily ignore the Java 8 features).
Assumptions
Interface is collection of ONLY abstract methods and final fields.
Did you see the keyword abstract in Java interfaces? No. Then you should not consider an interface as a collection of abstract methods. Maybe you are misleaded by the C++ so-called interfaces, which are classes with only pure virtual methods. C++, by design, does not have (and does not need to have) interfaces, because it has mutliple inheritance.
As explained by Gosling, you should rather consider an interface as "a set of methods that an object responds to". I like to see an interface and the associated documentation as a service contract. It describes what you can expect from an object that implements that interface. The documentation should specify the pre and post-conditions (e.g. the parameters should be not null, the output is always positive, ...) and the invariants (a method that does not modify the object internal state). This contract is the heart, I think, of OOP.
There is no multiple inheritance in Java.
Indeed.
JAVA omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefit. This primarily consists of operator overloading (although it does have method overloading), multiple inheritance, and extensive automatic coercions. (Gosling, p.2)
Nothing to add.
Interfaces can be used to achieve multiple inheritance in Java.
No, simlpy because there is no multiple inheritance in Java. See above.
One Strong point of Inheritance is that We can use the code of base class in derived class without writing it again. May be this is the most important thing for inheritance to be there.
That's called "implementation inheritance". As you wrote, it's a convenient way to reuse code.
But it has an important counterpart:
parent classes often define at least part of their subclasses' physical representation. Because inheritance exposes a subclass to details of its parent's implementation, it's often said that "inheritance breaks encapsulation" [Sny86]. The implementation of a subclass becomes so bound up with the implementation of its parent class that any change in the parent's implementation will force the subclass to change. (GOF, 1.6)
(There is a similar quote in Bloch, item 16.)
Actually, inheritance serves also another purpose:
Class inheritance combines interface inheritance and implementation inheritance. Interface inheritance defines a new interface in terms of one
or more existing interfaces. Implementation inheritance defines a new implementation in terms of one or more existing implementations. (GOF, Appendix A)
Both use the keyword extends in Java. You may have hierarchies of classes and hierarchies of interfaces. The first ones share implementation, the second ones share obligation.
Questions
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.**
Implementation of an interface is not inheritance. It's implementation. Thus the keyword implements.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?**
No multiple inheritance in Java. See above.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it./Then why to make interfaces ?/What are the exact benefits of using interfaces? Is it really Multiple-Inheritance that we achieve using Interfaces?
The most important question is: why would you like to have multiple-inheritance? I can think of two answers: 1. to give mutliple types to an object; 2. to reuse code.
Give mutliple types to an object
In OOP, one object may have different types. For instance in Java, an ArrayList<E> has the following types: Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess, AbstractList<E>, AbstractCollection<E> and Object (I hope I have not forgotten anyone). If an object has different types, various consumers will be able use it without be aware of its specificities. I need an Iterable<E> and you give me a ArrayList<E>? It's ok. But if I need now a List<E> and you give me a ArrayList<E>, it's ok too. Etc.
How do you type an object in OOP? You took the Runnable interface as an example, and this example is perfect to illustrate the answer to this question. I quote the official Java doc:
In addition, Runnable provides the means for a class to be active while not subclassing Thread.
Here's the point: Inheritance is a convenient way of typing objects. You want to create a thread? Let's subclass the Thread class. You want an object to have different types, let's use mutliple-inheritance. Argh. It doesn't exist in Java. (In C++, if you want an object to have different types, multiple-inheritance is the way to go.)
How to give mutliple types to an object then? In Java, you can type your object directly. That's what you do when your class implements the Runnable interface. Why use Runnable if your a fan of inheritance? Maybe because your class is already a subclass of another class, let's say A. Now your class has two types: A and Runnable.
With multiple interfaces, you can give multiple types to an object. You just have to create a class that implements multiple interfaces. As long as you are compliant with the contracts, it's ok.
Reuse code
This is a difficult subject; I've already quoted the GOF on breaking the encapsulation. Other answer mentionned the diamond problem. You could also think of the Single Responsibility Principle:
A class should have only one reason to change. (Robert C. Martin, Agile Software Development, Principles, Patterns, and Practices)
Having a parent class may give a class a reason to change, besides its own responsibilities:
The superclass’s implementation may change from release to release, and if it does, the subclass may break, even though its code has not been touched. As a consequence, a subclass must evolve in tandem with its superclass (Bloch, item 16).
I would add a more prosaic issue: I always have a weird feeling when I try to find the source code of a method in a class and I can't find it. Then I remember: it must be defined somewhere in the parent class. Or in the grandparent class. Or maybe even higher. A good IDE is a valuable asset in this case, but it remains, in my mind, something magical. Nothing similar with hierarchies of interfaces, since the javadoc is the only thing I need: one keyboard shortcut in the IDE and I get it.
Inheritance howewer has advantages:
It is safe to use inheritance within a package, where the subclass and the superclass implementations are under the control of the same programmers. It is also safe to use inheritance when extending classes specifically designed and documented for extension (Item 17: Design and document for inheritance or else prohibit it). (Bloch, item 16)
An example of a class "specifically designed and documented for extension" in Java is AbstractList.
But Bloch and GOF insist on this: "Favor composition over inheritance":
Delegation is a way of making composition as powerful for reuse as inheritance [Lie86, JZ91]. In delegation, two objects are involved in handling a request: a receiving object delegates operations to its delegate. This is analogous to subclasses deferring requests to parent classes. (GOF p.32)
If you use composition, you won't have to write the same code again and again. You just create a class that handles the duplications, and you pass an instance of this class to the classes that implements the interface. It's a very simple way to reuse code. And this helps you to follow the Single Responsibility Principle and make the code more testable. Rust and Go don't have inheritance (they don't have classes either), but I don't think that the code is more redundant than in other OOP languages.
Furthermore, if you use composition, you will find yourself naturally using interfaces to give your code the structure and the flexibility it needs (see other answers on use cases of interfaces).
Note: you can share code with Java 8 interfaces
And finally, one last quote:
During the memorable Q&A session, someone asked him [James Gosling]: "If you could do Java over again, what would you change?" "I'd leave out classes" (anywhere on the net, don't know if this is true)
This is very old question and java-8 release have added more features & power to interface.
An interface declaration can contain
method signatures
default methods
static methods
constant definitions.
The only methods that have implementations in interface are default and static methods.
Uses of interface:
To define a contract
To link unrelated classes with has a capabilities (e.g. classes implementing Serializable interface may or may not have any relation between them except implementing that interface
To provide interchangeable implementation e.g. Strategy_pattern
default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces
Organize helper methods in your libraries with static methods ( you can keep static methods specific to an interface in the same interface rather than in a separate class)
Have a look at this related SE question for code example to understanding the concepts better:
How should I have explained the difference between an Interface and an Abstract class?
Coming back to your queries:
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
Interface can contain code for static and default methods. These default methods provides backward compatibility & static methods provides helper/utility functions.
You can't have true multiple inheritance in java and interface is not the way to get it. Interface can contain only constants. So you can't inherit state but you can implement behaviour.
You can replace inheritance with capability. Interface provides multiple capabilities to implementing classes.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Refer to "uses of interface" section in my answer.
Inheritance is when one class derives from another class (which can be abstract) or an Interface. The strongest point of object oriented (inheritance) is not reuse of code (there are many ways to do it), but polymorphism.
Polymorphism is when you have code that uses the interface, which it's instance object can be of any class derived from that interface. For example I can have such a method:
public void Pet(IAnimal animal) and this method will get an object which is an instance of Dog or Cat which inherit from IAnimal. or I can have such a code:
IAnimal animal
and then I can call a method of this interface:
animal.Eat() which Dog or Cat can implement in a different way.
The main advantage of interfaces is that you can inherit from some of them, but if you need to inherit from only one you can use an abstract class as well. Here is an article which explains more about the differences between an abstract class and an interface:
http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
Both Methods Work (Interfaces and Multiple Inheritance).
Quick Practical Short Answer
Interfaces are better when you have several years of experience using Multiple Inheritance that have Super Classes with only method definition, and no code at all.
A complementary question may be: "How and Why to to migrate code from Abstract Classes to Interfaces".
If you are not using many abstract classes, in your application, or you don't have many experience with it, you may prefer to skip interfaces.
Dont rush to use interfaces.
Long Boring Answer
Interfaces are very similar, or even equivalent to abstract Classes.
If your code has many Abstract classes, then its time you start thinking in terms of Interfaces.
The following code with abstract classes:
MyStreamsClasses.java
/* File name : MyStreamsClasses.java */
import java.lang.*;
// Any number of import statements
public abstract class InputStream {
public void ReadObject(Object MyObject);
}
public abstract class OutputStream {
public void WriteObject(Object MyObject);
}
public abstract class InputOutputStream
imnplements InputStream, OutputStream {
public void DoSomethingElse();
}
Can be replaced with:
MyStreamsInterfaces.java
/* File name : MyStreamsInterfaces.java */
import java.lang.*;
// Any number of import statements
public interface InputStream {
public void ReadObject(Object MyObject);
}
public interface OutputStream {
public void WriteObject(Object MyObject);
}
public interface InputOutputStream
extends InputStream, OutputStream {
public void DoSomethingElse();
}
Cheers.
So. There are a lot of excellent answers here explaining in detail what an interface is. Yet, this is an example of its use, in the way one of my best colleagues ever explained it to me years ago, with what I have learned at university in the last couple of years mixed in.
An interface is a kind of 'contract'. It exposes some methods, fields and so on, that are available. It does not reveal any of its implementation details, only what it returns, and which parameters it takes. And in here lies the answer to question three, and what I feel is one of the greatest strengths of modern OOP:
"Code by addition, Not by modification" - Magnus Madsen, AAU
That's what he called it at least, and he may have it from some other place. The sample code below is written in C#, but everything shown can be done just about the same way in Java.
What we see is a class called SampleApp, that has a single field, the IOContext. IOContext is an interface.
SampleApp does not care one wit about how it saves its data, it just needs to do so, in its "doSomething()" method.
We can imagine that saving the data may have been more important than HOW it was saved at the beginning of the development process, so the developer chose to simply write the FileContext class. Later on, however, he needed to support JSON for whatever reason. So he wrote the JSONFileContext class, which inherits FileContext. This means that it is effectively an IOContext, which has the functionality of FileContext, save the replacement of FileContexts SaveData and LoadData, it still uses its 'write/read' methods.
Implementing the JSON class has been a small amount of work, comparing to writing the class, and having it just inherit IOContext.
The field of SampleApp could have been just of type 'FileContext', but that way, it would have been restricted to ever only using children of that class. By making the interface, we can even do the SQLiteContext implementation, and write to a database, SampleApp will never know or care, and when we have written the SQL lite class, we need only make one change to our code: new JSONFileContext(); instead becomes new SQLiteContext();
We still have our old implementations and can switch back to those if the need arises. We have broken nothing, and all the changes to our code are half a line, that can be changed back within the blink of an eye.
so: Code by addition, NOT by modification.
namespace Sample
{
class SampleApp
{
private IOContext context;
public SampleApp()
{
this.context = new JSONFileContext(); //or any of the other implementations
}
public void doSomething()
{
//This app can now use the context, completely agnostic of the actual implementation details.
object data = context.LoadData();
//manipulate data
context.SaveData(data);
}
}
interface IOContext
{
void SaveData(object data);
object LoadData();
}
class FileContext : IOContext
{
public object LoadData()
{
object data = null;
var fileContents = loadFileContents();
//Logic to turn fileContents into a data object
return data;
}
public void SaveData(object data)
{
//logic to create filecontents from 'data'
writeFileContents(string.Empty);
}
protected void writeFileContents(string fileContents)
{
//writes the fileContents to disk
}
protected string loadFileContents()
{
string fileContents = string.Empty;
//loads the fileContents and returns it as a string
return fileContents;
}
}
class JSONFileContext : FileContext
{
public new void SaveData(object data)
{
//logic to create filecontents from 'data'
base.writeFileContents(string.Empty);
}
public new object LoadData()
{
object data = null;
var fileContents = loadFileContents();
//Logic to turn fileContents into a data object
return data;
}
}
class SQLiteContext : IOContext
{
public object LoadData()
{
object data = null;
//logic to read data into the data object
return data;
}
public void SaveData(object data)
{
//logic to save the data object in the database
}
}
}
Interfaces
An interface is a contract defining how to interact with an object. They are useful to express how your internals intend to interact with an object. Following Dependency Inversion your public API would have all parameters expressed with interfaces. You don't care how it does what you need it to do, just that it does exactly what you need it to do.
Example: You may simply need a Vehicle to transport goods, you don't care about the particular mode of transport.
Inheritance
Inheritance is an extension of a particular implementation. That implementation may or may not satisfy a particular interface. You should expect an ancestor of a particular implementation only when you care about the how.
Example: You may need a Plane implementation of a vehicle for fast transport.
Composition
Composition can be used as an alternative to inheritance. Instead of your class extending a base class, it is created with objects that implement smaller portions of the main class's responsibility. Composition is used in the facade pattern and decorator pattern.
Example: You may create a DuckBoat (DUKW) class that implements LandVehicle and WaterVehicle which both implement Vehicle composed of Truck and Boat implementations.
Answers
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Interfaces are not inheritance. Implementing an interface expresses that you intend for your class to operate in the way that is defined by the interface. Inheritance is when you have a common ancestor, and you receive the same behavior (inherit) as the ancestor so you do not need to define it.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
Interfaces do not achieve multiple inheritance. They express that a class may be suitable for multiple roles.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
One of the major benefits of interfaces is to provide separation of concerns:
You can write a class that does something with another class without caring how that class is implemented.
Any future development can be compatible with your implementation without needing to extend a particular base class.
In the spirit of DRY you can write an implementation that satisfies an interface and change it while still respecting the open/closed principal if you leverage composition.
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing an interface then it is inheritance? We are not using its code.
It is not equal inheritance. It is just similiar. Let me explain:
VolvoV3 extends VolvoV2, and VolvoV2 extends Volvo (Class)
VolvoV3 extends VolvoV2, and VolvoV2 implements Volvo (Interface)
line1: Volvo v = new VolvoV2();
line2: Volvo v = new VolvoV3();
If you see only line1 and line2 you can infer that VolvoV2 and VolvoV3 have the same type. You cannot infer if Volvo a superclass or Volvo is an interface.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritances?
Now using interfaces:
VolvoXC90 implements XCModel and Volvo (Interface)
VolvoXC95 implements XCModel and Volvo (Interface)
line1: Volvo a = new VolvoXC90();
line2: Volvo a = new VolvoXC95();
line3: XCModel a = new VolvoXC95();
If you see only line1 and line2 you can infer that VolvoXC90 and VolvoXC95 have the same type (Volvo). You cannot infer that Volvo is a superclass or Volvo is an interface.
If you see only line2 and line3 you can infer that Volvo95 implements two types, XCModel and Volvo, in Java you know that at least one has to be an interface. If this code was written in C++, for instance, they could be both classes. Therefore, multiple inheritances.
Q3. Anyhow, what is the benefit of using Interfaces? They are not having any code. We need to write code again and again in all classes we implement it.
Imagine a system where you use a VolvoXC90 class in 200 other classes.
VolvoXC90 v = new VolvoXC90();
If you need to evolve your system to launch VolvoXC95 you have to alter 200 other classes.
Now, imagine a system where you use a Volvo interface in 10,000,000 classes.
// Create VolvoXC90 but now we need to create VolvoXC95
Volvo v = new VolvoFactory().newCurrentVolvoModel();
Now, if you need to evolve your system to create VolvoXC95 models you have to alter only one class, the Factory.
It is a common sense question. If your system is composed only of few classes and have few updates use Interfaces everywhere is counterproductive. For big systems, it can save you a lot of pain and avoid risk adopting Interfaces.
I recommend you read more about S.O.L.I.D principles and read the book Effective Java. It has good lessons from experienced software engineers.
Interfaces are made so that a class will implement the functionality within the interface and behave in accordance with that interface.

Disadvantage of object composition over class inheritance

Most design patten books say we should "Favor object composition over class inheritance."
But can anyone give me an example that inheritance is better than object composition.
Inheritance is appropriate for is-a relationships. It is a poor fit for has-a relationships.
Since most relationships between classes/components fall into the has-a bucket (for example, a Car class is likely not a HashMap, but it may have a HashMap), it then follows the composition is often a better idea for modeling relationships between classes rather than inheritance.
This is not to say however that inheritance is not useful or not the correct solution for some scenarios.
My simple answer is that you should use inheritance for behavioral purposes. Subclasses should override methods to change the behaviour of the method and the object itself.
This article (interview with Erich Gamma, one of the GoF) elaborates clearly why Favor object composition over class inheritance.
In Java, whenever you inherit from a class, your new class also automatically becomes a subtype of the original class type. Since it is a subtype, it needs to adhere to the Liskov substitution principle.
This principle basically says that you must be able to use the subtype anywhere where the supertype is expected. This severely limits how the behavior of your new inherited class can differ from the original class.
No compiler will be able to make you adhere to this principle though, but you can get in trouble if you don't, especially when other programmers are using your classes.
In languages that allow subclassing without subtyping (like the CZ language), the rule "Favor object composition over inheritance" is not as important as in languages like Java or C#.
Inheritance allows an object of the derived type to be used in nearly any circumstance where one would use an object of the base type. Composition does not allow this. Use inheritance when such substitution is required, and composition when it is not.
Just think of it as having an "is-a" or a "has-a" relationship
In this example Human "is-a" Animal, and it may inherits different data from the Animal class. Therefore Inheritance is used:
abstract class Animal {
private String name;
public String getName(){
return name;
}
abstract int getLegCount();
}
class Dog extends Animal{
public int getLegCount(){
return 4;
}
}
class Human extends Animal{
public int getLegCount(){
return 2;
}
}
Composition makes sense if one object is the owner of another object. Like a Human object owning a Dog object. So in the following example a Human object "has-a" Dog object
class Dog{
private String name;
}
class Human{
private Dog pet;
}
hope that helped...
It is a fundamental design principle of a good OOD. You can assign a behaviour to a class dynamicly "in runtime", if you use composition in your design rather than inheritance like in Strategy Pattern. Say,
interface Xable {
doSomething();
}
class Aable implements Xable { doSomething() { /* behave like A */ } }
class Bable implements Xable { doSomething() { /* behave like B */ } }
class Bar {
Xable ability;
public void setAbility(XAble a) { ability = a; }
public void behave() {
ability.doSomething();
}
}
/*now we can set our ability in runtime dynamicly */
/*somewhere in your code */
Bar bar = new Bar();
bar.setAbility( new Aable() );
bar.behave(); /* behaves like A*/
bar.setAbility( new Bable() );
bar.behave(); /* behaves like B*/
if you did use inheritance, the "Bar" would get the behaviour "staticly" over inheritance.
Inheritance is necessary for subtyping. Consider:
class Base {
void Foo() { /* ... */ }
void Bar() { /* ... */ }
}
class Composed {
void Foo() { mBase.Foo(); }
void Bar() { mBase.Foo(); }
private Base mBase;
}
Even though Composed supports all of the methods of Foo it cannot be passed to a function that expects a value of type Foo:
void TakeBase(Base b) { /* ... */ }
TakeBase(new Composed()); // ERROR
So, if you want polymorphism, you need inheritance (or its cousin interface implementation).
This is a great question. One I've been asking for years, at conferences, in videos, in blog posts. I've heard all kinds of answers. The only good answer I've heard is preformance:
Performance differences in languages. Sometimes, classes take advantage of built-in engine optimizations that dynamic compositions don't. Most of the time, this is a much smaller concern than the problems associated with class inheritance, and usually, you can inline everything you need for that performance optimization into a single class and wrap a factory function around it and get the benefits you need without a problematic class hierarchy.
You should never worry about this unless you detect a problem. Then you should profile and test differences in perf to make informed tradeoffs as needed. Often, there are other performance optimizations available that don't involve class inheritance, including tricks like inlining, method delegation, memoizing pure functions, etc... Perf will vary depending on the specific application and language engine. Profiling is essential, here.
Additionally, I've heard lots of common misconceptions. The most common is confusion about type systems:
Conflating types with classes (there are a couple existing answers concentrate on that here already). Compositions can satisfy polymorphism requirements by implementing interfaces. Classes and types are orthogonal, though in most class-supporting languages, subclasses automatically implement the superclass interface, so it can seem convenient.
There are three very good reasons to avoid class inheritance, and the crop up again and again:
The gorilla/banana problem
"I think the lack of reusability comes in object-oriented languages, not functional languages. Because the problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle." ~ Joe Armstrong, quoted in "Coders at Work" by Peter Seibel.
This problem basically refers to the lack of selective code reuse in class inheritance. Composition lets you select just the pieces you need by approaching software design from a "small, reusable parts" approach rather than building monolithic designs that encapsulate everything related to some given functionality.
The fragile base class problem
Class inheritance is the tightest coupling available in object-oriented design, because the base class becomes part of the implementation of the child classes. This is why you'll also hear the advice from the Gang of Four's "Design Patterns" classic: "Program to an interface, not an implementation."
The problem with implementation inheritance is that even the smallest change to the inner details of that implementation could potentially break child classes. If the interface is public, exposed to user-land in any way, it could break code you are not even aware of.
This is the reason that class hierarchies become brittle -- hard to change as you grow them with new use-cases.
The common refrain is that we should be constantly refactoring our code (see Martin Fowler et al on extreme programming, agile, etc...). The key to refactor success is that you can't break things -- but as we've just seen, it's difficult to refactor a class hierarchy without breaking things.
The reason is that it's impossible to create the correct class hierarchy without knowing everything you need to know about the use-cases, but you can't know that in evolving software. Use cases get added or changed in projects all the time.
There is also a discovery process in programming, where you discover the right design as you implement the code and learn more about what works and what doesn't. But with class inheritance, once you get a class taxonomy going, you've painted yourself into a corner.
You need to know the information before you start the implementation, but part of learning the information you need involves building the implementation. It's a catch-22.
The duplication by necessity problem. This is where the death spiral really gets going. Sometimes, you really just want a banana, not the gorilla holding the banana, and the entire jungle. So you copy and paste it. Now there's a bug in a banana, so you fix it. Later, you get the same bug report and close it. "I already fixed that". And then you get the same bug report again. And again. Uh-oh. It's not fixed. You forgot the other banana! Google "copy pasta".
Other times, you really need to work a new use-case into your software, but you can't change the original base class, so instead, you copy and paste the entire class hierarchy into a new one and rename all the classes you need in the hierarchy to force that new use-case into the code base. 6 months later a new dev is looking at the code and wondering which class hierarchy to inherit from and nobody can provide a good answer.
Duplication by necessity leads to copy pasta messes, and pretty soon people start throwing around the word "rewrite" like it's no big deal. The problem with that is that most rewrite projects fail. I can name several orgs off the top of my head that are currently maintaining two development teams instead of one while they work on a rewrite project. I've seen such orgs cut funding to one or the other, and I've seen projects like that chew through so much cash that a startup or small business runs out of money and shuts down.
Developers underestimate the impact of class inheritance all the time. It's an important choice, and you need to be aware of the trade offs you opt into every time you create or inherit from a base class.

Categories

Resources