Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Saturday, September 13, 2014

Improve Performance of the Application

As and software producer all of us want to do is software product with correct functionality. Is that enough ? No. We need to give product with correct functionality with optimum resource consumption as well.

Today I'm going to tell you some tips and trikes about resource optimization. basically it is about Memory and CPU resources.

1. Switch for multiple If
 When you are using multiple If conditions ( Most of the time more than 2 ) CPU (Registry level) instructions check as far as use much If with code. It consume more registers in CPU. But with switch it just use check and Jump CPU instruction that far more faster than assignments. Using jump tables makes switches much faster than some if-statements

Use switch when ever possible once you find more than two if statements.

2. Use structures according to the situation
Execution of class is much more consume resources than class.  Whenever you don't need to use functions bind with objects and when you don't go with boxing and unboxing much with code.

3. Chunky calls
Don't let your functions to handle lot of task by itself. use modularity to avoid it.

4. Add Collections
Never try to assign collection items one by one to the another collection. Just try to use simple casting and try to add entire collection directly.

5. Working with strings.
When you are working with string most of the cases we try to concatenate string by '+'operator.(including me ). But sad story is there is more optimal solution than that. use string bulider to concatenate strings.

Here for start.

6. Use bits whenever as possible.
I saw most of the programmers use integers/strings to hold the simple states, flags. Please don't do that there is more than 2 states. Just use bit or bool to store states. It will optimize code and resource as well. ( Simply bit is smaller than more bits)

7. Array as possible
When we use simple basic array it will helpful to maintain machine instructions(registry). Other collections need more than array because most of them are derived form it. Array is basic element in modern machine instructions.

8. ObservableCollection vs List
Use List whenever that your items not binded with the UI. Observation collections are derived from List and it also holds the property changed notifications. If there is no use of property change go for List.  ObservableCollection check the property change when it on use and because of that it consume more.

9. For than foreach
Use while, for and do while loops wherever than foreah. foreach has good performance but basic loops are better than it.

10. ToString
Some  programmers use ToString method wherever elements are already strings. Use ToString wherever the element that con the string. don't use ToString as habit. With integers use
ToStringLookup will optimize memory heap that using with converting integer.

11. Don't sort collections already sorted.
Check collection already sorted or not before sort it.

12. Global variables.
Use global variables when you using same type of object frequently

13. Constant and static
Constants are not assignable memories but they are easy to load.

Static is more faster than instant creations. When load statics no need of run time to check the instance



Hope this is helps...



Monday, August 4, 2014

Test Your OOP and C# Knoledge Free


Visit      bit.ly/oopcsharp

Thursday, July 10, 2014

Multiple inheritance in C#

When we are talking about Object Oriented Programming concepts inheritance is most important concept. C# is that language derived from powerful lanuage C++. But some of the features in C++ such like Multiple inheritance is not allowed with C#.

Instead of multiple inheritance with Classes C# provide multiple inheritance with interfaces. If you have scenario that multiple inheritance need to play role you can go with interfaces with one base class. 

An interface contains only the signatures of methods, properties, events or indexers. A class or Struct that implements the interface must implement the members of the interface that are specified in the interface definition.

You can inherit any number of interfaces but only one base class


public interface demoInterface
   {
       public string interfaceProperty { get; set; }
       public void interfaceMethod();
   }
   public class DemoClass1
   {
       public int demoClassProp1 { get; set; }
   }
   public class DemoMultipleInheritClass:DemoClass1,demoInterface
   {
       private string Property;
       public string interfaceProperty  // read-write instance property
       {
           get
           {
               return Property;
           }
           set
           {
               Property = value;
           }
       }
       public void interfaceMethod()
       {
           int variable1 = this.demoClassProp1;  
       }
   }



Wednesday, July 9, 2014

OOP Concepts in C# and C++

With this post I'm gonna have brief cover on the some important Object Oriented Concepts with the help of C# and C++ coding.

Inheritance
 If the object or a Class( take it as A) that based on another class( take it as B) we called A inherits B or A is a child of B. It allows to use permitted properties and methods of parent without implementing them inside the children  with in children.

C++
class A
{
    public int Num;
};
//Child Class
class B : A
{
    public string name;
};
class C
{
  public string email;
};
//Multiple inheritance
class D : A,C
{
    
};

C#
class A
    {
        public int Num { get; set; }
    }
    class B:A
    {
        public string name { get; set; }
    }
 Unfortunately C# doesn't support for multiple inheritance. To archive multiple inheritance functionality there there is way with interfaces. Hoping to add some separate article about interfaces.

Magical Static
 Static is one of important keyword that programmers using rapidly. static has two meanings with the usage of it.

if static keyword is using with variable in the code that means there is only one instance of that variable through out the execution time.

if static keyword is using with method it means that method can be used without create any instance of class or outside the class.

static members are not bounded with the class.

C++
class demo
{
    public:
        static int staticVariable;
        static int StaticFuntion();
};
//set the value for static variable
int demo::staticVariable = 10;
int demo::StaticFuntion()
{
    return 3;
};
int main()
{
    cout<<demo::staticVariable<<"\n";
    cout<<demo::StaticFuntion();
}

C#

