Pranay Rana: May 2018

Tuesday, May 22, 2018

Factory Design Pattern With Generics

Factory Method design pattern is one of the highly used design pattern, which is used in project to centralize creation of similar family object in application. It's part of creation design patterns as it helps to create objects in application.



Why to Centralize Object creation with Facotry?

  1. To avoid object creation every where in application with New. 
  2. To create object at run-time which serves purpose, based on requirement (i.e. based on input parameters). 
Factory Pattern Implementation

Below is class diagram and code implementation of Factory pattern.

Below code, centralize creation of command objects with help of Factory design pattern. Code below works as below

  • Code below creates different command to perform task such as addemployee, editemployee etc.
  • It's scalable as if developer wants to add new command let's say deleteemployee then it require to create new DeleteEmployee command which inherits from ICommand as other commands do.
  • CommandFactory , its factory pattern base class which has method GetCommand to return requested command based on input string argument. Modification required in GetCommand method when new command need to be added in application.
  • Program is client class which make use of CommandFactory and execute returned command.

    class Program
    {
        static void Main(string[] args)
        {
            ICommand cmd = CommandFactory.GetCommand("AddEmployee");
            Console.WriteLine(cmd.GetType());
            Console.ReadLine();
        }
    }

    public class CommandFactory
    {
        public static ICommand GetCommand(string cmdName)
        {
            if(cmdName=="AddEmployee") 
            {
                return new AddEmployee();
            } 
     else if(cmdName=="EditEmployee") 
            {
                return new EdutEmployee();
            }

            return new NullCommand();
        }
    }

    public class NullCommand : ICommand
    {
        public bool CanExecute()
        {
             Console.WriteLine("Null command");
    return true;
        }

        public void Execute()
        {
           Console.WriteLine("Null command");
        }
    }

    public class AddEmployee : ICommand
    {
        public bool CanExecute()
        {
            //validation
   return true;
        }

        public void Execute()
        {
          //code to execute
        }
    }
 
    public class EditEmployee : ICommand
    {
        public bool CanExecute()
        {
            //validation
             return true;
        }

        public void Execute()
        {
          //code to execute
        }
    }

    public interface ICommand
    {
        bool CanExecute();
        void Execute();
    } 

Following are issues with above code
  1. One big issue with above code is , it's violate Open Close principle. Because whenever new command added in application, developer need to go to Command Factory and need to add if condition for creating it.
    For Example: when there is need of adding Delete command , developer need to open CommandFactory class and need to add if clause for that.
  2. CommandFactory, GetCommand takes string argument to create and return instance of command. If developer pass wrong string argument value it will end up with NullCommand object (which is based on Null object pattern).
    So its not type safe implementation.
  3. CommandFactory, GetCommand can only return ICommand. If developer added new property/method let's say xyz which is specific to command ex. AddEmployee, then developer cannot access it like addCommandObj.xyz as return Command is of type ICommand and it doesnt has that property. 
Generics Based Factory Pattern Implementation

Solution to problem listed above is make use of factory pattern using Generics. Below is diagram and code of implementation


    class Program
    {
        static void Main(string[] args)
        {
            ICommand cmd = CommandFactory.GetCommand<AddEmployee>();
            Console.WriteLine(cmd.GetType());
            AddEmployee addEmployeeCmd = CommandFactory.GetCommand<AddEmployee>();
            Console.WriteLine(addEmployeeCmd.NewEmployeeId);
            Console.ReadLine();
        }
    }

    public class CommandFactory
    {       
        //only create object of type which implement ICommand
        public static T GetCommand<T>() where T:  ICommand
        {
          //it create object using Template type T and by making use of reflection
          //once create factory this way there is no need to open it again for modification
            Type type = typeof(T);
            Object obj = Activator.CreateInstance(type);
            return (T)obj;
        }
    }

    public class EditCommand : ICommand
    {
        public bool CanExecute()
        {
            //validation
            return true;
        }

        public void Execute()
        {
            //code to execute 
        }
    }

    public class AddEmployee : ICommand
    {
        private int newEmployeeId;
        public int NewEmployeeId
        {
            get { return newEmployeeId; }
        }

        public bool CanExecute()
        {
            return true;
        }

        public void Execute()
        {
            //execute code to create employee
            this.newEmployeeId = 1;//created employeeid 
        }
    }

    public interface ICommand
    {
        bool CanExecute();
        void Execute();
    } 

Following are advantages (solutions for previous approach problem) of generics based implementation

  1. It doesn't violate open close principle as object get created using reflection and using Generics Template type T in CommandFacoty class - GetCommand method. Check CommandFacotry Class in above code.
  2. By making use of Generics, it makes CommandFactory strongly type and there is no need string as argument based on which GetCommand method creating object in previous implementation.
     public static T GetCommand<T>() where T:  ICommand 
    if you see signature of GetCommand now,  it force Template type T must implement ICommand interface and so that it only going to create object of types which implement ICommand.
  3. Now factory can return object of specific implemented type like AddEmployee
      AddEmployee addEmployeeCmd = CommandFactory.GetCommand<AddEmployee>();
    
    Above line of code in Program class Main method proves point that now factory can return implemented type that can also be convert to to parent type ICommand.
