Inheritance: More than just titles or money

0

Hi there readers,

We have talked about the first principle of object oriented programming in an earlier post. Now, it would be time to talk about the second one, inheritance. In the normal world, we talk about inheritance when one is about to receive some piece of land or a title from a loved one in his/her family. In the programming realm, it is more than this. In OOP, inheritance happens when a class is based on another class . This relation is special because they share the same implementation. Doing so, the class (B), who inherits from the other (A), share the same behavior that A has. But why would programmers act like this? Why not simply copy-paste the code from the class A to the class B? Those are actually good questions you might have had.

I don’t know if you remember from earlier posts, but I had mentioned that having a software which had a lot of code was not the goal you should think of while writing code. Sometimes, there won’t be any other way than having a software which has 10,000.0 lines of code and it is okay. But what we aimed for is having a software that is as maintainable as it can be. When I say maintainable, what I mean is that simply finishing a project won’t mean that it won’t change in one day or one month or five years. A query from a client can make your project change over time,and while you’re going through those changes, you don’t want to change all the code that was written before. Having maintainable code can be achieved through different methods, and by this I don’t mean the methods we usually write in order to complete operations. One of them is code reuse.

Like it was said earlier, class B inherits from class A. Inheritance is a mechanism for code reuse. Not only B gets all the same behavior that A has,  but B has accessed to all the attributes from the class A. Has much as inheritance is a good principle to follow while doing OOP, there is something that we must keep in mind while using inheritance. When a class inherits from another, what we’re trying to achieve is to specialize a concept by adding new behaviors to the class. Basically, we have what we call the superclass which has some states and behaviors that can be common for many situations. Then, we have the subclasses which inherits those traits but add new ones. For example, we could have the superclass Person which has a Weight, Name and Age. Now, we have the classes Student, Manager and Employee.

The Student objects, since inheriting from Person, already have Name,Weight and Age. But a student has more than simply that like a grade point average (GPA) or a student id (ID). Employee is also inheriting from Person but has the properties Salary and  Bonus. Finally, we have Manager which inherits from Employee but only overrides behaviors from Employee.