public class Demo
   {
       public static int staicNumber { get; set; }
       public static int staticMethod()
       {
           return 3;
       }
   }
   class Demo2
   {
       public void funtion()
       {
           MessageDialog ms = new MessageDialog(Demo.staticMethod().ToString());
           ms.ShowAsync();
           MessageDialog ms2 = new MessageDialog(Demo.staicNumber.ToString());
           ms2.ShowAsync();
       }
   }

Access Modifiers and Key Words

Access modifiers defines the accessibility level of Class, Property or Method .
There are three basic access modifiers
  • Public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
  • Private
The type or member can be accessed only by code in the same class or structure.
  • Protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
C++
class demo
{
    public:
         int staticVariable;
         int StaticFuntion();
    private:
         int staticVariable1;
         int StaticFuntion1();
    protected:
         int staticVariable2;
         int StaticFuntion3();
};

But with C# there is an additional access modifier called internal  this type or member can be accessed by any code in the same solution/namespace, but not from another solution/namespace.

and C# allows to use internal protected type also.

Those access modifiers are applicable for classes also

 C#
public class Demo
   {
       public int MyProperty { get; set; }
       private int MyProperty1 { get; set; }
       protected int MyProperty2 { get; set; }
       internal int MyProperty3 { get; set; }
 
       internal protected int MyProperty4 { get; set; }
   }

 Abstract, Sealed and Partial  are another useful keywords that can be using with Class and Methods  in OOP in C#.

Abstract modifier indicates that the thing being modified has a missing or incomplete implementation.It indicates that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.

C#
public class Demo
    {
        abstract public int addition();
    }
 
    public class Demo2:Demo
    {
        public override int addition()
        {
            return 10;
        }
    }

Sealed modifier prevents other classes from inheriting from it. It seals  the class.



















Partial modifier can be used only with Classes and  Methods. It makes available to split code among few classes or code pages.

C#
public partial class Sample
    {
        public void Method1()
        {
        }
    }
 
    public partial class Sample
    {
        public void Method2()
        {
        }
    }
 
    public sealed class Demo2 : Demo
    {
        private void GiveExample()
        {
            Sample Object = new Sample();
            Object.Method1();
            Object.Method2();
        }
    }


Polymorphism (Overloading and Overriding)
 Polymorphism is a Greek word that means "many-shaped". There is two types of Polymorphism. that is
  1. Overloading.
  2. Overriding.
Overloading
 Overloading is when you have multiple methods in the same scope, with the same name but different signatures.

C++
class Demo
{
   public:
      void Function(int i) {
         
      }
 
      void Function(string name) {
         
      }
};


C#
//Overloading
public class Demo
{
    public void Function(int id)
    {}
    public void Function(string name)
    {}
}

 Operator Overloading
 This feature is not available with Java. It allows you to change the functionality of operators with our custom arguments. But at the end it should do the similar kind of function that did previously

Scenario :  Assume that we having class called liquor , and we have two instances of that Class called liquor1 and liquor2. this liquor1+liquor2 should will return total addition of all properties that liquor Class got. In here we need to overload the Operator +


Here is the Operators that can be overload
 + - * / % | & ~ !    = < > += -= *= /= %= |=  &= << >> <<= >>= == != <= >= && || ++ -- , -> *-> [ ] ( ) new delete

C++
class liquor
{
    public :
        int capacity;
        string name;
       liquor operator+(liquor l1);
};
 
liquor liquor:: operator+(liquor l1)
 {
    liquor ans;
    ans.capacity= l1.capacity + capacity;
    ans.name= (l1.name + " " + name);
    return ans;
 }
 
void Main()
{
    liquor liquor1;
    liquor1.capacity = 10;
    liquor1.name="Vodka";
 
    liquor liquor2;
    liquor2.capacity = 20;
    liquor2.name = "Vine";
 
 
    liquor liquor3 = liquor1 + liquor2;
}

 

 C#
public class liquor
    {
        public int capacity { get; set; }
        public string name { get; set; }
 
        //overload the + Operator
        public static liquor operator +(liquor l1, liquor l2)
        {
            liquor ans = new liquor(){capacity= l1.capacity + l2.capacity,name= (l1.name + " " + l2.name)};
            return ans;
        }
    }
 
    public class addition
    {
        //usage function
        public void returnAdition()
        {
            liquor liquor1 = new liquor() { capacity=10, name="Vodka" };
 
            liquor liquor2 = new liquor() { capacity = 20, name = "Vine" };
 
            liquor liquor3 = liquor1 + liquor2;
        }
    }


 Overriding is a principle that allows you to change the functionality of a method in a child class.

C++
class A
{
    public:
       virtual void fn(){cout<<10;}; //pure virtual member function
};
 
class B:A
{
    public:
        void fn()override{cout<<40;}//Overridden
};
 OR
class A
{
    public:
        void fn(){cout<<10;}; //pure virtual member function
};
 
class B:A
{
    public:
        void fn(){cout<<40;}//Overridden
};
 

 C#
public class Demo
    {
        public virtual void Method2()
        {
            //Print functionality implemented
        }
    }
 
 
    public  class Demo2 : Demo
    {
        public override void Method2()
        {
            //Print functionality implemented with some operation
        }
    }
 The virtual  keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.