Pages

Showing posts with label Object-oriented programming fundamentals. Show all posts
Showing posts with label Object-oriented programming fundamentals. Show all posts

Monday, August 24, 2015

Implement callback routines CallBack using OOP

Developers conversant in the event-driven programming model of MS-Windows and the X Window System are accustomed to passing function pointers that are invoked (that is, "called back") when something happens. object-oriented model does not currently support method pointers, and thus seems to preclude using this comfortable mechanism

Interfaces provides a mechanism by which we can get the equivalent of callbacks. The trick is to define a simple interface that declares the method we wish to be invoked.

 

 public interface InterestingEvent
    {
        // This is just a regular method so it can return something or
        // take arguments if you like.
        void interestingEvent();
    }

    public class EventNotifier
    {
        private InterestingEvent ie;
        //private bool somethingHappened;
        public EventNotifier(InterestingEvent e)
        {
            Console.Write("EventNotifier called\n");
            // Save the event object for later use.
            ie = e;
            // Nothing to report yet.
            e.interestingEvent();
        }
    }


   public class CallMe : InterestingEvent
    {
        private EventNotifier en;
        public CallMe()
        {
            // Create the event notifier and pass ourself to it.
            en = new EventNotifier(this);
        }
        // Define the actual handler for the event.
        public void interestingEvent()
        {
            Console.Write("Call Me function called");
        }
        //...
    }

     //*****Client Side**************
     CallMe obj = new CallMe();
     Console.ReadKey();
     //******End***************

Friday, June 12, 2015

SOLID Principles Of OOPS


Overview Of S.O.L.I.D 


While Designing a class the principles of S.O.L.I.D are guidelines that can be applied to remove code smells. S.O.L.I.D
  •     Single Responsibility Principle (SRP)
  •     Open/Close Principle (OCP)
  •     Liskov Substitution Principle (LSP)
  •     Interface Segregation Principle (ISP)
  •     Dependency Inversion Principle (DIP)

Single Responsibility Principle (SRP) It states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. There should not be more than one reason to change the class. This means class should be designed for one purpose only. This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and on future if we need to make one change we are going to make it in the class which handle it. When we need to make a change in a class having more responsibilities the change might affect the other functionality of the classes. Example- Employee class: This class is using for CRUD functionality of Employee, Then it should not have any method to MAP Employee attributes with Database columns, Because later if there is any new column added in Database, the class need to be modified which is violationg the rule of Single Responsibility Principle.


Open/Close Principle (OCP) It states that Class should be open for extension not for modification. Usually, many changes are involved when a new functionality is added to an application. Those changes in the existing code should be minimized, since it's assumed that the existing code is already unit tested and changes in already written code might affect the existing functionality. This is valuable for Production environment where the source codes has already been reviewed and tested. Adding the New functionality may causes the problem on existing  code.


Liskov Substitution Principle (LSP)
Basically when we designed a class, we use maintain Class hierarchies. We must make sure that the new derived classes just extend without replacing the functionality of old classes. Otherwise the new classes can produce undesired effects when they are used in existing program modules.
LSV states that if the module using any base class, then the reference to the Base class can be replaced with a Derived class without affecting the functionality of the program module.

Example : - A typical example that violates LSP is a Square class that derives from a Rectangle class, assuming getter and setter methods exist for both width and height. The Square class always assumes that the width is equal with the height. If a Square object is used in a context where a Rectangle is expected, unexpected behavior may occur because the dimensions of a Square cannot (or rather should not) be modified independently. This problem cannot be easily fixed: if we can modify the setter methods in the Square class so that they preserve the Square invariant (i.e. keep the dimensions equal), then these methods will weaken (violate) the postconditions for the Rectangle setters, which state that dimensions can be modified independently. If Square and Rectangle had only getter methods (i.e. they were immutable objects), then no violation of LSP could occur.