That’s a benefit from inheritance. Even though we inherits from a superclass, if we like the behaviors from the previous class but there is some things that need to be change, then we can override those behaviors in order to achieve what we truly wish to do. Down below, we’ll see in code exactly what I said we can do with inheritance.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
      static void Main(string[] args)
      {
         Person aPerson = new Person("Bob", 70.45, 23);// creating a person
         aPerson.SayingHello("Sarah");

         Student aStudent = new Student("Bobby", 1023453235, 3.98, 83.67, 22); //creating a student
         aStudent.PrintStudentAverage(); //Printing the student's average

        Employee anEmployee = new Employee("Tom", 5, 25.50, 23); //creating an employee
        anEmployee.SayingHello(aStudent.Name); //The employee says hi to the student
        anEmployee.PrintEmployeeSalary(); // Printing the salary of the employee

        Manager aManager = new Manager("Kevin", 43.45, 23, 4);
        aManager.SayingHello(anEmployee.Name);
        aManager.PrintEmployeeSalary();

        Console.ReadLine();//Press Enter to quit this application
     }
   }

   public class Person
   {
     private double _weight; //we define the fields by starting with the underscore (_)

     public double Weight
     {
        get { return _weight; }
       set { _weight = value; } //We'll let the weight like this because over time, it can change
     }

     private String _name;

     public String Name
     {
        get { return _name; }
        set { _name = value; }
        //Usually, the name of a person does not change, so we'll make it private.
       //This means that no one who can access an object of Person will be able to modify the name
     }

     private int _age;

     public int Age
     {
       get { return _age; }
       set { _age = value; }
     }
     //Constructor
     public Person(String aName,double aWeight, int anAge)
     {
       Name = aName;
       Weight = aWeight;
       Age = anAge;
     }

     public Person() { }

     public void SayingHello(String personName)
     {
        Console.WriteLine("Hi, my name his : {0}. It his a pleasure to make your acquantaince {1} !", Name, personName);
     }
  }

     public class Student : Person
     {
        private int _studentID;

       public int StudentID
       {
          get { return _studentID; }
          set { _studentID = value; }
       }

       private double _gpa;

       public double GPA
       {
          get { return _gpa; }
          set { _gpa = value; }
       }

       private int _numberOfClasses;

       public int NumberClassesForTheSemester
       {
          get { return _numberOfClasses; }
          set { _numberOfClasses = value; }
       }

       private int _numberOfCredits;

       public int NumberOfCredits
       {
         get { return _numberOfCredits; }
         set { _numberOfCredits = value; }
       }

        public Student(String name, int id, double gpa,double weight, int anAge)
        {
           this.Name = name;
           this.StudentID = id;
           this.GPA = gpa;
           this.Weight = weight;
           this.Age = anAge;
        }

        public void PrintStudentAverage()
        {
            Console.WriteLine("The average of {0} is {1}", this.Name, GPA);
        }

        private void ComputeStudentGPA()
        {
           //not how we actually do it, it is more as a behaviour to add to this class
           GPA = NumberClassesForTheSemester / NumberOfCredits;
        }
     }

    public class Employee : Person
    {
      private double _hourlyWage;

      public double Salary
      {
         get { return _hourlyWage; }
         set { _hourlyWage = value; }
      }

       private int _bonus;

       public int EndOfyearBonus
       {
          get { return _bonus; }
          set { _bonus = value; }
       }

       private int _yearInCompany;

       public int YearsInCompany
       {
          get { return _yearInCompany; }
          set { _yearInCompany = value; }
       }

       public Employee(String name, int yearsOfLoyalty,double salary, int age)
       {
          this.Name = name;
          this.YearsInCompany = yearsOfLoyalty;
          this.Salary = salary;
          this.Age = age;
       }

        public Employee() { }

        public virtual void ReceiveBonus(int bonus)
        {
            EndOfyearBonus = YearsInCompany * 2 * bonus;
        }

        public void PrintEmployeeSalary()
        {
           Console.WriteLine("This is the salary : {0} $/h of {1}", this.Salary, this.Name);
        }
     }
     public class Manager : Employee
     {
        public Manager(String name, double salary, int age, int numberOfYears)
        {
           this.Name = name;
           this.Salary = salary;
           this.Age = age;
           this.YearsInCompany = numberOfYears;
        }

        public override void ReceiveBonus(int bonus)
        {
           EndOfyearBonus = 3 * YearsInCompany * bonus;
        }
     }
  }

Kevin

Advertisements

Encapsulation: How to make sure the user don’t mess up the software

0

Hi there readers,

We’ll begin our journey down the road of oriented object programming with the first principle: encapsulation. When we create a software, we have multiple pieces of data which communicate with each other to do exactly what we wish to achieve. While we would love to live in a world were the users of our software will do exactly what we hope they should do, they won’t. THEY WILL NOT. When we create a software, we must the users not as good users who will do what we want but as evil users. This way, while we’re creating a software, we’ll make sure it is bulletproof.

The first way we get to do that is with encapsulation. While some part of the data must be available to the users, or they won’t be able to use the software,  encapsulation creates a wall around the important and sensible data. We protect what is important so that no wrong or unpredictable behavior  This wall enables us to choose exactly what we wish to protect and make private and what we wish to make public for the user.

We are not going ahead of ourselves, we’re going to stay with how to make data public and private. What we really want to do is how we can access and/or modify data.   Before we get into that, we must first get comfortable with the following: fields and properties. At first, they might seem almost alike for the beginner, I myself took a little while before I got used to them, but they’re not. Fields are simply public that a class exposes.  Even though properties do exposes those variables, they give to users the ability to control how the values can be set or how they can be accessed.  But in the end, they are both a way to store and retrieve information when we’re manipulating objects in our software.

