Thursday, 12 July 2012

Delegates and Events


The audio blog is here
Delegation :
                    Delegates mean those who are responsible. Delegation is handing over the responsibility a particular class to some other class. This lets objects to follow the single responsibility principle. If too much responsibility is being added to the class , you can delegate the responsibility to another class.
          

Delegates and Events:
                  In programming delegates are classes that have the responsibility to handle particular events. An event can range from a key stroke to a system call due to some internal errors. To simplify the explanation of delegates to a simple form you can relate the Delegates to function pointers in C.
              A typical delegate has a signature. The syntax of a delegate is,
              Delegate return_type Delegate_name(input type1,.....)
              The signature of the delegate is the return type and the input parameters.
              for example,
              public Delegate int my_first_delegate(int,int ) is a delegate. It can have functions that returns an int and gets two integer parameter.

                Example 1:
                  int add(int a,int b)
                   {
                          // do addition and return the value
                    }
                  public Delegate int my_first_delegate(int,int ) ;
                  my_first_delegate first=new my_first_delegate(add)
         
              Here you can call the add method using, first.invoke(10 ,20 );

Why Delegates ?
          Delegates came into existence because of various things. They came to handle the events when an event is getting triggered. They are also used in abstracting the user from  having the entire working section of code onto the client side.
          Consider the call add( 20  ,30 ) being made from the client side. If you have deleted the method on the server. The client will be reported with an error. To prevent such things we may use a Delegate. The generic pointer with the signature described in the previous example can be declared and used.
         If many functions are declared and the function to which the call has to be made can be changed dynamically. Consider the following example,
             
             public class list_function
             { 
                    public delegate int two_functions(int i, int y); 
                    public PointerMaths getPointer(int intoperation) 
                   { 
                         two_functions objpointer = null; 
                          if (  intoperation == 1  ) 
                         { objpointer = Add; } 
                          else if (  intoperation == 2  ) 
                         { objpointer = Sub; } 
                          else { objpointer=Print_list_the_functions_available; } 
                           return objpointer; 
                    }
                   private int add(int a,int b)   
                   {
                         return a+b;
                    }
                   private int sub(int a,int b)   
                   {
                         return a-b;
                    }
                     private int Print_list_the_functions_available(int a=0,int b=0)
                      {
                            print "1-->ADD , 2-->SUB , only two choices are available";
                            return -1;
                       }
               }
           In the client side of the code will be something like this,

            list_function ls=new list_function();
            int temp = ls.getPointer(3) .Invoke();
            int result = ls.getPointer(1).Invoke(30,20);

          The above code will result in addition function getting invoked.

Multicast Delegates :
           There are some times when more than a function are needed to be coupled to the delegate.
            Consider a scenario when a building is in fire, you will need a automated system to start showers inside the building , raise an alarm, stop elevators, make a call to the nearest fire engine service.
           All these functions are coupled one after another. This can be done using a multicast delegate.
            E.g :
             public void handle_fire_breakout();
             handle_fire_breakout hfr = null;
             hfr += start_shower();
             hfr += raise_alarm();
             hfr += stop_elevators();
             hfr += call_fire_engine();

            if the hfr is being called from the monitoring client side it may get called using ,
              in_case_of_fire.get_pointer().Invoke();

           The above mentioned methods will execute sequentially in the order by which they were added to the delegate.
            There are certain disadvantages in multicast delegates. If the methods which are getting invoked by the delegate eg. start_shower() belonged to another class called Shower then a problem  occurs. The delegate will be calling the method of another object(Shower) without even asking for the objects approval.
           If we put it in another way i.e, if the delegates are within the class Shower it will be a problem. Because the class shower will have the complete authority over the delegate and it can add any function over the delegate which is undesirable.
          To overcome these concepts we move on to the concept of events.

