Polymorphism: Empowering your objects

0

Hi there readers, So, we’re finally getting into the final pilar of object oriented programming, polymorphism. It’s a strange word at first, but we get use to it pretty fast.

What does the word polymorphism mean?

The root of polymorphism is traced back to the greeks. Poly means many and morphism mean forms. Basically, polymorphism gives an object the ability of having multiple forms. The fact that an object can have multiple forms means that while using inheritance of dependency injection (an advance topic which will be mentioned later), we don’t have to care what kind of object we’re calling during runtime. Having multiple forms means that while calling a certain function, in the hierarchy of objects, custom or not, it won’t matter which objects is being called. A real world example of polymorphism

Example

Everyone is a person, but each one as his own waking up routine at a specific time of the day:

  • As a waiter
  • As a lawyer
  • As a student taking classes at nights

Method overriding? Virtual methods? What are those ??

Basically, virtual methods are found in the parent class. Virtual methods are behaviors in parent objects which can be overridden by their children. To make sure a method can be use by the children and be overridden, not only it must have the virtual keyword in its signature, but it should also have the protected keyword to make sure that only children can use it. This is a key concept in oriented object programming.

Easily, it’s possible to see why such a feature can be attractive for programmers. We love code reuse and we hate rewriting the same piece of code. Some readers might wonder why we hate rewriting code, right ? Well, it’s pretty simple in fact. It’s a bad programming behavior, YOU SHOULD NOT DO THAT ! Having to rewrite code will double or even triple or X factor time the amount of time you need to invest into maintaining the software.

Back to virtual methods. Having a basic foundation for most of the component in your system simplifies the work that must be completed. More than just this, when you’re overriding behaviors, it’s because you have a darn god reason to do this. in fact, while you’re testing your code or going over your software a few months after writing it, you’ll understand exactly why you did why you did. We usually do this because we have a good reason why.

public abstract class Human
{
   protected virtual void Greetings(string name)
   {
       Console.WriteLine("Hi, my name is {0}:", name);
   }
}

public class Doctor : Human
{
   public void GreetingPatient(string patientName,string doctorName)
   {
     Console.WriteLine("Hello {0}",patientName);
     Greetins(doctorName);
   }
   protected override void Greetings(string name)
   {
     Console.WriteLine("Hi, I'm doctor {0}. It's nice to meet you.",name);
   }
 }
Advertisements

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

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