OOPs Design Patterns and Dependency Injection–Draft


Background

The intention of this article is to collect the important design principle across multiple web sites as quick refresh guide.

OOPS

Class

  • A class is a blueprint for creating an object.
  • While analysing the requirements, a noun is an object. An adjective is an attribute (or a property). A verb is a method (or a function).

Fundamental principles of OOP:

  • Encapsulation
    • The combining together of attributes (data) and methods (behaviour/processes) into a single abstract data type with a public interface and a private implementation. This allows the implementation to be altered without affecting the interface.
    • Use : Consumer needs not to know the implementation in order to use it.
  • Abstraction
    • Abstraction means working with something we know how to use without knowing how it works internally.
    • to deal with objects considering their important characteristics and ignore all other details.
    • How to Achieve A design in which the names of classes, methods, and other elements convey both the original developer’s purpose in creating them and their value to a client developer. If a developer must consider the implementation of a component in order to use it, the value of encapsulation is lost.
  • Inheritance
    • The derivation of one class from another so that the attributes and methods of one class are part of the definition of another class. The first class is often referred to the base or parent class.
  • Polymorphism
    • Polymorphic methods are used which have one name but different implementations for different classes.
    • We will explain how to work in the same manner with different objects, which define a specific implementation of some abstract behavior.
    • Polymorphism Types
      • 1. Method overloading – Static Polymorphism / Static Binding / Early binding /.(in same class) – is the polymorphism exhibited at compile time.
      • 2. Method overriding – Dynamic Polymorphism / Dynamic binding / Runtime binding/.(in different classes.) – is the polymorphism exhibited at run time.
      • Some OOP theorists also put the concept of exception handling as additional fifth fundamental principle of OOP.


Design

High-level_design (HLD) is the overall system design – covering the system architecture and database design. It describes the relation between various modules and functions of the system. data flow, flow charts and data structures are covered under HLD. Examples use cases, state diagrams, activity diagrams, logical data model

Low Level Design (LLD) is like detailing the HLD. It defines the actual logic for each and every component of the system. Class diagrams with all the methods and relation between classes come under LLD. Programs specs are covered under LLD. Examples class diagrams, sequence diagrams, physical data models

Important Design principles

  1. SOLID
  2. “Good enough” principle
  3. Don’t repeat yourself (DRY)
  4. Keep it Simple and Sweet / Stupid. ( KISS)
  5. YAGNI (You aren’t going to need it. So don’t implement it).
  6. Hollywood Principle. ( Don’t call use, we will call you )

  1. Least Knowledge Principle. (Only talk to your immediate friends. Classes that they inherit from, objects that they contain, objects passed by argument)
  2. Depend on Abstractions, Not Concrete classes.
  3. Program to Interface Not Implementation.
  4. Minimize Coupling
  5. Maximize Cohesion

KISS

KISS is an acronym for “Keep it simple, stupid” as a design principle noted by the U.S. Navy in 1960.[1][2] The KISS principle states that most systems work best if they are kept simple rather than made complicated; therefore simplicity should be a key goal in design and unnecessary complexity should be avoided.

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” -Brian Kernighan

“Good enough” principle

The principle of good enough or “good enough” principle is a rule for software and systems design. It indicates that consumers will use products that are good enough for their requirements, despite the availability of more advanced technology.[1]

Don’t repeat yourself

“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.”

They apply it quite broadly to include “database schemas, test plans, the build system, even documentation.”[1] When the DRY principle is applied successfully, a modification of any single element of a system does not require a change in other logically unrelated elements.

YAGNI

You aren’t gonna need it[1][2] (acronym: YAGNI)[3] is a principle of extreme programming (XP) that states a programmer should not add functionality until deemed necessary.[4]

“Decide as late as possible: Delaying decisions as much as possible until they can be made based on facts and not on uncertain assumptions and predictions.

“Always implement things when you actually need them, never when you just foresee that you need them.” – Ron Jeffries


SOLID

http://zeroturnaround.com/rebellabs/object-oriented-design-principles-and-the-5-ways-of-creating-solid-applications/

The Single Responsibility Principle (SRP)

· An entity (an object, a class) should have only a single responsibility

· A responsibility is in fact a reason to change

· A class should have one, and only one, reason to change.

This means that every class, or similar structure, in your code should have only one job to do.

Example: Clear separation between Customer and Savings Account. A customer may have multiple accounts.

The Open Closed Principle (OCP)

Classes should be Open for extension, closed for modification

You should be able to extend a class, without modifying it. 

Abstractions through inheritance – changed behaviour through polymorphism Open for extension: behaviour of classes can be extended to satisfy changing requirements

Closed for modification: classes themselves are not allowed to change

once you have developed a class you should never modify it, except to correct bugs.

If you need a modified behaviour of a class just change that class. This is however wrong

The answer here is abstraction. In OO it is possible to create abstractions with fixed design but limitless behaviours

Example Web API. In case of changes required in the interface new version of interface will be created, instead of changing existing

The Liskov Substitution Principle (LSP) / Design by contract / Preconditions, Postconditions & Invariants

Definition

If for each object o1 of type S there is an object o2 of type T such that for

all programs P defined in terms of T, the behaviour of P is unchanged

when o1 is substituted for o2 then S is a subtype of T.

· Rule: It is allowed to weaken preconditions and strengthen postconditions in overridden methods, but not vice versa