Events :
       Events will be assigned a listener of the events and the listener can add themselves to be the listener of the particular event. Thus overcoming both the problems described earlier.
        So how to accomplish the previous fire_monitoring thing using events. We shall see now,
        Class Shower // event_handler
        {
                 Shower(Fire_control fc)
                 {
                       fc.hfr_new += new handle_fire_breakout(start_shower); // assign event to a listener
                  }
                  private static start_shower()
                  {
                      // make the shower pour water
                   }
         }
         Class Fire_control
         {
                  public void handle_fire_breakout();
                  void execute ()
                  {
                      event  handle_fire_breakout hfr = null ; // event in the class
                       hfr += raise_alarm();
                       hfr += stop_elevators();
                       hfr += call_fire_engine();
                      if(fire_arises())
                      {
                             hfr();  //calling the event makes the listener start_shower
                      }
                   }
                   raise_alarm() {....}
                   stop_elevators() {...}
                   call_fire_engine() {...}
          }
          Class main_
          {
                  Fire_control fc= new Fire_control();
                  Shower(fc);
                  fc.execute() ;
           }
          This makes the event getting triggered in the Fire_control class will be listened by the start_shower function method of the Shower class.

Wednesday, 11 July 2012

Design Patterns in OOPS

Design Pattern :
             There are certain problems which seem to be occurring from time to time and the programmers have come up with a way to solve these problems and classified the solutions as various patterns.
               Patterns are not a completely implemented solution but a description or template to solve the problem. It tries to prevent the programmer from making a bad code.The general principles suggested to be followed are,

OPEN CLOSE PRINCIPLE :
                " Software entities like classes, modules and functions should be open for extension but closed for modifications. "
               If you add a new functionality to a class make the changes without affecting the previously existing code. Consider the following example,
                 class Car {
                     public:
                     ..........
                     Petrol P;
                     Car(){P=0;}
                      Fill_tank(Petrol litres){P+=litres;}
                      Run(){run using the petrol;}
                      ...........
                  }
                  The above mentioned Car class will be handling only petrol cars. If a new diesel car comes we need to change the code inside the Car and add new methods. If the Car class is a highly complex class and edited by many people it will be better if we implement the new functionality outside the Car class.So its better to write a generic car code which can be made to run using any fuel.
 
                class Car{
                  public:
                  Fuel f;
                  Car(){f.content=0;}
                  Fill_tank(Fuel temp){f.content+=temp.content;}
                  Run(){run using the fuel;}
                }
                 class Fuel{
                   int content;
                 }
                  class Petrol : public Fuel{
                  }
                  class Diesel: public Fuel{
                  }

DEPENDENCY INVERSION PRINCIPLE :
                   Dependency Inversion Principle states that when you go for designing , design the complex classes first and then go for designing the simple classes. This is because the complex classes will be difficult to modify in future, rather than changing the simple classes.
                    For example: consider a ATM machine which is using a button type input interface. Even If the button type is replaced by a touch screen type the underlying working of the ATM machine should not be changed for changing the input interface. This comes by following the DIP principle.

INTERFACE SEGREGATION PRINCIPLE :
                   This Principle concentrates on the design of the interfaces. Interfaces should be able to accommodate the changes in future. If a bad interface is designed you will have the problem of unnecessarily implementing the methods of the interface in the class inheriting it.
                      If you are designing an interface for Power Generator. Control_pollution()  is a method to be implemented. But if the Power Generator is using a renewable resource you need not implement the Control_pollution() method.
                    So its better you go for two interfaces of Power_Generator_Renewable and Power_Generator_non-Renewable.This will segregate the interfaces. Caution: Be careful while following the principle because you may end using way too many interfaces.
                   To apply the principle have a balance between complicating the code using new interfaces and avoiding unnecessary implementation of methods in the class using interfaces.

SINGLE RESPONSIBILITY PRINCIPLE :
                  According to the principle assign a class with only one responsibility. If you are trying to assign more than one responsibility you better break down the code into two different classes.
                 Many people may find this principle annoying as i personally do. But it will be better if you don't put too much methods into a single class. Because it will spoil the use of object oriented approach as you are not properly identifying the objects...!!!