Wrapping up
Factory pattern is one of the highly used deign pattern which used in most of the application to create and centralize object creation. So when it written not strongly type based way can lead to problem. So it's better to implement it strongly type based way (Generics implementation) to avoid issues and it helps to stick your code with SOLID principle.


Sunday, May 13, 2018

Angular Application Structure

Setting up application structure of application is one of the most important part of application development. Because well structured application allows to scale/grow application with less efforts, saves lot of effort in maintenance of application, allows to locate files and resources easily.

No framework forces to follow how to structure application (how to arrange files in different parts of application) , same goes for Angular 2 framework. It doesn't force developer to structure application, like how to arrange components, directives, pipes, services etc. created by developer. But angular team propose guideline one must follow for structuring application in style guide here : StyleGuide

Application Structure

Below diagram is visual presentation of structure of Angular application, which is as per the guide lines from angular team.




Application Module - It's Start point of angular application. This is first module get called when application get loaded. This module automatically get created when application created with the help of Angular-cli.
Point to note , all feature modules and core module is going to register themselves in this module.

Core Module - In angular application, It's module going to have application level singleton services (Ex. HttpInterceptor used for intercepting http request, LoggerService,  LoggedInUserService) or application level component (Ex. Navigation Bar).

Core Module have all singleton services,  so only the root AppModule  (Application Module) should import the CoreModule to make same instance of service in all modules of application. If a lazy-loaded module imports it too, lazy module will create its own instance of core module services and use that newly created instance of services instead of application level singleton services.  To avoid that problem make use of forRoot method and guard clause, code for that given below. https://angular.io/guide/singleton-services

@NgModule({
  imports: [CommonModule]
  declarations: [XyzComponent],//needed if there component
  exports: [XyzComponent]//needed if want to export component
})
export class CoreModule {

  constructor (@Optional() @SkipSelf() parentModule: CoreModule) {
    if (parentModule) {
      throw new Error(
        'CoreModule is already loaded. Import it in the AppModule only');
    }
  }
 
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: CoreModule,
      providers: [
        LoggerService ,UserService
      ]
    };
  }
}

Shared Module - In angular application, It's module going to have all dump angular Pipes, Directives , Components, Function  etc. i.e. all who are dumb and receive input from, component which uses it.  Ex. Extended Form Validation Component (Check Here), Confirmation Model Popup, Formatting Pipes,  Validation &  Common functions used through out application, Directive used by controls etc its like utilities used in application .
Point to note, It should not going to have angular services.

Feature Modules - In angular application, Feature modules are going to have have features which is going to be provided by application.   (Ex. CustomerModule, OrdersModule, ProductsModule, ShippingModule).
This features modules also going to have shared features modules in which is going to be shared between this features module only. For Example. ProductDataService module which is going to be shared between ProductModule and OrderModule.

Module Dependency ( Flow of Services ) 

Below diagram shows dependency between modules (i.e. it shows the flow of services) discussed above.



Hows modules dependent or Service flow

Feature Modules - these modules are going to consume singleton services form Core Module (Via application module in which it registered) and shared dumb pipes, component, directives, functions from shared module.
Which means Feature modules depends on Core Module and Shared module i.e. service flow from core & shared modules to feature modules.
Important point to note here is, Service flows from top towards bottom, not from bottom to top. This means top level Core module, Application module and shared module must not consume service from feature modules.

Core Module - this module going to consume service from shared module if needed. Mostly it's doesn't need service from shared module but sometime need to access common function or formatting pipes for its component , that's why diagram has dotted line.
So service flows from shared module to core module if needed, otherwise this is independent module which provides application level singleton services and component. 

Application Module - this module is simple module just going to to have one component  to provide start point of application. It's going to consume services from Core Module and if needed consume services from shared module.

Shared Module - It's utility module. This module have all the dumb angular components, pipes , directives  and utility functions. So this module provides its services to all the modules (Application Module, Core Module, Feature Modules) in applications.
But its not going to consume service from other modules.

Conclusion
Angular framework doesn't force developer to follow discussed structure for developing application. But it's must need when application going to grow & developer wants to scale it up, and also helps in identifying different part of application in turns helps in maintaining application.

Putting component, service, pipe, directives in proper folder structure its not end of story. To make property structure developer must need to setup dependency properly between module i.e. flow of service as discussed.

Note
Above article is based on my reading on angular.io portal and structure applied in my application. Please comment if something wrong.