Wednesday, October 31, 2012

Command Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Command design pattern.

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


  • Command declares an interface for executing an operation
  • ConcretedCommand defines a binding between a Receiver object and an action and also implements Execute by invoking the corresponding operation(s) on Receiver
  • Client creates a ConcreteCommand object and sets its receiver
  • Invoker asks the command to carry out the request
  • Receiver knows how to perform the operations associated with carrying out the request.



Applicability
  • GUI buttons and menu items: a Command may have an associated icon, keyboard shortcut, tooltip text, and so on. A toolbar button or menu item component may be completely initialized using only the Command object. 
  • Macro recording: If all user actions are represented by command objects, a program can record a sequence of actions simply by keeping a list of the command objects as they are executed. It can then "play back" the same actions by executing the same command objects again in sequence. If the program embeds a scripting engine, each command object can implement a toScript() method, and user actions can then be easily recorded as scripts.
  • Multi-level undo: If all user actions in a program are implemented as command objects, the program can keep a stack of the most recently executed commands. When the user wants to undo a command, the program simply pops the most recent command object and executes its undo() method.
  • Networking: It is possible to send whole command objects across the network to be executed on the other machines, for example player actions in computer games.
  • Parallel Processing: Where the commands are written as tasks to a shared resource and executed by many threads in parallel (possibly on remote machines -this variant is often referred to as the Master/Worker pattern)
  • Thread pools: A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. The items in the queue are command objects. Typically these objects implement a common interface that allows the thread pool to execute the command even though the thread pool class itself was written without any knowledge of the specific tasks for which it would be used.
  • Transactional behavior: Similar to undo, a database engine or software installer may keep a list of operations that have been or will be performed. Should one of them fail, all others can be reverted or discarded (usually called rollback). For example, if two database tables that refer to each other must be updated, and the second update fails, the transaction can be rolled back, so that the first table does not now contain an invalid reference.
  • Wizards: Often a wizard presents several pages of configuration for a single action that happens only when the user clicks the "Finish" button on the last page. In these cases, a natural way to separate user interface code from application code is to 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 contains no user interface code.

Consequences
  • Command decouples the object that invokes the operation from the one that knows how to perform it. Due to this usage it is also known as Producer - Consumer design pattern.
  • Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. Command pattern issues requests to objects without knowing anything about the operation being requested or the receiver of the request.
  • Promote “invocation of a method on an object” to full object status
  • An object-oriented callback
  • Sequences of Command objects can be assembled into composite (or macro) commands.
  • Command objects can be thought of as “tokens” that are created by one client that knows what need to be done, and passed to another client that has the resources for doing it.
  • Two important aspects of the Command pattern are interface separation (the invoker is isolated from the receiver) and time separation (stores a ready-to-go processing request that’s to be stated later).
  • Command pattern allows saving the requests in a queue
  • Offers support for undoable actions (the Execute method can memorize the state and allow going back to that state)
  • One usage for the command design pattern is to run commands asynchronous in background of an application. In this case the invoker is running in the main thread and sends the requests to the receiver which is running in a separate thread. The invoker will keep a queue of commands to be run and will send them to the receiver while it finishes running them.
Downsides
  • Command Pattern tends to lead to a proliferation of small classes; however, it does lead to simpler clients for supporting modern user interfaces. So,  It is important to have a good naming convention and to do your best to factor common classes.

Sample Code
Classic Command Pattern Sample

Command Pattern using delegate  Sample

Command Dispatcher Sample
Note: Command Dispatcher is a Pipeline pattern that can use Command pattern as well.

Related Patterns
  • Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Command normally specifies a sender-receiver connection with a subclass.
  • Chain of Responsibility can use Command to represent requests as objects.
  • Command and Memento act as magic tokens to be passed around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
  • Command can use Memento to maintain the state required for an undo operation.
  • MacroCommands can be implemented with Composite.
  • A Command that must be copied before being placed on a history list acts as a Prototype.

References
http://www.dofactory.com/Patterns/PatternCommand.aspx
http://sourcemaking.com/design_patterns/command
http://www.oodesign.com/command-pattern.html
http://en.wikipedia.org/wiki/Command_pattern
http://java.dzone.com/articles/design-patterns-command

Futher readings
http://www.codeproject.com/Articles/9415/Distributed-Command-Pattern-an-extension-of-comman
http://msdn.microsoft.com/en-us/magazine/cc785480.aspx
http://msdn.microsoft.com/en-us/magazine/cc163920.aspx

Sunday, October 28, 2012

Visitor Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Visitor design pattern.