LISKOV'S SUBSTITUTION PRINCIPLE :
                 This means that the if a parent class has a method and a child class inherits it. The way the child class execute the methods should not be different from the way the child executes the method.
                   If Light is a class and turn_on() is a method in it. The turn_on() method should return the same function of giving light for Light class or any other class derived from it eg. Tube light or neon light.
               
               eg. Consider a Point_2d class and a Point_3d class inherited from the Point_2d class.
                  Point_2d {
                     int x,y;
                     2d(int a,int b){x=a,y=b;}
                      same_points(Point_2d p)
                      {
                              if(this.x==p.x && this.y==p.y)  return true;
                              return false;
                       }
                  }
                 Point_3d: public Point_2d{
                      int z;
                       3d(int a,int b,){x=a,y=b;z=random()%1000;}
                       3d(int a,int b,int c) {x=a,y=b,z=c;}
                        same_points(Point_3d p)
                        {
                                if(this.x==p.x && this.y==p.y && this.z==p.z) return true;
                                return false;
                         }
                 }

                The same_points() in the parent class works differently from that of the same_points() in the derived class.This is a violation of LSP.
               This may make you feel that LSP doesn't allow method over riding right.?? Yeah its a violation of LSP to use method over riding. Not all principles can be followed all the time as they are general guidelines for a better code.

REFACTORING :
            Refactoring the code means making the code which you wrote to follow the above mentioned principles. Your code may be functional but it will be a better code if you change your code to follow these principles.

DESIGN PATTERNS:
                         There are a lot of design pattern to discuss. And people may want to know which pattern should one go for to solve the problem. To these people i might suggest you may not always get solution from the classified patterns. There may be some situations where you might have coded according to a pattern without knowing that it is a pattern design.

Example : Singleton class.
             Singleton class is a design pattern. In this pattern there should be only one copy of object of the singleton class. These can be like the init process in the system. The system can contain any number of other processes but only one init process.
               The implementation requires use of a private constructor to prevent any object from creating the object directly. A static member which is to mark the creation of the first and only object for the entire program. And a method to call the private constructor.
             Similarly any non-sharable resources like printer can be quoted as examples. These should be implemented in such a way that they work well in multi-threaded environments too.
              Usually they are implemented by mechanisms similar to that of semaphores or using a static member of the class.

Disadvantages of patterns :
                         Pattern are not always advantageous as they might lead to unnecessary complication of the code. Don't use pattern unless they are really necessary and don't overuse the design patterns.

Anti Pattens:
                  These refer to the patterns that exist in the real world and they are counter productive and often lead to bad consequences. For example : Hard coding and not rechecking the code having a blind faith in the code .
          

Tuesday, 10 July 2012

Interfaces and Abstract Classes in OOPS


My Audio Blog for this page here

Abstract Classes :
                             Abstract classes are the classes that cannot be instantiated. They cannot have objects but they serve as a tool to maintain some hierarchical structure in the program. These classes can contain methods which may contain or may not contain definition. But there should be at-least one undefined method. The class can contain member variables also.
                             Abstract classes helps in aggregating the classes of similar type to have a single base class. For example , a squirrel and a human can be very different in nature but by classification they belong to the same abstract class of Animals as they have common behavior.
                    Class Animals{
                      see(){use eyes to watch ;}
                      hear() {use ears to hear;}
                      move(){}=0;
                     }
                   Class Man : Animals{
                     move(){use two legs;}
                   }
                   Class Squirrel : Animals{
                     move(){use four legs;}
                    }
                     Abstract class will have the basic behavior of all the classes inherited from it. The user can inherit the abstract classes and add additional behavior he wants to his new class.

Interface :
                   Interfaces seem to be similar to Abstract Classes but they are not allowed to define anything inside them. They are just to list the set of methods which must be implemented in the class which implements the interface. They are to support multiple inheritance.
                   Multiple inheritance are not supported in java and C#. So programmers come up with interfaces to handle this. A class can have not more than one parent class , but it can have any number of interfaces. The iphone has both the qualities of a connecting device and a computer. So we may design the model like this,

                  interface connecting_device{
                          make_call();
                          get_call();
                  }
                   Class computer{
                      use_browser();
                      use_applications();
                      watch_movies(){use a player to run the movie on screen};
                       store_info();
                   }
                   Class iphone: extends computer , implements connecting_device{
                      make_call(){....}   
                      get_call(){....}
                      store_info(){....}
                   }
                   Class nokia_1100: implements connecting_device{
                         make_call(){...}
                         get_call(){...}
                    }

                 In case where you need a class which has more than a behavior we categorize it in a single domain and use interface to attain the rest of the behavior.