Like I said earlier, it can be hard to get used to them and to know which to use in a given situation. Usually, we use properties when one has to enforce the way a value can be retrieve any moment during the run time. We use fields for operations like a validation, for example, does this particular file exists at this moment when I need to use it (bool value).

We got to know about all of this, it would be a great time to see this all in action in an example.  We’ll create our first class with fields, properties and methods. Those are really what define an object. The properties and fields provide different states to the object and the methods give the object the behavior we expect it to have at run time.

We are going to create the class Person, class starts with an upper-cased letter, which will have a few fields such like a height or a weight.  The objects from the class Person will have a few different behaviors, such as saying hello to a fellow comrades.

Before we get into the code sample, I thought it would be a good idea to talk about how we do create objects. We have mentioned them but we barely scratch the surface. We have what the techies in this world call constructors.  They have the same name as the class we’re creating, and just like any other methods, they can, or not, receive parameters to initialize given attributes from the class at run time.


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Person aPerson = new Person("Bob", 70.45, 23);
aPerson.SayingHello("Sarah");
Console.ReadLine();
}
}

public class Person
{
private double _weight; //we define the fields by starting with the underscore (_)

public double Weight
{
get { return _weight; }
set { _weight = value; } //We'll let the weight like this because over time, it can change
}

private String _name;

public String Name
{
get { return _name; }
set { _name = value; }
//Usually, the name of a person does not change, so we'll make it private.
//This means that no one who can access an object of Person will be able to modify the name
}

private int _age;

public int Age
{
get { return _age; }
set { _age = value; }
}

public Person(String aName,double aWeight, int anAge)
{
Name = aName;
Weight = aWeight;
Age = anAge;
}

public void SayingHello(String personName)
{
Console.WriteLine("Hi, my name his : {0}. It his a pleasure to make your acquantaince {1} !", Name, personName);
}

}
}

Kevin

OOP: Do you object to this statement ?

0

Hi readers,

First of all, I’d like to wish you to have a wonderful holidays with your family, wherever you are at this moment. During the first lectures, we went over some of the basics of programming. Even though it might have seen like a lot, it was just the core fundamentals we needed to understand the basic logic in any given program. Don’t worry, we’ll cover some more later in the blog. Right now, with what we’ve seen so far, I thought it would be a good idea to get into the hype of object oriented programming.

Say what? Object oriented programming (OOP) ? Sounds funny huh? It is actually a really popular programming paradigm in the developer’s world. It is my belief that we ought all to know more about this. I don’t mean that we need to be expert in this particular field, but there’s so much to do with this paradigm that it would be a shame to not exploit what it gives us !

To begin, what is oriented object programming ? Wikipedia defines object oriented programming as the following: “a programming paradigm based on the concept of “objects”, which are data structures that contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.”  I’m going to roughly summarize this as a programming paradigm which able a given programmer to place any form of data in an “object” which can be use at anytime for any given purposes such as interact with it.

That’s some heavy abstract notions that was written. In this blog, I’m going to cover as much on this paradigm as I possibly can. OOP has a lot of advantages such as making code more flexible and more maintainable. As much as I would like to tell you that oriented-object programming is the best way to do things that you’d like to do, it is not always the case. In fact, like anything else this world, OOP has some downsides that can be unappealing like the effort it takes. To be really good in this paradigm, it takes a lot a thinking and creativity to create efficient objects which will help you reach your goals. Don’t get me wrong, I like OOP. Even if it takes some time and creativity, you must keep in mind that in any given programming paradigm, coding is a craft that takes time, no matter what you do.