Definition
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. (dofactory)




  • Visitor declares a Visit operation for each class of ConcreteElement in the object structure. The operation's name and signature identifies the class that sends the Visit request to the visitor. That lets the visitor determine the concrete class of the element being visited. Then the visitor can access the elements directly through its particular interface
  • ConcreteVisitor implements each operation declared by Visitor. Each operation implements a fragment of the algorithm defined for the corresponding class or object in the structure. ConcreteVisitor provides the context for the algorithm and stores its local state. This state often accumulates results during the traversal of the structure.
  • Element defines an Accept operation that takes a visitor as an argument and ConcreteElement implements the Accept operation that takes a visitor as an argument.
  • ObjectStructure can enumerate its elements or may provide a high-level interface to allow the visitor to visit its elements or may either be a Composite (pattern) or a collection such as a list or a set



  • A client that uses the Visitor pattern must create a ConcreteVisitor object and then traverse the object structure, visiting each element with the visitor.
  • When an element is visited, it calls the Visitor operation that corresponds to its class. The element supplies itself as an argument to this operation to let the visitor access its state, if necessary.

Applicability
  • Similar operations have to be performed on objects of different types grouped in a structure (a collection or a more complex structure). The object structure is not likely to be changed but is very probable to have new operations which have to be added. Since the pattern separates the visitor (representing operations, algorithms, behaviors) from the object structure it's very easy to add new visitors as long as the structure remains unchanged.
  • Do the right thing based on the type of two objects. 

Consequences
  • Visitor lets you define a new operation without changing the classes of the elements on which it operates.
  • The Visitor pattern is the classic technique for recovering lost type information without resorting to dynamic casts.
  • Double dispatch - In “double dispatch”, the operation executed depends on: the name of the request, and the type of TWO receivers (the type of the Visitor and the type of the element it visits).

Downsides
  • Visitor is not good for the situation where “visited” classes are not stable. Every time a new Composite hierarchy derived class is added, every Visitor derived class must be amended. 
  • The visitor methods signature has to be known in advance.
  • A lot of code has to be written to prepare the use of visitors
  •  If the hierarchy, ObjectStructure, cannot be modified because you are not allowed to, the visitor pattern cannot be applied at all.
  • You may be forced to compromise encapsulation, by needing to expose too much of the Element class's internals to make the Element classes "visitor ready"
  • If overused it can increase undesirable coupling within our application, versus a solution where we just used polymorphism; ie. the Elements descend from an Abstract base class, and each Element overriding the operation" methods.
  • Data accumulated by walking the tree has to be stored on the visitor.

Sample Code
Classic implementation of visitor pattern sample


Visitor pattern sample using C# 4.0 dynamic


Related Patterns
  • Iterator pattern defines a traversal principle without making a type differentiation within the traversed objects.
  • Command pattern encapsulates like the visitor pattern one or more functions in an object to present them to a caller. Unlike the visitor, the command pattern does not enclose a principle to traverse the object structure. Hence, the Visitor pattern is like a more powerful Command pattern because the visitor may initiate whatever is appropriate for the kind of object it encounters.
  • The visitor pattern can be used in addition with the Composite pattern. The object structure can be a composite structure. In this case in the implementation of the accept method of the composite object the accept methods of the component object has to be invoked.

References


Futher readings
http://codebetter.com/jeremymiller/2007/10/31/be-not-afraid-of-the-visitor-the-big-bad-composite-or-their-little-friend-double-dispatch/
http://en.wikipedia.org/wiki/Double_dispatch
http://www.jquantlib.org/index.php/A_better_implementation_of_Visitor_pattern
http://c2.com/cgi/wiki?VisitorPattern
http://groovy.codehaus.org/Visitor+Pattern
http://coderkarl.wordpress.com/2012/02/29/simplifying-the-visitor-pattern-with-the-dynamic-keyword/
http://code.logos.com/blog/2010/03/the_visitor_pattern_and_dynamic_in_c_4.html
http://logji.blogspot.com.au/2012/02/correcting-visitor-pattern.html
http://mikehadlow.blogspot.com.au/2010/09/using-visitor-pattern-with-domain.html
http://cleancoder.posterous.com/validating-the-visitor
http://vimeo.com/33706069

Saturday, October 27, 2012

State Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF State design pattern.

