How should a basic class hierarchy be constructed?

19,479

Solution 1

I'll use C++ as an example language, since it relies so much on inheritance and classes. Here's a simple guide on how to build controls for a simple OS, such as windows. Controls include simple objects on your windows, such as buttons, sliders, textboxes, etc.


Building a basic class.

This part of the guide applies for (almost) any class. Remember, well planned is half done. What kind of class are we working on? Which are it's attributes and what methods does it need? These are the main questions we need to think of.

We're working on OS controls here, so let's begin with a simple class, shall it be Button. Now, what are the attributes on our button? Obviously it needs a position on the window. Also, we don't want every button to be exact same size, so size is an other attribute. Button also "needs" a label (the text drawn on the button). This is what you do with each class, you design it and then code it. Now I know which attributes I need, so lets build the class.

class Button
{
    private:
        Point m_position;
        Size m_size;
        std::string m_label;
}

Notice how I've left out all the getters and setter and other methods for the sake of shorter code, but you'd have to include those too. I'm also expecting us to have Point and Size classes, normally we'd have to struct them ourselves.


Moving onto the next class.

Now that we got one class (Button) finished, we can move to the next class. Let's go with Slider, the bar which e.g. helps you scroll web pages up and down.

Let's begin like we did on button, what does our slider class need? It's got location (position) on the window and size of the slider. Also, it's got minimum and maximum values (minimum means that the scroller is set to the top of the slider, and maximum means it's on the bottom). We also need the current value, i.e. where the scroller is at the moment. This is enough for now, we can build our class:

class Slider
{
    private:
        Point m_position;
        Size m_size;
        int m_minValue;
        int m_maxValue;
        int m_currentValue;
}

Creating a base class.

Now that we got two classes, the first thing we notice is we just defined Point m_position; and Size m_size; attributes on both classes. This means we have two classes with common elements and we just wrote the same code twice, wouldn't it be awesome if we could write the code only once and tell both of our classes to use that code instead of rewriting? Well, we can.

