Thursday, June 2, 2016

OOP Concepts

Encapsulation is the process of keeping one or more items within a single package. it prevents access to implementation details. access specifiers are public, private, protected, internal etc.

E.g.
public can be accessed any code.

private can only be accessed by code in the same class or struct.

protected can only be accessed by code in the same class or struct, or in a derived class.

internal can be accessed by any code in the same assembly only.

protected internal can be accessed by any code in the same assembly, or by any derived class in another assembly.

Abstraction is the process of providing only essential information to the outside real world and hiding overall background details to present an object. It relies on the separation of interface and implementation.to hide irrelevant details 
For example, we continue with “Bike” as an example, we have no access to the piston directly, we can usestart button to run the piston. Just imagine if a bike manufacturer allows direct access to piston, it would be very difficult to control actions on the piston. That’s the reason why a bike provider separates its internal implementation from its external interface.

private string GetEngineMakeFormula(){ return formula;}

public string DisplayMakeFormula() { //"GetEngineMakeFormula()" is private but accessible and limited to this class only
return GetEngineMakeFormula();}

Polymorphism means having many forms. Generally, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. (Overloading)
Vehicle airplane = new Airplane();
A Bike can be into two forms like cell start or kick start. We can later on decide which form or method we will use to start bike to go for drive

Inherritance

Initialize Child will Run Parent Constructor 1st only Child Constructor.
Child can Run Parent Method.
Can initialize Parent Object.
Override only for virtual or abstract method.

Constructor no return value, can overloaded