Interface Segregation Principle (ISP)
It states avoid tying a client class to a big interface if only a subset of this interface is really needed. Many times you see an interface which has lots of methods. This is a bad design choice since probably a class implementing. . This can make it harder to understand the purpose of a component, but it can also cause increase coupling, where by components that make use of such a component are exposed to more of that components capabilities that are appropriate.
The Interface Segregation Principle (or ISP) aims to tackle this problem by breaking a components interface into functionally separate sub-interfaces. Although a component may still end up with the same set of public members, those members will be separated into separate interfaces such that a calling component can operate on the component by referring only to the interface that concerns the calling component.


Dependency Inversion Principle (DIP)
In an application we have low level classes which implement basic and primary operations and high level classes which encapsulate complex logic and rely on the low level classes. A natural way of implementing such structures would be to write low level classes and once we have them to write the complex high level classes. Since the high level classes are defined in terms of others this seems the logical way to do it. But this is not a flexible design.
High-level modules should not depend on low-level modules. Both should depend on abstractions.Abstractions should not depend on details. Details should depend on abstractions

Friday, November 2, 2012

Dependency Injection


First, let’s examine the idea of dependency injection by walking through a simple example. Let’s say you’re writing the next blockbuster game, where noble warriors do battle for great glory. First, we’ll need a weapon suitable for arming our warriors.
class Sword 
{
    public void Hit(string target)
    {
        Console.WriteLine("Chopped {0} clean in half", target);
    }
}
Then, let’s create a class to represent our warriors themselves. In order to attack its foes, the warrior will need an Attack() method. When this method is called, it should use its Sword to strike its opponent.
class Samurai
{
    readonly Sword sword;
    public Samurai() 
    {
        this.sword = new Sword();
    }

    public void Attack(string target)
    {
        this.sword.Hit(target);
    }
}
Now, we can create our Samurai and do battle!
class Program
{
    public static void Main() 
    {
        var warrior = new Samurai();
        warrior.Attack("the evildoers");
    }
}
As you might imagine, this will print Chopped the evildoers clean in half to the console. This works just fine, but what if we wanted to arm our Samurai with another weapon? Since the Sword is created inside the Samurai class’s constructor, we have to modify the implementation of the class in order to make this change.
When a class is dependent on a concrete dependency, it is said to be tightly coupled to that class. In this example, the Samurai class is tightly coupled to the Sword class. When classes are tightly coupled, they cannot be interchanged without altering their implementation. In order to avoid tightly coupling classes, we can use interfaces to provide a level of indirection. Let’s create an interface to represent a weapon in our game.
interface IWeapon
{
    void Hit(string target);
}
Then, our Sword class can implement this interface:
class Sword : IWeapon
{
    public void Hit(string target) 
    {
        Console.WriteLine("Chopped {0} clean in half", target);
    }
}
And we can alter our Samurai class:
class Samurai
{
    readonly IWeapon weapon;
    public Samurai() 
    {
        this.weapon = new Sword();
    }

    public void Attack(string target) 
    {
        this.weapon.Hit(target);
    }
}
Now our Samurai can be armed with different weapons. But wait! The Sword is still created inside the constructor of Samurai. Since we still need to alter the implementation of Samurai in order to give our warrior another weapon, Samurai is still tightly coupled to Sword.
Fortunately, there is an easy solution. Rather than creating the Sword from within the constructor of Samurai, we can expose it as a parameter of the constructor instead.
class Samurai
{
    readonly IWeapon weapon;
    public Samurai(IWeapon weapon) 
    {
        this.weapon = weapon;
    }