Abstract vs Interface :
                  The users may confuse as when to go for Interface and when to go for Abstract class. They have some similarities as they cannot be instantiated and contain undefined functions. But Interface is not a class.
                  It all depends on the way you look at your problem. But my best advice would be to look for any common behavior in the objects. If they exist make a abstract class and define the common behavior within the class and inherit the classes from the abstract class.

Partial Classes:
                Partial classes is a new concept in C#. Using partial classes we can split the classes into multiple files.Compiler will treat them as different classes but when compiled they execute as a single class.

Monday, 9 July 2012

Association , Aggregation and Composition in OOPS



Association :
                 Association is the relationships between classes. They can be one-to-one , one-to-many , many-to-many. Aggregation is a special case of Association.

               For example : An object of a class Person can be related with only one  object of person as a spouse. This is a one to one relation.
                                      An object of class Person can be related to any number of Car object as a owner. This is a one-to-many relation.

Aggregation :
                 It is regarded as 'has a' relation between two objects. But it is less constrained in a way that one object can exist even if the other one perishes.
              For example : A Desktop has a NIC(Network Interface Card). It means that they are related yet the desktop can exist without a NIC.

Composition:
               It is a form of Aggregation , but it has more constraint applied over it. Here the object in the relationship will exist only if the other exists.
               For example : A Desktop has a Mother Board. The desktop will exist only if the Mother Board Exists. Thus is a strong form of Aggregation .

Polymorphism On OOPS

Polymorphism :
                  Polymorphism exists in OOPS. Polymorphism is associated with a class , method and objects . By polymorphism we mean that the method or class that we talk about exhibits different property at different situations.Polymorphism comes into picture because of the following ,
                  1) Inheritance
                  2) Overriding
                  3) Dynamic binding
                  4) Overloading

A simple example :
          class output{
                 public :
                 print(string s) {cout<<s;}
                 print(int s){cout<<s;}
           }
            int main()
            {
                output o; o.print("my score is ") ; o.print( 0 );
             }
        
              This is called as overloading a function and we can discuss about this later. The thing to note is even though the same function name is used the function called are different.

Why Polymorphism :
            Most people wont find the need to go for the overloading concepts . It wont be difficult to have a different name for different type of execution. But the key idea to go for polymorphism is to abstract the business logic from the users. For example : you know that decimal values are stored in C . But you never know what how they are stored. The reason is that it is not important.

Inheritance :
             Inheritance is deriving the base class methods and the attributes by the derived class.
                Class vessel
                 {
                              int litres;
                              void hold_water(int liters){volume=litres;}
                               bool will_break()=0;
                 }
                 Class Plastic_bottle : public vessel
                  {
                              bool will_break(){return false;}
                  }
                 Classic Glass_bottle : public vessel
                 {
                             bool will_break(){return true;}
                  }
                  int main()
                  {
                         Class * bottle = new Plastic_bottle();
                         cout<<bottle.will_break();   // will return 0
                         bottle = new Glass_bottle();
                         cout<<bottle.will_break();   // will return 1
                   }
            Polymorphism is linked with inheritance because a vessel can be made to contain water no matter what type is it in, either a Glass_bottle or a Plastic_bottle. But it might break depending on the material from which it was built from.


Overriding and Late Binding:
             Overriding is used in Inheritance when the derived class needs to implement certain methods its own way which are already defined in the parent class. So it overrides the method  in the parent class with the same name.

               Class Rented_vechile
                {
                      virtual void collect_money(){ Get money for traveled distance;}
                }
                Class Share_auto: Rented_vechile
                {
                       void collect_money(){Get money from each individual for his travel;}
                }
                int main()
                {
                     Rented_vechile *rv=Share_auto();
                     rv->collect_money();
                }
             The above code has called for the method and there is no need to explicitly mention that it to the derived class. This can be quoted as an example for late binding as well. In late binding the compiler doesn't know to which object's method is getting called until run-time, bcoz both the base class and derived class have the same method.

 Overloading:
          The methods which you invoke from certain objects execute differently depending on the parameters passed on to it. This is method level polymorphism.
            Operator overloading in C++ is a special kind of polymorphism in C++ because you cannot replace the original functionality of the operators but you can add additional functionality to them.
           For example :  The operator '+' will execute for addition for numbers. We can add additional functionality to this by making it concatenate two strings.