· If you can not satisfy this rule then you need to refactor the class hierarchy. Typically, those two types should be in the same level of the hierarchy. There is a superclass for both of these classes

Anywhere you specify a base type, you should be able to use an instance of a derived type.

Derived classes must be substitutable for their base classes without the client knowing about the change

· Recollect inheritance should be reuse of interface

· Overriding is inheritance with reuse of implementation

· Very often you will need to refactor the class hierarchy

Example DBConnection is substituatable with SQLconnection or Oracleconnection

Joint account can be derived from Saving account which will have extra parameters for the multiple accounts.

The Interface Segregation Principle (ISP)

Make fine grained interfaces that are client specific.

ISP guides us to create multiple, smaller, cohesive interfaces.

Example

  1. Separate interfaces has to be created for the Savings Account and OD Account
  2. There will be a common interface for Account. Separate interfaces for Savings account (interest calculation) and OverDraft Account (Mortages)

The Dependency Inversion Principle (DIP)

Depend on abstractions, not on concretions.

high-level modules should not depend upon low-level modules; they should depend on abstractions.

abstractions should not depend upon details; details should depend upon abstractions.

Example.

Let’s say,  once credit score reaches certain limit, OD account is provided.

The implementation can’t happen on the CreditScore class directly.

The CreditScore might have used for LoanAgainstGold as well.

Create a separate ICreditScore interface as parent of CreditScore class. ODAccount can depend up on the ICreditScore.

Further Adapter pattern could be used to convert the event to the necessary format for the ODAccount.


Design Patterns

A design pattern in Software is used to solve similar problems that occur in different scenarios.

What is design patterns ? Have you used any design pattern in your code ?

Design patterns are tried and tested way to solve particular design issues by various programmers in the world. Design patterns are extension of code reuse.

Read more: http://javarevisited.blogspot.com/2012/06/20-design-pattern-and-software-design.html#ixzz52HXCxjjh

Most used patterns

http://www.dofactory.com/topic/1035/most-frequently-used-design-patterns.aspx

https://www.quora.com/Which-are-top-5-common-mostly-used-design-patterns-for-C

http://www.developerfusion.com/article/8307/aspnet-patterns-every-developer-should-know/