Definition

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








  • Context defines the interface of interest to clients and maintains an instance of a ConcreteState subclass that defines the current state.

  • State defines an interface for encapsulating the behavior associated with a particular state of the Context.
  • Each ConcreteSate implements a behavior associated with a state of Context.

  • Context delegates state-specific requests to the current ConcreteState object.
  • A context may pass itself as an argument to the State object handling the request. This lets the State object access the context if necessary.
  • Context is the primary interface for clients. Clients can configure a context with State objects. Once a context is configured, its clients don't have to deal with the State objects directly.
  • Either Context or the ConcreteState sub-classes can decide which state succeeds another and under what circumstances.

  • The State pattern does not specify where the state transitions will be defined. The choices are two: the Context object, or each individual ConcreteState sub-class. The advantage of the latter option is ease of adding new ConcreteState sub-classes. The disadvantage is each ConcreteState sub-class has knowledge of (coupling to) its siblings, which introduces dependencies between sub-classes.
  • A table-driven approach to designing finite state machines does a good job of specifying state transitions, but it is difficult to add actions to accompany the state transitions. The pattern-based approach uses code (instead of data structures) to specify state transitions, but it does a good job of accommodating state transition actions.
Applicability
  • When the behavior of an object should be influenced by it's state.
  • When complex conditions tie object behavior to it's state.

Consequences
  • Removes conditional (if/else/switch) statements relating to different states check.
  • Increases cohesion by aggregating state specific behavior into ConcreteState sub-classes with intention revealing names it’s easier to find that specific logic, and it’s all in one place.
  • Easy to add new states
  • Helps us in using the Single Responsibility Principle (SRP).

Downsides

  • Each ConcreteState sub-class has knowledge of (coupling to) its siblings, which introduces dependencies between sub-classes.
  • State pattern could be very verbose, when there are many states.
  • Some operations may not be possible when the context is in certain states (However, see this article for solution)


Sample Code


Related Patterns
  • Strategy has two different implementations, the first is similar to State. The difference is in binding times (Strategy is a bind-once pattern, whereas State is more dynamic).
  • The implementation of the State pattern builds on the Strategy pattern. The difference between State and Strategy is in the intent. With Strategy, the choice of algorithm is fairly stable. With State, a change in the state of the “context” object causes it to select from its “palette” of Strategy objects.
  • The structure of State and Bridge are identical (except that Bridge admits hierarchies of envelope classes, whereas State allows only one). The two patterns use the same structure to solve different problems: State allows an object’s behavior to change along with its state, while Bridge’s intent is to decouple an abstraction from its implementation so that the two can vary independently.
  • Flyweight explains when and how State objects can be shared.
  • Interpreter can use State to define parsing contexts.

References
http://www.dofactory.com/Patterns/PatternState.aspx
http://www.lepus.org.uk/ref/companion/State.xml
http://sourcemaking.com/design_patterns/state
http://elegantcode.com/2010/03/19/dont-give-up-on-the-state-pattern-just-yet/

Futher readings
http://en.wikipedia.org/wiki/Finite_State_Machine
http://www.eventhelix.com/realtimemantra/hierarchicalstatemachine.htm

Tuesday, October 23, 2012

Strategy Design Pattern

Although they are lots of books and articles about Design Patterns, yet I would like to share my point of view about common design patterns and would be happy to have your thoughts on comments. This post introduces GoF Strategy design pattern.

Definition
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. (DoFactory)


  • Context is configured with a ConcreteStrategy object and maintains a reference to a Strategy object. Context may define an interface that lets Strategy access its data.
  • Strategy and Context interact to implement the chosen algorithm. A context may pass all data required by the algorithm to the strategy when the algorithm is called. Alternatively, the context can pass itself as an argument to Strategy operations. That lets the strategy call back on the context as required.
  • A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context; thereafter, clients interact with the context exclusively. There is often a family of ConcreteStrategy classes for a client to choose from.
  • Usually each strategy need data from the context have to return some processed data to the context. This can be achieved in two ways:
    • Creating some additional classes to encapsulate the specific data.
    • Passing the context object itself to the strategy objects. The strategy object can set returning data directly in the context. 


Applicability

  • Many related classes differ only in their behavior 
  • You need different variant of an Algorithm
  • An algorithm uses data that clients should not know about
  • A class defines many behaviors, and these appear as multiple conditional statement in its operations.

Consequences
  • The strategy pattern uses aggregation instead of inheritance. In the strategy pattern, behaviors are defined as separate interfaces and specific classes that implement these interfaces. Specific classes encapsulate these interfaces. This allows better decoupling between the behavior and the class that uses the behavior. The behavior can be changed without breaking the classes that use it, and the classes can switch between behaviors by changing the specific implementation used without requiring any significant code changes. Behaviors can also be changed at run-time as well as at design-time.
  • Eliminates conditional statements
  •  The strategy design pattern splits the behavior (there are many behaviors) of a class from the class itself and defines families of related algorithms or behaviors for contexts to reuse and select.

Downsides
  • The main draw back of Strategy Pattern is that a client must understand how the Strategies differ. Since clients get exposed to implementation issues the strategy design pattern should be used only when the variation in behavior is relevant to them. In order to decouple the client class from strategy classes is possible to use a factory class inside the context object to create the strategy object to be used. By doing so the client has only to send a parameter (like a string) to the context asking to use a specific algorithm, being totally decoupled of strategy classes.
  • Communication overhead between strategy and context.
  • All algorithms should use the same Strategy interface.