Destructor use for manual cleanup to destroy the objects that we no longer want to use.
~Bike(){ //Destructor }

OOP Deisgn Principle (SOLID)

5 principles to design a class SOLID:

SRP (Single Responsibility Principle)

  • 1 Class only 1 responsibility.
  • A class should have one, and only one, reason to change.
  • E.g. Student Class only for Student, teacher Class only for Teacher.
  • e.g. We not write function in every catch there, we will write a Common Log Class and Method, and use all the class. so in future, we just change the common log method. Not 1 by 1.

OCP (Open Closed Principle)

  • be open for extension, but closed for modification.
  • E.g. different shape has different calculate area method, we cannot use if…else to calculate this, in future, it might have new shape.
  • Shape > Abstract class, calculate area > abstract method.
  • Rectangle inherit Shape and override calculate method.

http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/

LSP (Liskov Substitution Principle)

  • Derived classes must be substitutable for their base classes.
  • object of a derived class should be able to replace an object of the base class without bringing any errors in the system or modifying the behavior of the base class.
  • New derived classes are extending the base classes without changing their behavior.
  • Not implement method in sub class (so you can loop with Parent class and call Parent Method)
  • Sub class function overrides the base class method to give it new meaning.

http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/06/30/simplifying-the-liskov-substitution-principle-of-solid-in-c.aspx

ISP (Interface Segregation Principle)

  • No client should be forced to depend on methods it does not use.
  • Client only want printer function print ONLY, not scan and photocopy.
  • So you can use interface control how many interface you want.

http://www.codeproject.com/Tips/766045/Interface-Segregation-Principle-ISP-of-SOLID-in-Cs

DIP (Dependency Inversion Principle)
  • High-level modules should not depend on low-level modules. They should both depend on abstractions.
  • Loose Coupling and Dependency Injection.
  • Depend on abstractions, not on concretions. 

OOP Design Pattern

Abstract Factory Pattern: Create instances of classes belonging to different families (abstract method, 1 products 2 style)
http://penyu91.blogspot.my/2016/08/abstract-factory-pattern.html

Builder Pattern: Separate representation and object construction.
http://penyu91.blogspot.my/2016/08/builder-design-pattern.html

Factory Method Pattern: Create instances of derived classes.
http://penyu91.blogspot.my/2016/08/factory-pattern.html

Prototype Pattern: Clone or copy initialized instances.
http://penyu91.blogspot.my/2016/08/prototype-pattern.html

Singleton Pattern: Class with only one single possible instance.
http://penyu91.blogspot.my/2016/03/singleton-pattern.html

Dependency Injection

  • If no Dependency Injection, customer point to DatabaseHelper now, future have XMLDatabase, you would change lot of code.
  • Dependency Injection is good; it makes the classes loose couple.
  • It achieves Dependency Inversion Principle. (High-level modules should not depend on low-level modules. Both should depend on abstractions.) [Customer is High Level, DatabaseHelper is low level, IStorage is High Level]
  • Is to pass the variable into Constructor, Default Constructor is to initialize the concrete class.
static void Main(string[] args)
{
       var customera = new Customer(new DatabaseHelper());
       customera.CustStore();

       var customerb = new Customer(new XMLHelper());
       customerb.CustStore();

       Console.ReadLine();
}

public class Customer
{
    private IStorageHelper _iStorageHelper;

    public Customer(IStorageHelper iStorageHelper)
    {
        _iStorageHelper = iStorageHelper;
    }

    public void CustStore()
    {
        _iStorageHelper.Store();
    }
}

public interface IStorageHelper
{
    void Store();
}

public class DatabaseHelper : IStorageHelper
{
    public void Store()
    {
        Console.WriteLine("DB Store");
    }
}

public class XMLHelper : IStorageHelper
{
    public void Store()
    {
        Console.WriteLine("XML Store");
    }
}

Wednesday, June 1, 2016

High Conhension(亲密度), Loose Coupling (联结)

Effect on how flexible and maintainable your software

High cohesion increases the probability that a component can be reused in more places.

  • stuck together well , clear , closely, easy understand. e.g. DAC all related to Database.
  • e.g. Low Conhension -  EmalMessage has Login

Loose coupling allows components to be used independently from other components.  e.g IPOD

  • Tight Coupling, 2 classes are tight together (Class A instantiate object Class B), e.g. motherboard need to depend RAM, Processor.
  • Tight coupling increases the maintenance cost as it is difficult and changes to one component would affect all other components that are connected to it.
  • Solution, add interface in between,
  • Lego (loose coupling) , Puzzle (high Coupling)

So, next time you are writing a class, think to yourself: Am I writing a Lego or am I writing a puzzle piece?

Monday, May 23, 2016

Interface C#

Interface 

    interface IBankCustomer
    {
        void DepositMoney();
        void WithdrawMoney();
    }

    public class Demo : IBankCustomer
    {
        public void DepositMoney()
        {
            Console.WriteLine("Deposit Money");
        }

        public void WithdrawMoney()
        {
            Console.WriteLine("Withdraw Money");
        }

        public static void Main()
        {
            Demo DemoObject = new Demo();
            DemoObject.DepositMoney();
            DemoObject.WithdrawMoney();
        }
    }

  • Interface No need access modifiers, default is public.
  • Interface methods only header, no body.
  • Interface No Field.
  • Interface No Constructor.
  • Interface can inherit other interface.
  • Child Class must implement all the Interface method.
  • Child Class can inherit mutiple Interface.

Different Interface and abstract Class

1.A class cannot inherit more than one class (class DerivedClass : BaseClass1, BaseClass2),
interface can (public class Demo : Interface1, Interface2)

2. Abstract class can have abstract or non abstract method;

Thursday, May 5, 2016

EXEC Query

DECLARE @EndDate VARCHAR(10);
DECLARE @SQL VARCHAR(5000);
DECLARE @LastDate VARCHAR(10);
DECLARE @StartDate VARCHAR(10);
DECLARE @StartYear VARCHAR(4);
DECLARE @StartMonth VARCHAR(2);

SET @StartDate = CONVERT(VARCHAR(20),DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) -1, 0),23);
SET @EndDate = CONVERT(VARCHAR(20),DATEADD(MONTH,1,@StartDate),23);
SET @LastDate = CONVERT(VARCHAR(20),DATEADD(Day,-1,@EndDate),23);
SET @StartYear = CONVERT(VARCHAR(4),datepart(yyyy,@StartDate));

SET @StartMonth = CONVERT(VARCHAR(2),datepart(mm,@StartDate));

Set @SQL = 'Select *,date as ''Trans Date'' From DBYear'+ @StartYear  +'.dbo.Table WHERE TransDate BETWEEN '''+ @StartDate + ''' AND '''+ @EndDate + '''; 
exec(@SQL)
select(@SQL)