The following list shows some of the most common design patterns within these groups:

  • · Presentation Pattern
    • · Model-View-Controller (MVC)
    • MVVM – Angular – Dual binding
    • Page Controller Pattern – Web forms
    • · Use Case Controller
    • · Model-View-Presenter (MVP)
  • · Persistence Pattern
      • · Repository
      • Unit of Work
    • · Creational
      • · Factory
      • Prototype – Serialization
      • Builder – Separate representation and object construction- UWP, WPF and WinForm
      • Injection
      • · Singleton -The Timer class in UWP, WPF, and WinForms all utilize this.
    • Structural
      • · Service Agent / Proxy / Broker
      • · Provider
      • Adapter- You can look at many of the built in classes that have interfaces
        that are matched with different interfaces.
    • · Host or Behavioral
      • · Command
      • · Publish-Subscribe / Observer- .NET Event
      • · Plug-in / Module / Intercepting Filter – MVC filtering
      • Strategy Pattern – List, Array, Dictionary, Char all have a sort method and that sort method chooses the best algorithm for sorting based on the data. Encapsulate algorithms within a class and make them interchangeable

    Personally, my answer would go something like this:

    1. Layers (n-Tier architecture – all my projects are layered)
    2. Facade (Service Layer)
    3. Iterator (LINQ really)
    4. Active Record (we use this as our business object and data access
      pattern)
    5. Singleton (every app has use for several singletons)
    6. Proxy WCF
    7. Factory (great useful pattern for creating families of objects)
    8. Adapter

    Presentation Patterns

    1. MVC Vs MVP – They separate the dependencies between a Model (think Domain objects), your screen/web page (the View), and how your UI is supposed to behave (Presenter/Controller)
    2. In MVC,controller has one to many relationship with View(s). in MVP view has one to one relationship with a controller
    3. In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching.
    4. In MVC,
      • Controller are based on behaviors and can be shared across views
      • Can be responsible for determining which view to display
    5. MVC vs MVVM For ASP.Net, MVVM is used to two-way bind data within views
      1. MVVM. Don’t be fooled by the letters, by the omission of the C. Controllers are still there.
      2. We just add one thing: statefulness, data cached on the client (and along with it intelligence to handle that data). That data, essentially a cache on the client, now gets called »ViewModel«. It’s what allows rich interactivity. And that’s it.
        1. MVC = model, controller, view = essentially one-way communication = poor interactivity
        2. MVVM = model, controller, cache, view = two-way communication = rich interactivity
      3. Views display a certain shape of data. They have no idea where the data comes from.
      4. ViewModels hold a certain shape of data and commands, they do not know where the data, or code, comes from or how it is displayed (what view is displaying it).
        The VM then becomes a dumb container that requires little, if any, testing.

      5. Models hold the actual data (various context, store or other methods)
      6. Controllers listen for, and publish, events. Controllers provide the logic that controls what data is seen and where. Controllers provide the command code to the ViewModel so that the ViewModel is actually reusable.

    image

    image

    The Repository Pattern

    The Repository pattern virtualizes storage of entities in a persistent medium, such as a database or as XML. . It effectively hides the storage implementation from the application code, and allows the use of a common set of methods in the application without requiring knowledge of the storage mechanism or format.

    The Repository Pattern has gained quite a bit of popularity since it was first introduced as a part of Domain-Driven Design in 2004. Essentially, it provides an abstraction of data, so that your application can work with a simple abstraction that has an interface approximating that of a collection. Adding, removing, updating, and selecting items from this collection is done through a series of straightforward methods, without the need to deal with database concerns like connections, commands, cursors, or readers. Using this pattern can help achieve loose coupling and can keep domain objects persistence ignorant.

    wps5E41.tmp

    Specification
    Repositories that follow the advice of not exposing IQueryable can often become bloated with many custom query methods. The solution to this is to separate queries into their own types, using the Specification Design Pattern. The Specification can include the expression used to filter the query, any parameters associated with this expression, as well as how much data the query should return (i.e. “.Include()” in EF/EF Core). Combining the Repository and Specification patterns can be a great way to ensure you follow the Single Responsibility Principle in your data access code. See an example of how to implement a generic repository along with a generic specification in C#.

    • Repository Per Entity or Business Object

    • Generic Repository Interface

    Scenarios

    • The Builder is only needed when an object cannot be produced in one step.
    • The builder design pattern describes an object that knows how to craft another object of a specific type over several steps. It holds the needed state for the target item at each intermediate step.
    • Think what StringBuilder goes through to produce a final string.
    • Wizard
    • One great an example of this would be in the de-serialization process for a complex object. Often times the parameters for the complex object must be retrieved one by one.
    Singleton The Singleton Design Pattern is used to restrict the number of times a specific object can be created to a single time by providing access to a share instance of itself
    Factory pattern
    • If you are using large chunk of if/else or switch statement in your code to create instances of similar classes.
    • Every time when you introduce a new class, you will have to add more conditions to the statement.
    • Factory pattern provides a simple interface for external codes to acquire an instance of a class. It makes code much easier to maintain and test.
    Observer pattern
    • The main class which will notify its listener class (Observer) upon its changes of state is called Observerable class.
    • A change of state can be from a simple property update to business logic.
    • Observerable class does not care about what its Observers do; it does not even know their existence.
    • This way, two objects are loosely coupled. It became very easy to add additional functions without alerting main code.
    Builder pattern


    Gang of Four (GoF) patterns

    https://msdn.microsoft.com/en-us/magazine/cc188707.aspx

    http://dotnetacademy.blogspot.in/2011/10/design-patterns-which-are-used-in-net.html#sthash.LZaSea83.dpuf

    http://www.ehartwell.com/InfoDabble/Design_patterns_and_the_.NET_framework

    http://stackoverflow.com/questions/1316743/are-there-any-design-patterns-used-in-the-net-framework

    Creational Pattern

    • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
      • Factory Methods are usually called within Template Methods.
    • Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components get built.
    • Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
    • The Abstract Factory Pattern can be implemented using the Factory Method Pattern, Prototype Pattern or the Singleton Pattern.
      • Abstract Factory classes are often implemented with Factory Methods, but they can also be implemented using Prototype
      • The ConcreteFactory object can be implemented as a Singleton as only one instance of the ConcreteFactory object is needed.

    What is the difference between Factory and Abstract Factory Patterns?

    Factory vs Abstract Factory

    What is main benefit of using factory pattern ? Where do you use it?

    Factory pattern’s main benefit is increased level of encapsulation while creating objects. If you use Factory to create object you can later replace original implementation of Products or classes with more advanced and high performance implementation without any change on client layer.

    • The main difference between a “factory method” and an “abstract factory” is that the factory method is a single method, and an abstract factory is an object.
    • In Factory pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required.
    • Factory Method pattern is a simplified version of Abstract Factory pattern. Factory Method pattern is responsible of creating products that belong to one family, while Abstract Factory pattern deals with multiple families of products.

    Factory method takes care of one product where as the abstract factory Pattern provides a way to encapsulate a family of products.

    • In Factory pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.
    • Abstract Factory patterns acts a super-factory which creates other factories. This pattern is also called as Factory of factories. In Abstract Factory pattern an interface is responsible for creating a set of related objects, or dependent objects without specifying their concrete classes.

    image

    image

    Factory patterns

    Abstract patterns

    The objects are created through inheritance.

    The objects are created through composition.

    It is used in which the subclass is responsible for object instantiation.

    It is used to delegate object instantiation by a class to some object.

    This pattern creates products.

    This pattern creates factory.

    Each subclass knows what other classes to use or objects to create.

    Swapping FactoryMethod classes with object composition.

    Name

    Description

    .NET

    Creational patterns

    Abstract factory

    Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

    Any place where you need a run-time value to construct a particular dependency, Abstract Factory is the solution.

    Having Initialize methods on the interfaces smells of a Leaky Abstraction.

    the approach becomes very powerful when we want to dynamically create instances based on parameters. For example, creating instances at runtime based on User Inputs. This is also very centric to Dependency Injection (DI). Activator.CreateInstance is not centric to Abstract Factory Pattern. It just allows us to create instances in a convenient way based on the type parameter.

    Abstract Factory: System.Data.Common.DbProviderFactory. Every member function of this class is a factory method.

    http://stackoverflow.com/questions/1943576/is-there-a-pattern-for-initializing-objects-created-via-a-di-container/1945023#1945023

    Factory method

    Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

    This strategy for creating new object instances is known as a Factory pattern. Rather than invoking the object’s constructor, you can ask the object factory to create the instance for you. That way, the factory class can hide the complexity of object creation (like how to parse a Double out of a string). If you wanted to change the details of creating the object, you’d only have to change the factory itself; you would not have to change every single place in the code where the constructor is called.

    Factory Method:

    System.Data.IDbConnection.BeginTransaction(). The type of transaction created depends on the underlying IDbConnection implementation.

    WebRequest.Create() returns a concrete type that depends on the URL scheme

    System.Convert class contains a host of static methods that work like factory design pattern

    System.Net.WebRequest: This class is used to request and receive a response from a resource on the Internet.FTP, HTTP, and file system requests are supported by default. To create a request, call the Create method and pass in a URI. The Create method itself determines the appropriate protocol for the request and returns the appropriate subclass of WebRequest: HttpWebRequest, FtpWebRequest, or FileWebRequest. The caller doesn’t need to know the specifics of each protocol, only how to invoke the factory and work with the WebRequest that gets returned. If the URI changes from an HTTP address to an FTP address, the code won’t have to change at all.

    Builder

    Separate the construction of a complex object from its representation so that the same construction process can create different representations.

    Builder: The WCF channel construction infrastructure.

    Prototype

    Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

    Prototype – used in framework for cloning and serialization

    In .Net, cloning can be achieved my making use of the ICloneable of the system namespace. Using the clone method, we can create clones or copies of instances with the same value of the existing instance. Shallow copy is used here which simply creates a reference of the original. Deep copy can be used when a duplicate instance needs to be created. http://www.careerride.com/NET-Architecture-implement-prototype-pattern.aspx

    Singleton

    Ensure a class only has one instance, and provide a global point of access to it.

    Singleton – used as an activation method in WCF, i.e. a web service may be treated as a singleton by the WCF infrastructure. Ditto for .NET Remoting

    Singleton pattern is commonly used in print spoolers.

    – A class with static members needs to be created.

    – A private constructor to the class above should be defined.
    – A static method can be used to access the singleton object.

    Static Class vs Singleton

    1. Singletons can be handled polymorphically without forcing their users to assume that there is only one instance.
    2. First, a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members)
    3. A singleton instance (or rather, a reference to that instance) can be passed as a parameter to other methods, and treated as a normal object. A static class allows only static methods.
    4. A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues. So state management is not properly handled
    5. If there are bunch of functions should be kept together, then static is the choice. Anything else which needs single access to some resources, could be implemented singleton.
    6. What makes you say that either a singleton or a static method isn’t
      thread-safe? Usually both should be implemented to be thread-safe.

    Structural patterns

    Adapter

    The Provider and Adapter patterns allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the other. In more practical terms, these patterns provide separation between components that allows behavioral changes to occur without prior knowledge of requirements.

    The Adapter Design Pattern, also known as the Wrapper, allows two classes to work together that otherwise would have incompatible interfaces.

    Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

    image

    The ADO.NET providers, eg System.Data.SqlClient.SqlConnection, System.Data.OleDb.OleDbConnection etc. Each provider is an adapter for its specific database.

    DataAdapter; Encoding; TypeLibConverter; delegate

    By allowing managed classes and COM components to interact despite their interface differences, RCWs are an example of the Adapter pattern. The Adapter pattern lets you adapt one interface to another. COM doesn’t understand the System.String class, so the RCW adapts it to something that it can understand. Even though you can’t change how a legacy component works, you can still interact with it. Adapters are frequently used like this. 

    Bridge

    Decouple an abstraction from its implementation so that the two can vary independently.

    Composite

    Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

    Composite: many examples

    System.Windows.Forms.Control and its derived classes.

    System.Web.UI.Control and its derived classes.

    System.Xml.XmlNode and its derived classes.

    ASP.NET has lots of controls. A control may be a simple single item like a Literal, or it could be composed of a complex collection of child controls, like a DataGrid is. Regardless, calling the Render method on either of these controls should still perform the same intuitive function.

    Decorator

    Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

    System.Windows.Controls.Decorator (in WPF).

    wpsC706.tmp

    System.IO.Stream :Any useful executable program involves either reading input, writing output, or both. Regardless of the source of the data being read or written, it can be treated abstractly as a sequence of bytes. .NET uses the System.IO.Stream class to represent this abstraction. CryptoStream :System.Security.Cryptography.CryptoStream to encrypt and decrypt Streams on the fly, without the rest of the application needing to know anything more than the fact that it is a Stream. 

    Facade

    Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

    Facade: System.Xml.Serialization.XmlSerializer. XmlSerializer hides a complex task (that includes generating assemblies on the fly!) behind a very easy-to-use class.

    Flyweight

    Use sharing to support large numbers of fine-grained objects efficiently.

    Proxy

    Provide a surrogate or placeholder for another object to control access to it.

    Various patterns exist that remove dependencies between a client and a service by using intermediate brokers The aim of all these patterns is to allow remote connection to, and use of, a service without the client having to know how the service works.

    Proxy: The web service proxies generated by svcutil.exe and deriving from System.ServiceModel.ClientBase<TChannel>

    The service exposes a Contract that defines its interface, such as the Web Service Description Language (WSDL) document for a Web Service. A client-side proxy or gateway interface uses the Contract to create a suitably formatted request, and passes this to the service interface. The service sends the formatted response back through its gateway interface to the client proxy, which exposes it to the client. In effect, the client just calls the service methods on the client proxy, which returns the results just as if the service itself was a local component.

    wps2A6E.tmp

    Behavioral patterns

    Chain of responsibility

    Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

    System.Web.UI.Control.OnBubbleEvent() and System.Web.UI.Control.RaiseBubbleEvent()

    Command 

    Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

    encapsulates a operation call in an object thus making it transferable over a wire or persist-able

    System.Windows.Input.ICommand (in WPF)

    Implement the wizard using a command object. The command object is created when the wizard is first displayed. Each wizard page stores its GUI changes in the command object, so the object is populated as the user progresses. “Finish” simply triggers a call to execute(). This way, the command class will work.

    Interpreter

    Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

    Iterator

    Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

    foreach; IEnumerator; generic List<>

    System.Collections.IEnumerable,System.Collections.Generic.IEnumerable<T>. System.Data.IDataReader

    foreach statements make use of the iterator for the array behind the scenes. All you need to know is that you are guaranteed to have the loop run exactly once for each item in the array.

    To make those statements work, the object referenced in the In expression must implement IEnumerable.

    Mediator

    Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

    Memento

    Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.

    The .NET Serializable pattern is a variation on the Memento pattern

    Observer / EventListner

    Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

    • callback – notifies a single caller that some operation finished with some result
    • observer – notifies zero to n interested parties that some event (for example a finished operation) happened

    The .NET event mechanism

    delegates and events

    https://stackoverflow.com/questions/8951276/callback-command-vs-eventlistener-observer-pattern

    then Observer pattern is a natural choice for you.

    1. Use the callback pattern to trigger operations and notify the caller asynchronously that the triggered operation finished.
    2. Use the event/observer pattern to give some other components (that did not trigger the operation) the chance to be notified when an operation finishes

    Intercom

    Define a many-to-many as well as one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

    State

    Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

    Strategy

    The Strategy Design Pattern allows an object to have some or all of its behavior defined in terms of another object which follows a particular interface

    A particular instance of this interface is provided to the client when it is instantiated or invoked, providing the concrete behavior to be used. 

    Define a family of algorithms, encapsulate each one, and make them interchangeable.

    Strategy lets the algorithm vary independently from clients that use it.

    Sort method in ArrayList

    wpsC726.tmp

    Both Array and ArrayList provide the capability to sort the objects contained in the collection via the Sort method. Strategy Design Pattern is used with Array and Arraylist to sort them using different strategy without changing any client code using IComparable interface 

    One of the new generic collections in version 2.0 of the .NET Framework, List<T>, also makes heavy use of the Strategy pattern, shown in Figure . In addition to the updated Sort method, the find-related methods, BinarySearch, and others all take parameters that allow parts of the respective algorithms to vary based on the needs of the caller.

    The Strategy design pattern is used extensively to achieve the Single Responsibility Principle, the Explicit Dependencies Principle, and the Dependency Inversion Principle, and is a key to Dependency Injection and the use of Inversion of Control Containers.

    Template method

    Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

    Render method for custom controls. Regardless of which style of custom control you choose, you don’t have to write any code to handle the functionality that’s common to all controls, like loading and saving ViewState at the right time, allowing PostBack events to be handled, and making sure the control lifecycle events are raised in the correct order. The main algorithm for how a control should be loaded, rendered, and unloaded is contained in the control base class.

    Strategy is used to allow callers to vary an entire algorithm, like how to compare two objects, while Template Method is used to vary steps in an algorithm. Because of this, Strategy is more coarsely grained. There can be vast differences between different client implementations, while with Template Method the algorithm remains fundamentally the same.

    Strategy uses delegation while Template Method uses inheritance. In the sorting example of Strategy, the comparison algorithm is delegated to the IComparer parameter, but with custom controls you subclass the base and override methods to make changes. Both, however, let you easily alter processes to fit your specific needs.

    Visitor

    Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

    System.Linq.Expressions.ExpressionVisitor (used internally by [LINQ])


    What is the Dependency injection?

    Dependency injection & Factory

    Dependency injection (DI) is a technique for achieving loose coupling between objects and their collaborators, or dependencies. Rather than directly instantiating collaborators, or using static references, the objects a class needs in order to perform its actions are provided to the class in some fashion.

    • This follows the Dependency Inversion Principle, which states that “high level modules should not depend on low level modules; both should depend on abstractions.”
    • Instead of referencing specific implementations, classes request abstractions (typically interfaces) which are provided to them when they are constructed.
    • Extracting dependencies into interfaces and providing implementations of these interfaces as parameters is also an example of the Strategy design pattern.


    https://stackoverflow.com/questions/557742/dependency-injection-vs-factory-pattern

    http://www.c-sharpcorner.com/UploadFile/97fc7a/factory-pattern-in-net-with-an-example/

    • Dependency Injection is more of a architectural pattern for loosely coupling software components. Factory pattern is just one way to separate the responsibility of creating objects of other classes to another entity. Factory pattern can be called as a tool to implement DI. Dependency injection can be implemented in many ways like DI using constructors, using mapping xml files etc.
    • Factory pattern offers higher-level abstraction than DI. A factory can offer configuration options just as DI does, but it can also choose to hide all those configuration details, so that the factory can decide to switch to a completely different implementation without the client knowing. DI on its own does not allow this. DI requires the client to specify the changes he want
    • Life cycle management is one of the responsibilities dependency containers assume in addition to instantiation and injection. The fact that the container sometimes keep a reference to the components after instantiation is the reason it is called a “container”, and not a factory.
    • Dependency injection containers usually only keep a reference to objects it needs to manage life cycles for, or that are reused for future injections, like singletons or flyweights. When configured to create new instances of some components for each call to the container, the container usually just forgets about the created object.
    • One disadvantage of DI is that it can not initialize objects with logic. For example, when I need to create a character that has random name and age, DI is not the choice over factory pattern. With factories, we can easily encapsulate the random algorithm from object creation, which supports one of the design patterns called “Encapsulate what varies”.

    Inversion of Control Container

    An Inversion of Control Container uses the principle stated above to (in a nutshell) manage classes. That is, their creation, destruction, lifetime, configuration, and dependencies. This way classes do not need to obtain and configure the classes they depend on. This dramatically reduces coupling in a system and, as a consequence, simplifies reuse and testability.

    http://ayende.com/blog/2887/dependency-injection-doesnt-cut-it-anymore

    the core things that an IoC container should provide.

    • · Dependency Injection
    • · No required dependency on the container from the services
    • · Life style management
    • · Aspect Oriented Programming

    In Package Manager Console enter Command: Install-Package Ninject.MVC4

    After Installing Ninject Framework you should be able to see one class, NinjectWebCommon class, in the Application start folder [App_Start].

    A NinjectResolver will inherit System.Web.Mvc.IDependencyResolver,

    1. using Ninject;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using System.Web;
    6. namespace MvcNInject.App_Start
    7. {
    8. public class NinjectResolver: System.Web.Mvc.IDependencyResolver
    9.     {
    10. private readonly IKernel _kernel;
    11. public NinjectResolver()
    12.         {
    13.             _kernel = new StandardKernel();
    14.             AddBindings();
    15.         }
    16. public object GetService(Type serviceType)
    17.         {
    18. return _kernel.TryGet(serviceType);
    19.         }
    20. public IEnumerable<object> GetServices(Type serviceType)
    21.         {
    22. return _kernel.GetAll(serviceType);
    23.         }
    24. private void AddBindings()
    25.         {
    26. // _kernel.Bind<To, From>(); // Registering Types 
    27. this._kernel.Bind<IEvent>().To<EventConcrete>(); // Registering Types
    28.         }
    29.     }
    30. }

    In Application_Start() method we are going to call our NinjectResolver class.

    1. protected void Application_Start()
    2.         {
    3.             AreaRegistration.RegisterAllAreas();
    4.             DependencyResolver.SetResolver(new NinjectResolver());// Calling  NinjectResolver Class 
    5.             WebApiConfig.Register(GlobalConfiguration.Configuration);
    6.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    After completing with calling class in Global.asax now we are going to move forward to EventController and in this controller we are going to implement Constructor Injection.

    1. public class EventController : Controller
    2. {
    3.      private readonly IEvent _IEvent;
    4.      public EventController(IEvent IEvent)
    5.      {
    6.          _IEvent = IEvent;
    7.      }
    8. }

    Property Injection

    Here I have created Property with name [_Event];  to inject in property we need to Use [Inject] attribute on top of the Property where you want it.

    See below example.

    1. [Inject]
    2. public IEvent _Event { set; get; }

    If you have looked closely then you can see I have commented Constructor; and still we are able to inject using Property injection.

    Method Injection

    Here I have created Method Injection. To use this just create a Method with any unique name, I have named it DemoMethod and this method should take the Interface as Parameter, after that, on that method, just add [Inject] Attribute.

    1. [Inject] 
    2. public void DemoMethod(IEvent IEvent)
    3. {
    4.    _IEvent = IEvent;
    5. }

    Dependency injection http://www.ninject.org

    https://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx

    Write your code so it’s flexible…

    public class Samurai {
        public IWeapon Weapon { get; private set; }
        public Samurai(IWeapon weapon) 
        {
            this.Weapon = weapon;
        }
    }

    …and let Ninject glue it together for you.

    public class WarriorModule : NinjectModule
    {
        public override void Load() 
        {
            this.Bind<IWeapon>().To<Sword>();
        }
    }

    Software Maintenance and Support

     

    “Begin with the end in mind”

    Maintenance and support will continue for the life of your software system. A significant portion of the system’s life-cycle budget will be consumed by these tasks. In fact, experts estimate that Maintenance can eventually account for 40 to 80% of the total project cost.

    What is Maintenance?

     

    This phase of the software lifecycle consists of the tasks required to keep your system operational after it is delivered into Production.

    Software maintenance cost is derived from the changes made to software after it has been delivered to the end user. Software does not “wear out” but it will become less useful as it gets older, plus there WILL always be issues within the software itself.

    The different types of maintenance tasks are described as:

    1. Corrective – Updates that are required to correct or fix problems. (generally 20% of software maintenance costs)
    2. Perfective – Modifications that enhance or improve the functionality or performance of the software. This includes new user requirements. – costs due to improving or enhancing a software solution to improve overall performance (generally 5% of software maintenance costs)
    3. Adaptive – Software modifications that are required due to environmental changes (eg. upgrade to operating system) – costs due to modifying a software solution to allow it to remain effective in a changing business environment (25% of software maintenance costs)
    4. Preventative – This corrects potential flaws or problems in the software before they become effective.
    5. Enhancements – costs due to continuing innovations (generally 50% or more of software maintenance costs) Same as Perfective ?

    What is Support?

     

    Support refers to the assistance given to users to address their problems and queries after system implementation.

    Key parameters considered while estimating the efforts required.

    • The industry and application type
    • Size of the application
    • Platform Types.
    • Programming language used
    • Effort spent on different maintenance activities
    • Effort spent on different support activities
    • The number and types of defects found during the maintenance period
    • Average time is taken to repair defects
    • Calls to Help Desk
    • Team size

    Automated Source Code Analysis

    • The architecture tools and Static Code Analysis in Visual Studio Ultimate help us to visualize the organization, relationships, design patterns and behavior of existing applications

    To detect patterns and the general structure of an application at a high level.

    • Generate sequence diagrams from the existing code and get required interfaces for each component
    • Helps to asses the impact of changes

    Improve productivity and quality through Automation

    • Automated Live Unit Testing with VS
    • Automatically runs the impacted unit tests in the background as you type and provides real-time feedback

    Iterative Waterfall

    • Produces working software early during the lifecycle
    • The focus is on delivering a sprint of work
    • Deliver series of valuable/shippable features/projectsLowrisk
      • Low risks factors as the risks can be identified and resolved during each iteration.
      • if one project goes wrong, it would not impact another project

    Flexible

    • More flexible as scope and requirement changes can be implemented at low cost

    • SDLC Models
      • https://www.itproportal.com/2010/07/04/comparison-various-software-development-life-cycle/
      • http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=32B2FE647EC4C6DF095FC1D671C4A24A?doi=10.1.1.667.9896&rep=rep1&type=pdf
      • http://www.agilistapm.com/differences-between-waterfall-iterative-waterfall-scrum-and-lean-software-development-in-pictures/
      • https://www.mountaingoatsoftware.com/blog/an-iterative-waterfall-isnt-agile

     

    • Requirement Elicitation
    • The term elicitation is used in books and research to raise the fact that good requirements cannot just be collected from the customer, as would be indicated by the name requirements gathering. Requirements elicitation is non-trivial because you can never be sure you get all requirements from the user and customer by just asking them what the system should do OR NOT do (for Safety and Reliability). Requirements elicitation practices include interviews, questionnaires, user observation, workshops, brainstorminguse cases, role playing and prototyping

    Reverse analysis the source code

    • Visual Studio Architecture Tooling Guide Scenarios https://blogs.msdn.microsoft.com/visualstudioalmrangers/2015/04/22/library-of-tooling-and-guidance-solutions-aka-msvsarsolutions/
    • https://vsardata.blob.core.windows.net/projects/Visual%20Studio%20Architecture%20Tooling%20Guide%20-%20Scenarios.pdf 
    Questions / Metrics

    1. Size of each application or module
    Application Number of Modules Number of

    Screens

     

    Number of  Scheduled Batches Number of  Integrations to External applications

    The number and types of defects found in a year

    Classification Priority No of issues found
    Standard Critical (P1)
    High (P2)
    Medium (P3)
    Low (P4)

    List of different .NET languages, Databases used with the applications.

    Technology / Languages Number of applications
    C#
    VB. NET
    SQL Server
    Oracle
    MySQL
    NoSQL

    List of different .NET frameworks used with the applications.

    Technology / Languages Number of applications
    ASP.NET – Web Forms
    ASP.NET – MVC
    WinForms
    WPF
    WebAPI
    WCF
    SingalR
    Entity Framework
    NHibernate
    Angular
    Any other technologies
     

    Third-party applications or packages integrated with the applications

    Third Party integrations Number of applications
    CRM (Siebel, Vantive, Remedy, SharePoint, Documentum etc.)
    BI / OLAP / DW Tools

    (ETL, Data Stage, Sagent, Informatica,

    SAS, Ab Initio)

    ERP Skills (Peoplesoft, SAP,

    Oracle Applications etc.)

     

    Software development life cycle models used

    SDLC Number of applications Number of releases in a year
    Waterfall
    Iterative Waterfall
    Agile
    Any other SDLC methods

    Type of Integration and deployment methods used (to estimate the efforts to deliver the build to different environments

    Integration and Deployment Number of applications
    CI/CD
    Automated deployments only
    Manual Integration and deployment

    Availability of the documents in English –  Architecture documents, HLD, LLD, User guides, deployment documents

    References

    1. https://files.ifi.uzh.ch/rerg/arvo/courses/seminar_ws02/reports/Seminar_9.pdf
    2. https://gupea.ub.gu.se/bitstream/2077/10553/1/gupea_2077_10553_1.pdf
    3. https://www.slideshare.net/anandsubramaniam/project-metrics-measures
    4. http://isbsg.org/maintenance-support/

    SPA -Part 1:JavaScript to Angular

    Introduction

    This article is a collection of notes and references from other web sites for the self study of Single Page Applications and Angular. The list of source web sites referred are mentioned in the “POINTS OF INTEREST” section of this article.

    Background

    • Single-Page Applications (SPAs) are Web apps that load a single HTML page and dynamically update that page as the user interacts with the app.
    • SPAs use AJAX and HTML5 to create fluid and responsive Web apps, without constant page reloads. However, this means much of the work happens on the client side, in JavaScriptThe Traditional Page Lifecycle vs. the SPA Lifecycle
    • In a traditional Web app, every time the app calls the server, the server renders a new HTML page. This triggers a page refresh in the browser.
    • An SPA renders only one HTML page from the server, when the user starts the app. Along with that one HTML page, the server sends an application engine to the client. The engine controls the entire application including processing, input, output, painting, and loading of the HTML pages.
    • In an SPA, after the first page loads, all interaction with the server happens through AJAX calls. These AJAX calls return data—not markup—usually in JSON format. The app uses the JSON data to update the page dynamically, without reloading the page.
    • Benefits
      • One benefit of SPAs is obvious: Applications are more fluid and responsive, without the jarring effect of reloading and re-rendering the page.
      • Typically, 90–95 percent of the application code runs in the browser; the rest works in the server when the user needs new data or must perform secured operations such as authentication. Because dependency on the server is mostly removed, an SPA autoscales in the Angular 2 environment: No matter how many users access the server simultaneously, 90–95 percent of the time the app’s performance is never impacted.
      • Sending the app data as JSON creates a separation between the presentation (HTML markup) and application logic (AJAX requests plus JSON responses).
      • In a pure SPA, all UI interaction occurs on the client side, through JavaScript and CSS. After the initial page load, the server acts purely as a service layer.

    ECMAScript Vs TypeScript

    ECMAScript (or ES) is a trademarked scripting-language specification standardized by Ecma International in ECMA-262 and ISO/IEC 16262.

    • It was created to standardize JavaScript, so as to foster multiple independent implementations. ECMAScript is the language, whereas JavaScript, JScript, and even ActionScript 3 are called “dialects”.
    • ES5 is the JavaScript you know and use in the browser today. ECMAScript version 5 was finished in December 2009,  the latest versions of all major browsers (Chrome, Safari, Firefox, and IE)  have implemented version 5. So ES5 does not require a build step (transpilers) to transform it into something that will run in today’s browsers.
    • Coders commonly use ECMAScript for client-side scripting on the World Wide Web, and it is increasingly being used for writing server applications and services using Node.js.
    • TypeScript is a strongly typed, object oriented, compiled language. It was designed by Anders Hejlsberg (designer of C#) at Microsoft. TypeScript is both a language and a set of tools. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features.

    • As data types are introduced in Typescript below concepts are applicable
      • Variable declaration with datatypes
      • Type conversion/casting
      • Function overloading
      • Generics
    • As OOPs are inbuilt in Typescript below concepts are applicable
      • Class declarations with private, public, protected, static members
      • Constructor
      • Inheritence, Overriding, Interfaces, this and base operators

    OOPs in ECMA Vs TypeScript

    • An object is an unordered list of name-value pairs. Each item in the list can be a property or methods.
    • JavaScript does not have classes. The classes in ES2015 are just a cleaned up syntax for setting up prototype inheritance between objects.
    • ECMA5 has a prototype-based inheritance mechanism: Every JavaScript function has a prototype property, and you attach properties and methods on this prototype property when you want to implement inheritance (to make those methods and properties available to instances of that function).This prototype property is not enumerable; that is,only one object can be assigned.
    • constructor is a function used for initializing new objects, and you use the new keyword to call the constructor.

    In ES5 and earlier, constructor functions defined “classes” like this:

    function Person(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
    }
    var person = new Person("Bob", "Smith");

    ES2015 introduces a new syntax using the class keyword:

    // the name of the ES5 constructor
    // function is name of the ES2015 class
    class Person {
    
      // observe there is no "function" keyword
      // also, the word "constructor" is used, not "Person"
      constructor(firstName, lastName) {
    
        // this represents the new object being
        // created and initialized
        this.firstName = firstName;
        this.lastName = lastName;
    
      }
    } 
    var person = new Person("Bob", "Smith");
    // TypeScript
    
    class Person {
      
      firstName: string;
      lastName: string; 
      
      constructor(firstname:string, lastname:string ){
      this.firstName = firstname;
      this.lastName = lastname; 
      } 
    }
    
    var person = new Person("Mary", "Smith", 39);

    Hello World from TypeScript

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>TypeScript HTML App</title>
        <script src="app.js"></script>
    </head>
    <body>
        <div id="content"></div>
    </body>
    </html>
    
    //app.ts
    class Greeter {
        element: HTMLElement;
    
        constructor(element: HTMLElement) {
            this.element = element;
            this.element.innerHTML = "Hello World";
        }
    }
    
    window.onload = () => {
        var el = document.getElementById('content');
        var greeter = new Greeter(el);
    };
    
    //Tranaspiled code
    var Greeter = (function () {
        function Greeter(element) {
            this.element = element;
            this.element.innerHTML = "Hello World";
        }
        return Greeter;
    })();
    
    window.onload = function () {
        var el = document.getElementById('content');
        var greeter = new Greeter(el);
    }

    Points of Interest

    You can explore more on the objects and OOPs in Javscript in below references.

    History

    Version 1.0 – 2017  June 21 – Initial