    public void Attack(string target) 
    {
        this.weapon.Hit(target);
    }
}
Then, to arm our warrior, we can inject the Sword via the Samurai ‘s constructor. This is an example of dependency injection (specifically, constructor injection). Let’s create another weapon that our Samurai could use:
class Shuriken : IWeapon
{
    public void Hit(string target)
    {
        Console.WriteLine("Pierced {0}'s armor", target);
    }
}
Now, we can create an army of warriors:
class Program
{
    public static void Main() 
    {
        var warrior1 = new Samurai(new Shuriken());
        var warrior2 = new Samurai(new Sword());
        warrior1.Attack("the evildoers");
        warrior2.Attack("the evildoers");
    }
}
This results in the following output to be printed to the console:
Pierced the evildoers armor.
Chopped the evildoers clean in half.
This is called dependency injection by hand, because each time you want to create a Samurai, you must first create some implementation of IWeapon and then pass it to the constructor of Samurai. Now that we can change the weapon the Samurai uses without having to modify its implementation, the Samurai class could be in a separate assembly from Sword – in fact, we can create new weapons without needing the source code of the Samurai class!
Dependency injection by hand is an effective strategy for small projects, but as your application grows in size and complexity, it becomes more and more cumbersome to wire all of your objects up. What happens when the dependencies have dependencies of their own? What happens when you want to add a (e.g. caching, tracing to a log, auditing etc.) decorator in front of each instance of a given dependency? You can easily end up spending most of your time creating and wiring together objects, when you could be writing code that adds real value to your software. This is where dependency injection libraries / frameworks like Ninject can help.

Ref:- Here


For Eg:-
 class Client
    {
        static void Main(string[] args)
        {
            var con1 = new Assembly(new SQLConnection());
            Console.Write(con1.WriteConnection() + "\n" );
            var con2 = new Assembly(new MySQLConnection());
            Console.Write(con2.WriteConnection() + "\n");
            var oracle = new Assembly(new OracleConnection());
            Console.Write(oracle.WriteConnection());
            Console.Read();
        }
    }

    public interface IConnection
    {
        string GetConnection(string con);
    }

    public class SQLConnection : IConnection
    {
        public string GetConnection(string conn)
        {
            return conn;
        }
    }

    public class MySQLConnection : IConnection
    {
        public string GetConnection(string conn)
        {
            return conn;
        }
    }

    public class OracleConnection : IConnection
    {
        public string GetConnection(string con)
        {
            return con;
        }
    }


    //This is a assembly which will be loosely coupled in spite of any connection
    public class Assembly
    {
        readonly IConnection objCon;
       //We inject connection in constructor
        public Assembly(IConnection conn)
        {
            this.objCon = conn;
        }

        public string WriteConnection()
        {
            return this.objCon.GetConnection(this.objCon.ToString());
        }
    }
Thanks,
Amit

Thursday, July 14, 2011

Object Oriented Programming - Concepts

Object Oriented Programming

OOP is Nothing but Object Oriented Programming.
In OOPs concept is implimented in our real life systems.
OOPs have following features
1. Object - Instance of class
2. Class - Blue print of Object
3. encapsulation - Protecting our data
4. polymorphism - Different behaviors at diff. instances
5. abstraction - Hidding our irrelavance data
6. inheritence - one property of object is aquring to
another property of object

Simple Ex.
Please assume u standing near a car.
How to impliments our OOPs concept for this scenario ?
Simple,
car is a object b'coz it having more functions.
car is a class b'coz it contain more parts and features inside.
car is a Encapsulation B'coz it protected some unwanted parts or
functions to user car is a Polymorphism b'coz it have different
speed as display in same speedometer car is a Abstraction b'coz
it hidding more parts by coverig such as engine,disel tank car
is a Inheritance b'coz one car is a property of more people.
i mean your car is driving bu you, your friend and your relatives.

Wonderful source link for OOPS concepts:-
http://www.desy.de/gna/html/cc/Tutorial/tutorial.html


Q:what is difference between instance and object.?
instance means just creating a reference(copy) .
object :means when memory location is associated with the object( is a runtime entity of the class) by using the new operator

Q:what are the all difference between interface and abstract class?
interface is a set of abstract methods, all of which have to be overriden by the class whichever implements the interface
abstract class is a collection of data and methods which are abstact (not all of them)

Interfaces are essentially having all method prototypes no definition but Abstract class can contain method definations also.