Let’s head back to what OOP actually is. We saw some core basics that we all ought to master if we want to be good, or should I say, great programmers, such as loops or conditional structures (ex: if-else).  With these, we can now move to the next level, in this matter, OOP. In OOP, we define virtual objects in our software. Most of the time, we try to represent real objects from the world such as a car or a an animal (ex: a dog). More than just saying this an animal, we give this object specific behaviors with the help of methods.  Finally, at any time, an object can have a state too, such as being awake or tired in the case of a dog. To wrap up, in order to create an object Dog, we would have to define what is called a class named Dog which would be define with different attributes like a weight (double), a name (string) and a number of legs (int). To interact with this dog, we would have to define the different behaviors we expect to find in this object such as: walking, barking or sleeping. You’ll be able to see below an image that I found on the web,  which sums up what I’ve said

OOP_Objects

In the previous paragraph, I have mentioned a specific keyword of oriented object programming : class. A class is a template in which we will store all the data we need in order to define the object we want to create. That’s all there is to it. When we use objects from this class, we call them instances of the class. When I say instances I mean that once you have created an object of a particular class, you actually are creating a reference which is pointing to the data of this specific class. In short, in your code, you can have multiple references to the same class (instances) but, that does not mean they will contain the same exact data. Let’s say that you’re creating a zoo application. In a zoo, there is more than one animal of the same kind, but they aren’t identical. In the same with objects. Some can be identical. for given purposes, but some are simply not.

While we’re diving in the oriented object programming paradigm, we’ll get to see what truly makes a programming language like C# OOP with the help of encapsulation, inheritance and polymorphism. Without those three core fundamentals, you cannot use OOP with a language. But more on this in a later post.

Kevin

First real life project : Managing orders

2

Welcome reader,

This post is a small break from the programming basics serie. I’m going to talk about a real life project I will talk about in this blog. It will be an open source project, which will be accessible from my GitHub account profile.  Before going talking more about the basics, I thought it would be a good idea to talk about what could be achieved when we will put everything that was learned and mastered here in this blog.

You have to create a software application which will store a large number of clients. These clients will make orders and they have to save in a database which must be available a least 95% of the time. Sometimes, special orders takes more time than usual before they come in, when this happens, you can either make it so that when it happens, you automatically send emails to users or u make a query in the database to select users and then send the email. For emails in this situation, you should have templates which would just receive dynamic data so the user of the software has less manipulation to do.

For users, the fun would be to have a self-contained mobile application . What I mean is this:

  • sign in into the app with all our information.
  • Be able to see whats going on in our account.

Moreover, while using a mobile device, such as a phone or a tablet, users would have notification of what going on. Even if emails are sent to the email account, it would even better to select what kind of feedback from the company a customer would like to receive.

In this example, we have a software application which must use a database. The information must be available at least 95 % of the time, so the fail rate has to be really low. The information on the orders must be available online so the users can access it from his mobile device with their app.

In our dev world, there are many ways to complete a task. What I recommend is usually go with what you know so you’ll know what you’re doing while you are doing it. But, in a realm in which things move faster than when oneself blinks his eyes, I think it would be a benefit to try out new technologies in order to gain experience.

For this kind of problem, I have chosen to use:

  1. C# with the object oriented paradigm
  2. Windows Phone (Universal App)
  3. The Android Operating System
  4. Reactive Extension (Rx)
  5. LINQ
  6. The Firebase database

Honestly, I haven’t really experimented the technologies #2, 4 and 6. But I’m not going into this series before we’re ready to do it. So during that time, I’ll get my hands dirty. In the developers community, when someone says getting their hands dirty, it is meant as programming. In order to understand something, we really need to experiment by ourselves, even if the code makes sense to you, I strongly suggest that you at least copy paste it into your IDE and run the application to see how it works on your machine. What would be best is to modify the code, play with it until you truly understand what’s going on.

On the topic of the open source project, I’m going to take you step by step in my solution. This is going a more advanced serie, but bear no fear, if there things that you don’t understand, post comments and I’ll answer you to the best of my knowledge. At first, we will setup our database before going into coding. Then, we’ll design our software application for the company. Then design our mobile app. Afterwards, when the designs are completed, I’ll explain the more complex parts of my implementation, but not all of it. You’ll be able to find the project on my GitHub. Don’t worry, it’ll be commented!

Kevin