Sample Code



Related Patterns

State: State is like Strategy except in its intent.Strategy is a bind-once pattern, whereas State is more dynamic

Template MethodStrategy is like Template Method except in its granularity. Strategy pattern is an alternative to sub-classing by encapsulating the algorithm in separate strategy classes lets you vary the algorithm independently of its context, making it easier to switch, understand and extend.

Decorator: Strategy lets you change the guts of an object. Decorator lets you change the skin.
Flyweight: Strategy objects often make good flyweights.

Template Method Design Pattern

Although they are lots of books and articles about Design Patterns, yet I would like to share my point of view about common design patterns and would be happy to have your thoughts on comments. This post introduces GoF Template Method design pattern.

Definition
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 (DoFactory).


Applicability
  1. When behavior of an algorithm can vary, you let sub-classes implement the behavior through overriding
  2. You want to control the point that sub-classing is allowed
  3. You want to avoid code duplication, implementing variations of the algorithm in sub-classes
I think you need to be cautious about item 3, because template method reduce code duplication using shared methods in base class and it could lead to deep inheritance coupling; If your code duplication could be put in a separate class, then you can can use shared component as a delegation. In Another word, do not clutter up your base classes by putting seemingly unrelated codes!


Consequences
  1. Well applicable in frameworks: They invoke so called hook methods, which provide default behavior which sub-classes can extend if necessary. It’s important for template methods to specify which methods are hooks (may be overridden) and which are abstract operations (must be overridden).
  2. A fundamental technique for code reuse, for example, in class libraries.
  3. Leads to an inverted control structure that’s sometimes referred to as the “Hollywood principle,” that is, “Don’t call us, we call you”.