In short Interface is a abstract class having all methods abstract.
Both abstract classes and interfaces are used when there is a difference in behaviour among the sub-types extending the abstract class or implementing the interface.

When the sub-types behaviour is totally different then you use an interface, when the sub-types behaviour is partially common and different with respect to the supertype an abstract class is used. In an abstract class the partially common behaviour is given a concrete implementation. Since there is no common behaviour between an interface and a sub-type an interface does not have an implementation for any of its behaviour.
If you create a abstract class writing the abstract keyword in the declaration part then You only can inherit the class. You can not create an instance of this abstract class but can inherit the class and with creating the instance of the derived class you can access the method of the abstract class.

If you use a virtual keyword in a method then you can override this method in the subclass if you wish..
If you create a abstract method then you must override this method in the subclass other wise it shows error in the program.


1) What is meant by Object Oriented Programming?
OOP is a method of programming in which programs are organised as cooperative collections of objects. Each object is an instance of a class and each class belong to a hierarchy.

2) What is a Class?
Class is a template for a set of objects that share a common structure and a common behavior.

3) What is an Object?
Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class.

4) What is an Instance?
An instance has state, behaviour and identity. The structure and behaviour of similar classes are defined in their common class. An instance is also called as an object.

5) What are the core OOP’s concepts?
Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOP’s concepts.

6) What is meant by abstraction?
Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model.

7) What is meant by Encapsulation?
Encapsulation is the process of compartmentalizing the elements of an abstraction that defines the structure and behavior. Encapsulation helps to separate the contractual interface of an abstraction and implementation.

What is meant by Inheritance?
Inheritance is a relationship among classes, wherein one class shares the structure or behavior defined in another class. This is called Single Inheritance. If a class shares the structure or behavior from multiple classes, then it is called Multiple Inheritance. Inheritance defines “is-a” hierarchy among classes in which one subclass inherits from one or more generalized superclasses.
9) What is meant by Polymorphism?
Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class.
10) What is an Abstract Class?
Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behavior, typically by implementing its abstract operations.

11) What is an Interface?
Interface is an outside view of a class or object which emphasizes its abstraction while hiding its structure and secrets of its behavior.

12) What is a base class?
Base class is the most generalized class in a class structure. Most applications have such root classes. In Java, Object is the base class for all classes.

13) What is a subclass?
Subclass is a class that inherits from one or more classes
14) What is a superclass?
superclass is a class from which another class inherits.

15) What is a constructor?
Constructor is an operation that creates an object and/or initializes its state.

16) What is a destructor?
Destructor is an operation that frees the state of an object and/or destroys the object itself. In Java, there is no concept of destructors. Its taken care by the JVM.
17) What is meant by Binding?
Binding denotes association of a name with a class.

18) What is meant by static binding?
Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.

19) What is meant by Dynamic binding?
Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.

20) Define Modularity?
Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.

21) What is meant by Persistence?
Persistence is the property of an object by which its existence transcends space and time.

22) What is collaboration?
Collaboration is a process whereby several objects cooperate to provide some higher level behavior.

23) In Java, How to make an object completely encapsulated?
All the instance variables should be declared as private and public getter and setter methods should be provided for accessing the instance variables.

24) How is polymorphism achieved in java?
Inheritance, Overloading and Overriding are used to achieve Polymorphism in java.

25) What is sealed and abstract class?

Source link:- http://msdn.microsoft.com/en-us/library/ms173150%28v=vs.80%29.aspx

Compile time polymorphism is functions and operators overloading.
Runtime time polymorphism is done using inheritance and virtual functions.
eg compile time polymorphism -- method overloding

run time time polymorphism -- method overriding

Static classes and static methods

  1. Static Class occupy memory during compile time.
  1. Static class cannot be instantiated. It calls its data members and member functions itself.
  1. Static class can have static members only as its cannot declare instance members in a static class
  1. Static class constructor get called whenever any static member is called.
  1. General Class can contains static methods but they too called its-self by class name.