Creating a base class is "always" (there are exceptions, but beginners shouldn't worry about them) recommended if we have two similar classes with common attributes, in this case Button and Slider. They are both controls on our OS with size and position. From this we get a new class, called Control:

class Control
{
    private:
        Point m_position;
        Size m_size;
}

Inheriting similar classes from common base class.

Now that we got our Control class, which includes the common items for every control, we can tell our Button and Slider to inherit from it. This will save us time, computer's memory and eventually time. Here's our new classes:

class Control
{
    private:
        Point m_position;
        Size m_size;
}

class Button : public Control
{
    private:
        std::string m_label
}

class Slider : public Control
{
    private:
        int m_minValue;
        int m_maxValue;
        int m_currentValue;
}

Now some people might say that writing Point m_position; Size m_size; twice is much easier than writing twice : public Control and creating the Control class. This might be true in some cases, but it's still recommended not to write the same code twice, especially not when creating classes.

Besides, who knows how many common attributes we'll eventually find. Later on we might realize we need Control* m_parent member to the Control class, which points to the window (or panel or such) in which our control is held in.

An other thing is, if we later on realize that on top of Slider and Button we also need TextBox, we can just create a textbox control by saying class TextBox : public Control { ... } and only write the textbox specific member variables, instead of size, position and parent again and again on every class.


Final thoughts.

Basically always when you have two classes with common attributes or methods, you should create a base class. This is the basic rule, but you are allowed to use your own brain since there might be some exceptions.

I am not a professional coder myself either, but I'm learning and I've taught you everything as my educators have taught it to me. I hope you (or atleast someone) will find this answer useful. And even though some people say that python and other duck typing languages don't even need to use inheritance, they're wrong. Using inheritance will save you so much time and money on larger projects, and eventually you'll thank yourself for creating the base classes. The reusability and management of your project will become billion times easier.

Solution 2

It depends on the language.

In Python for example you normally don't need a lot of inheritance because you can pass any object to any function and if the objects implements the proper methods everything will be fine.

class Dog:
    def __init__(self, name):
        self.name = name

    def sing(self):
        return self.name + " barks"

class Cat:
    def __init__(self, name):
        self.name = name

    def sing(self):
        return self.name + " meows"

In the above code Dog and Cat are unrelated classes, but you can pass an instance of either to a function that uses name and calls method sing.

In C++ instead you would be forced to add a base class (e.g. Animal) and to declare those two classes as derived.

Of course inheritance is implemented and useful in Python too, but in many cases in which it's necessary in say C++ or Java you can just avoid it thanks to "duck typing".

However if you want for example to inherit implementation of some methods (in this case the constructor) then inheritance could be use with Python too with

class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def sing(self):
        return self.name + " barks"

class Cat(Animal):
    def sing(self):
        return self.name + " meows"

The dark side of inheritance is that your classes will be more coupled and more difficult to reuse in other contexts you cannot foresee now.

Someone said that with object oriented programming (actually class oriented programming) sometimes you just need a banana and instead you get a gorilla holding a banana and a whole jungle with it.

Solution 3

Since you are primarily interested in the big picture, and not the mechanics of class design, you might want to familiarize yourself with the S.O.L.I.D. principles of object-oriented design. It's not a strict procedure, but a set or rules to support your own judgement and taste.

  1. The essence is that a class represents a single responsiblity (the S). It does one thing and does it well. It should represent an abstraction, preferably one representing a piece of your application's logic (encapsulating both behavior and data to support that behavior). It could also be an aggregation abstraction of multiple related data field. The class is the unit of such encapsulation and is responsible for maintaining the invariants of your abstractions.

  2. The way to build classes is to be both open to extensions and closed to modifications (the O). Identify likely changes in your class's dependencies (either types or constants that you used in its interface and implementation). You want the interface to be complete enough so that it can extended, yet you want its implementation to be robust enough so that it won't have to be changed for that.

    That's two principles about the class as the basic building block. Now on to building hierarchies, which represents class relationships.

  3. Hierarchies are built through inheritance or composition. The key principle here is that you only use inheritance to model strict Liskov-substitutability (the L). This is a fancy way of saying that you only use inheritance for is-a relationships. For anything else (barring some technical exceptions to get some minor implementation advantages) you use composition. This will keep your system as loosely coupled as possible.

  4. At some point many different clients might depend on your classes for different reasons. This will grow your class hierarchy and some of the classes lower in the hierarchy can get overly large ("fat") interfaces. When that happens (and in practice it's a matter of taste and judgement) you seggregate your general-purpose class interface into many client-specific interfaces (the I).

  5. As your hierarchy grows even further, it might appear to form a pyramid when you draw it with the basic classes on top and their subclasses or composities below it. This will mean that your higher-level application layers will depend on lower-level details. You can avoid such brittleness (which for example manifests itself through large compile times or very big cascades of changes following minor refactorings) by letting both the higher-level layer and the lower-level layer depend on abstractions (i.e. interfaces, which in C++ e.g. can be implemented as abstract classes or template parameters). Such dependency inversion (the D) once again helps to loosen couplings between the various parts of your application.

That's it: five solid pieces of advice that are more or less language independent and have stood the test of time. Software design is hard, these rules are to keep you out of the most frequently occuring types of trouble, everything else comes through practice.

Solution 4

You need to use inheritance, when you have a situation where there are two classes, that contains the attributes of a single class, or when there are two classes, in which one is dependant on the other. Eg)

class animal:
    #something
class dog(animal):
    #something
class cat(animal):
    #something

Here, there are two classes , dog and cat, that have the attributes of the class animal. Here , inheritance plays its role.

class parent:
    #something
class child(parent):
    #something

Here, parent and child are two classes, where the child is dependant of the parent, where the child has the attributes of the parent and its own unique ones. So, inheritance is used here.

Solution 5

I'd start with definition of class from wikipedia:

In object-oriented programming, a class is a construct that is used to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable its instances to have state and behavior. Data field members (member variables or instance variables) enable a class instance to maintain state. Other kinds of members, especially methods, enable the behavior of class instances. Classes define the type of their instances

Often you see examples that uses dogs, animals, cats and so on. But let's get to something practical.

First and most straight forward case when you need a class is when you need (or rather you should) to encapsulate certain functions and methods together, because they simply make sense together. Let's imagine something simple: HTTP request.

What do you need when creating HTTP request? Server, port, protocol, headers, URI... You could put all that into dict like {'server': 'google.com'} but when you use class for this, you'll just make it explicit that you need these attributes together and you'll be using them to do this one particular task.

For the methods. You could again create method fetch(dict_of_settings), but whole functionality is bound to attributes of HTTP class and just doesn't make sense without them.

class HTTP:
    def __init__(self):
        self.server = ...
        self.port = ...
        ...

    def fetch(self):
        connect to self.server on port self.port
        ...

r1 = HTTP(...)
r2 = HTTP(...)
r1.port = ...
data = r1.fetch()

Isn't it nice and readable?


Abstract classes/Interfaces

This point, just quick... Assume you want to implement dependency injection in your project for this particular case: you want your application to be independent on database engine.

So you propose interface (represented by abstract class) which should each database connector implement and then rely on generic methods in your application. Lets say that you define DatabaseConnectorAbstract (you don't have to actually define in python, but you do in C++/C# when proposing interface) with methods:

class DatabaseConnectorAbstract:
    def connect(): raise NotImplementedError(  )
    def fetch_articles_list(): raise NotImplementedError(  )
    ...

# And build mysql implementation
class DatabaseConnectorMysql(DatabaseConnectorAbstract):
   ...

# And finally use it in your application
class Application:
    def __init__(self,database_connector):
        if not isinstanceof(database_connector, DatabaseConnectorAbstract):
            raise TypeError()

        # And now you can rely that database_connector either implements all
        # required methods or raises not implemented exception

Class hierarchy

Python exceptions. Just take a look for a second on the hierarchy there.

ArithmeticError is generic Exception and in some cases it can get as particular as saying FloatingPointError. This is extremely useful when handling exceptions.

You can realize this better on .NET forms when object has to be instance of Control when adding to form, but can be practically anything else. The whole point is that object is DataGridView while still being Control (and implementing all methods and properties). This is closely connected with abstract classes and interfaces and one of many real-life examples could be HTML elements:

class HtmlElement: pass # Provides basic escaping
class HtmlInput(HtmlElement): pass # Adds handling for values and types
class HtmlSelect(HtmlInput): pass # Select is input with multiple options
class HtmlContainer(HtmlElement): pass # div,p... can contain unlimited number of HtmlElements
class HtmlForm(HtmlContainer): pass # Handles action, method, onsubmit

I've tried to make it as brief as possible, so feel free to ask in comment.

Share:
19,479

Related videos on Youtube

Skamah One
Author by

Skamah One

Earn money online: http://www.neobux.com/?r=skamahone

Updated on May 25, 2022

Comments

  • Skamah One
    Skamah One about 2 years

    I know how to code and use simple classes, and I even know how inheritance works and how to use it. However, there's a very limited amount of guides on how to actually design the structure of your class hierarchy, or even how to design a simple class? Also, when and why should I inherit (or use) a class?

    So I'm not really asking about how, I'm asking when and why. Example codes are always a good way to learn, so I would appreciate them. Also, emphasize the progress of designing rather than simply giving one sentence on when and why.

    I program mainly in C++, C# and Python, but I'll probably understand the simple examples in most languages.

    If any of the terms seem mixed up or so, feel free to edit my question. I'm not a native and I'm not sure of all the words.

    • Alexandre C.
      Alexandre C. about 11 years
      I think a good rule of thumb is to keep your class hierarchies as flat as possible. Don't overuse inheritance. This summarizes some common issues.
  • Captain Obvlious
    Captain Obvlious about 11 years
    What about composition and aggregation?
  • Skamah One
    Skamah One about 11 years
    @CaptainObvlious What are those? Why don't you leave an answer of your own, I won't accept the first answer, but the best one.
  • Aswin Murugesh
    Aswin Murugesh about 11 years
    composition and aggregation of what?
  • Drew Dormann
    Drew Dormann about 11 years
    Good example, but I'm a little wary of the phrase "need to use inheritance". What do people do who are using languages that don't have inheritance?
  • Aswin Murugesh
    Aswin Murugesh about 11 years
    @DrewDormann The question mentioned was about inheritance. So languages that do not have inheritance have no part in this question right?
  • Drew Dormann
    Drew Dormann about 11 years
    @AswinMurugesh That's correct. I'm suggesting that the word "need" is not correct for the languages in this question.
  • Admin
    Admin about 11 years
    The last two paragraphs on your answer, I don't think you quite understand the actual benefits of inheritance. Give me even one example where "The dark side of inheritance is that your classes will be more coupled and more difficult to reuse in other contexts you cannot foresee now." is true. OOP was designed to be the opposite of that, and when used correctly, it's the exact opposite of that.
  • 6502
    6502 about 11 years
    @MarkusMeskanen: if you know the problem perfectly then you can model an accurate deep hierarchy with inheritance and even multiple inheritance saving a lot by sharing common parts. However a perfect problem description is rarely what we face, and later if you need to add something that doesn't fit the scheme because was unanticipated you're in trouble. The other problem is that more complex the hierarchy is and harder is to reuse a part without taking it all (the gorilla problem)... if you use instead composition and delegation with simpler objects reuse is easier.
  • Admin
    Admin about 11 years
    If you need to add something later on and you can't add it, you've obviously done something wrong earlier on. And that's not cause of OOP, that's cause of you. Besides, can you even add something to the Animal class which can't be added to the Dog and Cat classes too, cause I can't think of anything that animal would have but a dog wouldn't? Also, the gorilla problem doesn't even exist. You'll never get anything useless if you've coded your classes right. As I said, give me even one example, a piece of code.
  • Niklas R
    Niklas R about 11 years
    Did you just mix PHP/Perl variables with Python classes? :D
  • Vyktor
    Vyktor about 11 years
    @NiklasR lol, indeed I did :D Should be fixed :)
  • 6502
    6502 about 11 years
    @MarkusMeskanen: The most evident case is when you place functionality in abstract base classes. If you want that functionality you will need either to use a derived class (the gorilla) than possibly will have other unrelated dependencies (the jungle) or you will need to create another derived class still being forced by the original design of the abstract base. An OOD never represents "the reality", but a specific view described only up to level of a good ROI. If you overuse inheritance it will be harder to reuse only part of that design.
  • 6502
    6502 about 11 years
    @MarkusMeskanen: in the Dog and Cat example Python allows you to just use them without forcing you to place them in a hierarchy where there is the abstract concept of Animal. If you need that concept you can add it, but if you don't you are not placing a burden on who will need to use Dog in another context where the Animal machinery is not needed or who will need to create an Aibo class that behaves in a certain context as a reasonable Dog but that's not an Animal.
  • Skamah One
    Skamah One about 11 years
    I liked all the answers and learned quite alot, but this one was (imo) superior to others. The more I think about it, and the more research I do, this answer makes most sense and teaches me the best. And I really liked the way you went through the progress step by step. Thanks for your answer, and than you others for answering too! :) I'd accept most of the answers if I could.
  • Admin
    Admin about 11 years
    @SkamahOne Thanks for the accept, I'm glad I could help!
  • Admin
    Admin about 11 years
    If you need to place functionality in an abstract class and then use a derived class to use that functionality, you are doing something wrong and don't know how to use inheritance. The actual problem in inheritance is: Most people don't understand how to use it properly. They see a problem in their code and post stupid threads about how bad inheritance is, when they've just used it wrong. This leads into everyone thinking it's bad. It's the same as giving a knife to a kid, then he cuts himself and tells everyone how bad knife is. Now everyone thinks knives are bad.
  • Admin
    Admin about 11 years
    Also, your second comment didn't make any sense at all. No offense, but you clearly don't understand the full benefits of inheritance. It's object based, things are categorized by objects, not by functionality. If you don't like the way it works, go with C and code your program without classes. Now let me code the same in C++ with proper inheritance tree, let's see who goes with less code and faster (and lighter) program. Let's add 50 new things to our program and see which one changes and/or reuses the existing code easier. There's a reason C++ won over C, people just can't use the reason.