Downsides
    1. Difficult to compose functionality:  When inheritance is used as the way to add new functionality, it becomes impossible to add functionality in more than one axis at the same time without defining more and more classes.
    2. Difficult to maintain: Having maintained a couple chunks of code that made extensive use of the template method, it can be challenging. Changes at any one level can disturb operation above or below that level in the template methods.
    • Alternative: define an interface for each kind of functionality and inject an instance for each. Typically these interfaces are factories and strategies. You can then mix and match each piece separately and also insert interceptors to handle functionality like logging, pooling, caching, etc.


    Sample Code



    Related Patterns
    • Factory Method is a specialization of Template Method.
    • Factory Methods are often called by template methods.
    • Strategy: Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.
    • Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class.
    References
    http://www.dofactory.com/Patterns/PatternTemplate.aspx
    http://tech.puredanger.com/2007/07/03/pattern-hate-template/
    http://sourcemaking.com/design_patterns/template_method
    http://juristr.com/blog/2010/07/practical-example-applying-template/

    Further readings
    http://patterns.cs.up.ac.za/examples.shtml
    http://msdn.microsoft.com/en-us/magazine/cc188707.aspx#S8

    Sunday, October 21, 2012

    Resolution Scope

    What is a scope

    "In computer programming, a scope is the context within a computer program in which a variable name or other identifier is valid and can be used, or within which a declaration has effect. Outside of the scope of a variable name, the variable's value may still be stored, and may even be accessible in some way, but the name does not refer to it; that is, the name is not bound to the variable's storage" (Wikipedia).
    In one sentence
    Scope is a fixed duration of time or method calls in which an object exists.


    What resolution scope means?

    In term of Dependency Injection, the scope defines the life-cycle and visibility of instances.

    A scope determines when a new instance of registered type with that scope is created and when an existing instance with that scope is destroyed. An instance of a scoped type is bound to the scope and is shared during the execution in the context of the scope.

    Common resolution scopes
    • No Scope (Transient, Prototype) : A new instance is created each time you request
    • Singleton (Container): The same instance is used each time you request it from this container
    • Thread: An instance is created for each thread

    Common resolution scopes for web applications
    • RequestScoped: Scopes a type definition to the life-cycle of a single HTTP request; that is each and every HTTP request will have its own instance of a single type definition. 
    • SessionScoped: Scopes a single type definition to the life-cycle of a HTTP Session.
    • ApplicationScoped: Scopes a single type definition to the life-cycle of a global HTTP Session (and usually binds to ApplicationContext).


    Why resolution scope?

    Using resolution scope has the following benefits:
    • It implicitly separates state by context (for example, two HTTP requests imply different contexts).
    • It reduces the necessity for state-aware application logic (which makes code much easier to test and reason about).

    How to define a custom resolution scope

    Sometimes, you can not find what you are looking in your selected DI framework. However, some of DI frameworks let you to extend built-in scopes or base classes to define your own custom scope; If not then you need to implement the custom scope yourself.
    At the following, you can find out how to define a custom resolution scope in Unity, and use it wherever that you like.
    To do that a base class named CustomScope has been defined. Any custom scope that you might use in the application inherits  from CustomScope. Following that, a sample code utilizing CustomScope has been demonstrated.


    ICustomScope and CustomScope definition



    CustomScope usage sample code



    Further Reading
    http://kohari.org/2009/03/06/cache-and-collect-lifecycle-management-in-ninject-20/
    http://code.google.com/p/google-guice/wiki/Scopes
    http://docs.jboss.org/webbeans/reference/1.0.0.PREVIEW1/en-US/html/scopescontexts.html

    Sunday, October 14, 2012

    Dependency Injection makes developers' life easier!


    What is Inversion of Control (IoC)?
    The basic idea of inversion of control is:
    Decoupling rules from implementation

    However, it has been defined as "Inversion of control (IoC) is an object-oriented programming practice where the object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis." (Wikipedia)


    What is Dependency Injection (DI)?
    The basic idea of dependency injection is:
    If you have an object that interacts with other objects 
    the responsibility of finding a reference to those objects at run time
     is moved outside of the object itself

    "interact" with other objects generally means invoking methods or reading properties from those objects. However, it has been defined as "A software design pattern that allows a choice of component to be made at run-time rather than compile time." (Wikipedia).
    Martin Fowler defines dependency injection as "A software design pattern that takes advantage of plugins to handle the interaction between components so that using different implementations in different deployments and assembling these plugins into an application is possible".

    In the following example class Foo is interacting with class Bar (Foo depends on Bar to fulfill a responsibility).In this case, Foo creates a new Instance of Bar and invokes its method.


    On the other side, In the following example the responsibility of getting a reference to an implementation of type IBar is moved outside of Foo. In this case, IBar has been injected into Foo as a dependency, via the constructor (It is also possible to inject dependencies via a property or even a regular method).



    How DI helps you to develop cleaner codes?
    Dependency Injection is an evolution of the "Factory Pattern" and can be done by hand or using a framework. It is basically an automated way to initialize a graph of objects which has the following benefits:
    • Facilitates the writing of testable code.
    • Leads to creating loosely-coupled and highly-cohesive code and makes your code easier to change (Nate Kohari)
    • Reduction of boilerplate code in the application objects since all work to initialize or set up dependencies is handled by a provider component.

    What is a Bootstrapper?
    A program that bootstraps itself is one that begins with an extremely trivial operation and then uses that to continue the start-up process internally. In a strict sense, the program does need help for the very first step but once that happens it doesn't need any external help.
    Traditional IoC solutions typically use a bootstrapper to configure components explicitly. The bootstrapper component has its own dependencies, but they're isolated to a single place within the application. This is usually a container that can be passed around; it can create classes while passing in the required dependencies, or it can be queried to return an implementation for an interface.

    Generally speaking, A bootstrapper in any application can be considered the entry point for running the application that is used to configure and initialize application's shell, modules as well as the IoC container.

    As an example the following is the Prism bootstrapper definition:
    "The bootstrapper is responsible for the initialization of an application built using the Composite Application Library. By using a bootstrapper, you have more control of how the Composite Application Library components are wired up to your application." (MSDN)

    Convention over configuration
    Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility (Wikipedia).
    Convention over configuration takes the stance that the configuration of DI framework is actually part of application, and should not be publicly configurable. However, if certain bindings are required to be configurable, then explicit configuration based on app.config  or XML can be used to do that.
    Having bindings in code saves you from the verbosity of XML, and gives you type-safety, refactorability, and intellisense. As an example Ninject takes Convention over configuration approach.

    .NET DI frameworks
    See Scott Hanselman's "List of .NET Dependency Injection Containers (IOC)" post.

    How to build an abstraction over DI framework?
    If you want to configure dependency injection infrastructure without being dependent on a particular implementation, then you can build your own abstraction over DI implementation.
    To achieve this, I prefer to  define the abstraction by defining two interfaces needed to have their implementations in your chosen DI framewor and a base bootstrapper class that needs to be extended in the target application. At the following you can find sample codes when Unity is the chosen DI framework.

    Resolver and Registrator interfaces

    Resolver and Registrator implementations for Unity

    Boostrapper base class

    References
    1. Martin Fowler, 2004, http://martinfowler.com/articles/injection.html
    2. Nate Kohari, 2007, http://kohari.org/2007/08/15/defending-dependency-injection/#comment-950
    3. Google, http://code.google.com/p/google-guice/
    4. Wikipedia, Dependency Injection, http://en.wikipedia.org/wiki/Dependency_Injection
    5. MSDN, Bootstrapper, http://msdn.microsoft.com/en-us/library/ff921139(v=pandp.20).aspx
    Further Reading

    Monday, October 1, 2012

    .NET Collection Overview

    This post is mainly a review for .NET collection interfaces and classes.

    IEnumerator – A Forward Const Iterator
    IEnumerator defines an enumerator, which is an analogy of forward const iterator. "Forward" means enumerator can move in only one direction - forward. "Const" means that it cannot change the underlying collection. Current property is read-only.

    IEnumerator Interface
    IEnumerator<T> Interface

    Objects that implement IEnumerator are usually returned from IEnumerable.GetEnumerator(). By convention, new enumerator points to a location "just before" the beginning of the collection. You should call MoveNext() to move the enumerator to the first element of the collection.  MoveNext() will return false if collection is empty.


    IEnumerable – An Enumerable Collection with Read-Only Forward-Only Access
    IEnumerable is implemented by virtually all .NET collections. It defines a single method - GetEnumerator(). This method returns an enumerator for the collection. Any object that implements IEnumerable can be used with the foreach operator.

    IEnumerable Interface
    IEnumerable<T> Interface


    IQueryable – evaluate queries against a specific data source
    IQueryable allows you to define parts of a query against a remote LINQ provider in multiple steps, and with deferred execution.
    LINQ queries against IEnumerable<T> produce delegates (methods) which, when invoked, perform the described query. LINQ queries against IQueryable<T> produce expression trees, a data structure which represents the code that produced the query. LINQ providers such as LINQ to SQL interpret these data structures, generating the same query on the target platform (T-SQL in this case).

    IQuerable Interface
    IQuerable<T> Interface
    IQueryProvider Interface

    IObservable, IObserver 
    IObservable defines a provider for push-based notification, IObserver provides a mechanism for receiving push-based notifications. IObserver and IObservable is actually the mathematical dual of IEnumerable and IEnumerator.

    IObservable<T> Interface
    IObserver<T> Interface

    ICollection – Synchronizable Collection with Count
    ICollection defines a collection with Count. It defines IsSynchronized and SyncRoot properties that deal with multi-threaded access to the collection and if collection gets modified by other threads, its enumerators are invalidated and throw InvalidOperationException if used. If IsSynchronized is true, synchronization is built-in into collection operations, and collection can be used safely from multiply threads. If IsSynchronized is false, it means that collection operations are not thread-safe, and user must lock the collection instance, or use some other synchronization mechanism if he wants to work with the collection from several threads. SyncRoot is apparently supposed to return an un-synchronized version of given collection. Note that IEnumerable and IEnumerator and ICollection<T> totally ignore this issue. IReadOnlyCollection represents a strongly-typed, read-only collection of elements.

    ICollection Interface
    ICollection<T> Interface
    IReadOnlyCollection<T> Interface


    IList – Modifiable Collection with Integer Index
    Represent a collection of objects than can be individually accessed by index and because of the integer index, IList behaves more like an array rather than a list.

    IList Interface
    IList<T> Interface
    IReadOnlyList<T> Interface


    ISet
    ISet Provides the base interface for the abstraction of sets.

    ISet<T> Interface


    IDictionary – Associate Container
    IDictionary defines an associative container that stores key and value pairs. The interface is relatively straightforward. IDictionaryEnumerator is a helper interface that derives from IEnumerator.


    DictionaryEntry Class
    IDictionaryEnumerator Interface
    IDictionary Interface
    IDictionary<T> Interface
    IReadOnlyDictionary<T> Interface


    IComparer, IComparable,  IEquatable<T>, IEqualityComparer
    IComparer defines a method, int Compare(object x, object y), that a type implements to compare two objects whereas IComparable defines a generalized type-specific comparison method, int CompareTo(object obj), that a value type or class implements to order or sort its instance.
    IEquatable defines a generalized method, Equals(T other), that a value or class implements to create a type-specific method for determining equality of instances. IEqualityComparer defines methods, bool Equals(object x, object y), int GetHashCode(object obj) to support the comparison of objects for equality.

    IComparer Interface
    IComparer<T> Interface
    IComparable Interface
    IComparable<T> Interface

    IEquatable<T> Interface

    IEqualityComparer Interface
    IEqualityComparer<T> Interface


    IStructuralComparable, IStructuralEquatable
    IStructuralComparable supports structural comparison of collection objects and IStructuralEquatable defines methods to support the comparison of objects for structural equality.

    IStructuralComparable Interface
    IStructuralEquatable Interface


    Collection Interfaces


    Collection Generic Interfaces

    System.Array – Fixed Sized Array
    This class is an abstract base class for all built-in C# arrays. It represents an array of fixed size and implements IList interface. This class is interesting, because it is probably the only class in .NET that is both abstract and sealed. Thus, you can neither instantiate it, nor derive from it. Built-in C# arrays derive from it implicitly. You as a mortal user cannot declare your class abstract sealed - this causes a compilation error.
    Array class definition

    ArrayList – Dynamic Array
    This class is a dynamic array that implements the IList interface. ArrayList can work as an adapter for arbitrary IList. Such adapters are created via static method ArrayList.Adapter(). This allows to use methods normally not available for IList, such as RemoveRange(), LastIndexOf() or Sort().
    ArrayList class definition

    BitArray  – Array of Bits
    This class implements a fixed-sized array of Boolean values, or bits. Note that it implements merely an ICollection - not a full IList. Once constructed, the size of the bit array never changes. Besides, it does not implement IList methods such as IndexOf(), Contains(), etc. From the other hand it implements a number of additional, Boolean-specific methods such as And(), Or(), and Xor()
    BitArray class definition

    Hashtable
    Hash table is an un-ordered collection of key-value pairs. Key objects must correctly implement Equals() and GetHashCode.
    Hashtable class definition

    HashSet<T>
    HashSet represents a set of values. It is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary or Hashtable collections. In simple terms, the HashSet class can be thought of as a Dictionary collection without values. It provides many mathematical set operations, such as set addition (unions) and set subtraction. However, a HashSet collection is not sorted and cannot contain duplicate elements. If order or element duplication is more important than performance for your application, consider using the List class together with the Sort method.
    HashSet class definition

    SortedList, SortedDictionary, SortedSet
    Sorted list is a sorted collection of key-value pairs. Besides implementing IDictionary interface, it also allows access to its items by integer index via GetByIndex() and SetByIndex() methods.
    SortedList, SortedDictionary, SortedSet classes definition

    Queue
    Queue implements standard collection operations plus Enqueue(), Dequeue() and Peek() methods. Using reflection we can see that internally it uses standard array (object[]) - much like an ArrayList.
    Queue class definition

    Stack
    Stack implements standard collection operations plus Push(), Pop() and Peek() methods.
    Stack class definition

    CollectionBase,  ReadOnlyCollectionBase, DictionaryBase
    These abstract classes implement IList. They represent a base for type-safe collections that manipulates concrete types instead of generic object. Internally CollecationBase is a wrapper around ArrayList.
    CollectionBase, ReadOnlyCollectionBase classes definition

    DictionaryBase is an abstract base for type safe dictionaries. The idea is similar to CollectionBase. Internally DictionaryBase relies on a Hashtable.
    DictionaryBase classes definition

    StringCollection, StringDictionary
    StringCollection implements type-safe collection of strings.
    StringDictionary Implements string-to-object map. Interestingly enough, this class neither derives from DictionaryBase, nor implements IDictionary.
    StringCollection, StringDictionary classes definition

    NameValueCollection
    Implements string-to-string map sorted by key.
    NameValueCollection class definition

    LinkedList
    LinkedList represents a doubly linked list and because it is doubly linked, each node points forward to the Next node and backward to the Previous node. It provides separate nodes of type LinkedListNode, so insertion and removal are O(1) operations.
    LinkedList class definition

    ListDictionary,  HybridDictionary
    ListDictionary implements a dictionary based on a linked list.
    ListDictionary class definition

    HybridDictionary implements a dictionary based on a linked list for small sizes (below 10), and on hash table for bigger sizes.
    HybridDictionary class definition

    C# Interview Questions


    In this post, I would like to share some C# development interview questions.
    Q: What does the term immutable mean?
    The data value may not be changed.  Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory and any changes are in fact copiesFor example System.String is immutable and System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. StringBuilder is more efficient in cases where there is a large amount of string manipulation.  Strings are immutable, so each time a string is changed, a new instance in memory is created.
    Q: What is a dangling else?

    (see here for more information)
    Q: What is checked { } and unchecked { }?
    By default C# does not check for overflow (unless using constants), we can use checked to raise an exception.
    Example:

    Q: What’s the difference between const and readonly?
    The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it: -- in the variable declaration (through a variable initializer). So, if the constant value is changed in an assembly, you need to replace all assemblies that use the constant values when application upgrade and deployment, but if  readonly value  is changed you need to replace the assembly that contains the change only.
    Other difference is that const varaible type could be primitive types, but readonly variable type can be any type.
    Q: What’s the difference between typeof(foo) and myFoo.GetType()?
    First one takes type name and return result at compile time whereas second one takes object and return type at runtime using reflection ofcourse.
    Q: What operators cannot be overloaded and write some code to overload an operator?
    =    .    ? :     ->      new       is       sizeof       typeof
    Q: If I have a constructor with a parameter, do I need to explicitly create a default constructor?
    Yes
    Q:What’s the difference between an interface and abstract class?
    In an interface class, all methods are abstract - there is no implementation.  In an abstract class some methods can be concrete.  In an interface class, no accessibility modifiers are allowed.  An abstract class may have accessibility modifiers.
    Q: Can you declare the override method static while the original method is non-static?
    No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.
    Q:What is a struct? Is a struct stored on the heap or stack? Can you derive from a struct?
    struct is a value type with certain restrictions. It is usually best to use a struct to represent simple entities with a few variables. Like a Point for example which contains variables x and y. it is stored on stack and can not be derived.
    Q: What is the difference between Finalize() and Dispose() and How we can support deterministic finalization?
    Finalize called by GC and Dispose called by programmer to free up resources. using statement is quite handy and makes code quite efficient as right after end of using statement object created/declared in that statement disposed automatically means dispose method get called in deterministic way to free up memory. IDisposible is interface which classes implements to dispose unmanaged resources in deterministic manner.
    Q: Can you allow a class to be inherited, but prevent the method from being over-ridden?
    Yes.  Just leave the class public and make the method sealed. e.g.public sealed override void Method() {}
    Q: From a versioning perspective, what are the drawbacks of extending an interface as opposed to extending a class?
    With regard to versioning, interfaces are less flexible than classes. With a class, you can ship version 1 and then, in version 2, decide to add another method. As long as the method is not abstract (i.e., as long as you provide a default implementation of the method), any existing derived classes continue to function with no changes. Because interfaces do not support implementation inheritance, this same pattern does not hold for interfaces. Adding a method to an interface is like adding an abstract method to a base class--any class that implements the interface will break, because the class doesn't implement the new interface method.
    Q: Write some code to implement a jagged array.
    Q: What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;} ?
    Throw also return stack trace which throw e doesn’t

    Q: Explain the use of override with new? what is shadowing?
    Overriding means giving implementation of virtual/abstract/override-able method in derived class and if we use new it means it can’t be access through by any other class ref/object
    The new keyword explicitly hides a member inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base-class version. Although you can hide members without the use of the new modifier, the result is a warning. Shadowing is somehow opposite to overriding as it lets redefine method implementation with signature as well.

    Q: Write code to define and use your own custom attribute.
    (From MSDN)

    Q: What is a delegate and a multicast delegate?
    A delegate is a variable that calls a method indirectly, without knowing its name. A delegate that has multiple handlers assigned to it is a Multicast delegate.

    Q: What is Lambda Expression?
    A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements. Lambda expressions can be used mostly to create delegates or expression tree types. Lambda expression uses lambda operator => and read as 'goes to' operator. Left side of this operator specifies the input parameters and contains the expression or statement block at the right side.
    Example: myExp = myExp/10;
    Now, let see how we can assign the above to a delegate and create an expression tree:

    Q: Write a standard lock() plus “double check” to create a critical section around a variable access
    Q: How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#?
    You want the lock statement, which is the same as Monitor Enter/Exit:

    Q: What are design patterns? Describe some common design patterns.
    “Design patterns are recurring solutions to software design problems you find again and again in real-world application development.” They are used as a common design language during software development life cycle as well.

    Creational Patterns
    Abstract Factory:   Creates an instance of several families of classes
    Builder:  Separates object construction from its representation
    Factory Method:  Creates an instance of several derived classes
    Prototype:   A fully initialized instance to be copied or cloned
    Singleton:   A class of which only a single instance can exist
    Structural Patterns
    Adapter:   Match interfaces of different classes
    Bridge:   Separates an object’s interface from its implementation
    Composite:   A tree structure of simple and composite objects
    Decorator:   Add responsibilities to objects dynamically
    Fa├žade:   A single class that represents an entire subsystem
    Flyweight:   A fine-grained instance used for efficient sharing
    Proxy:   An object representing another object
    Behavioral Patterns
    Chain of Resp.:   A way of passing a request between a chain of objects
    Command:   Encapsulate a command request as an object
    Interpreter:   A way to include language elements in a program
    Iterator:   Sequentially access the elements of a collection
    Mediator:   Defines simplified communication between classes
    Memento:   Capture and restore an object's internal state
    Observer:   A way of notifying change to a number of classes
    State:   Alter an object's behavior when its state changes
    Strategy:   Encapsulates an algorithm inside a class
    Template Method:   Defer the exact steps of an algorithm to a subclass
    Visitor:   Defines a new operation to a class without change