Tuesday, June 23, 2015

Useful Techniques in Visual Studio 2013

Peek Definition :
        Whenever we want to see the definition of a method /class ,we usually hit F12 which will open a new tab and analyze that definition.By doing so, we get distraction easily and need to switch back to original tab to continue.
         Alternatively , we can hit ALT+F12 to see glimpse of the definition in small window within the original tab or even we edit the definition within that small window as below and we can close the window by pressing ESC button.
Note : we can go deeper into a definition, by choosing Peek Definition when we are already within the Peek Definition at the top of the hierarchy. The top Peek Definition will display a dot within the title that represents the depth of the Peek Definition.

Availability : Visual Studio 2013 Professional and upwards.
Navigate To Feature (Edit -> Navigate To, or by pressing Ctrl+, (Ctrl + comma)):
  • we can use the space to create an and between two words. Like writing sea and or emp, this gives results for “SearchEmployee” because it contains the strings “sea” and “emp.” 
  • The character @ can be used to search only class names instead of searching everything, including file names and file paths.
  • Use capital letters to create a camel search for a path, file, and class name. For example, searching for SED can result in a “SearchEmployeeDepwise” class

Availability : Visual Studio 2013 and upwards.

The Enhanced Scrollbars :
    We can enable the enhanced scrollbar mode by right-clicking  the scrollbar and choose Scroll Bar Options à Behavior à use map mode for vertical scroll bar. With this enhances scrollbars, We can preview code within the same file.
Availability : Visual Studio 2013 and upwards.

Thursday, June 18, 2015

Wrap approaches when you are adding new features/ modifing the existing features in a legacy application

Wrap method:

Suppose we have Employee class which does pay the salary to employee  as below.
And all of sudden there is a change requirement to log employee information into the database/file
The same thing can be achieved in a bit different way without changing the pay method and
 introducing the new method as below

Wrap Class :  is nothing but decorator patterns.In this case, the same new requirement can be implemented as below.

Wednesday, June 17, 2015

Sprout approaches when you are adding new features/ modifing the existing features in a legacy application

     The sprout approaches is one of approaches which helps us when we are changing a legacy application and use these approaches with cautious.

Used when:
  1. you do not have much time to get the class under test harness 
  2. these new changes are to be get under test harness
  3. you want to develop these changes/method in test driven development
Types
  1. Sprout Method
  2. Sprout Class
Sprout Method : Steps to implement this type
  1. Identify where you need to make your code change.
  2. If the change can be formulated as a single sequence of statements in one place in a method, write down a call for a new method that will do the work involved and then comment it out.
  3. Determine what local variables you need from the source method, and make them arguments to the call.
  4. Determine whether the sprouted method will need to return values to source method. If so, change the call so that its return value is assigned to a variable.
  5. Develop the sprout method using test-driven development.
  6. Remove the comment in the source method to enable the call.
 Tips to get a new method under test harness
  • If the constructor is having bad dependencies, then try to pass the null values 
  • If passing null values to the constructor does not work, make that method as static.
Sprout Class : This type should be used  when the you can not get the new method under test harness even after the passing null values to the constructor and you can not make the new method as static.
Steps to implement this type as follows.
  1. Identify where you need to make your code change.
  2. If the change can be formulated as a single sequence of statements in one place in a method, think of a good name for a class that could do that work. Afterward, write code that would create an object of that class in that place, and call a method in it that will do the work that you need to do then comment those lines out.
  3. Determine what local variables you need from the source method, and make them arguments to the classes' constructor.
  4. Determine whether the sprouted class will need to return values to the source method. If so,provide a method in the class that will supply those values, and add a call in the source method to receive those values.
  5. Develop the sprout class test first.
  6. Remove the comment in the source method to enable the object creation and calls. 

Seams in C#


Seams : it is place where you can alter behavior in a program without editing in that place

Seam Enabling points :It is place where you can make the decision to use one behavior or another

In the above snippet, suppose we do not want to save any thing to data base or alter the save behavior. this place is called the seam

Seams types :
  1. Pre-processing seams (enabling point is Pre-processors)
  2. Link seams(enabling point is the classpath where you can change the assembly )
  3. Object seams(enabling point is the class constructor)




Changing Software

Legacy code :Code without the test.
Refactoring :The act of improving design without changing its behavior.
Optimization : It deals with resources (usually time or memory) Optimization.

Summary of reasons for changing software and its impact :
The below table should be read as e.g. if Refactoring (as a reason for changing software) is to be done ,Its impact are changes in structure




Impact On
Reasons for changing software
Adding Feature
Fixing a Bug
Change Requirements
Refactoring
Optimizing
Structure
Changes
Changes
--
Changes
--
New Functionality
Changes
--
--
--
--
Existing functionality
--
Changes
Changes
--
--
Resource Usage
--
--
--
--
Changes

Tuesday, June 16, 2015

Interface Segregation

Interface Segregation
It states that interfaces should be small and At their simplest, interfaces contain single methods that serve a single purpose.

The reasons for segregating (splitting ) large interface into smaller interfaces  :
  1. Self-documentation for other developers to follow
  2.  Decorating interfaces : we may have to decorate implementations using decorate pattern/adapter pattern  in the cases  where cross-cutting concerns such as logging transaction management ,caching are required
  3. Architectural Need :The interfaces are segregated based on the architectural need  e.g. the Data access technology  is different for the same data
  4. Client Need :When a set of certain set of operation is only available to a certain clients, the large interfaces are segregated into smaller interface
Examples of client needs  :
  1. Client A is having requirement to get read only a particular data from service and Client B is to get write only to the same data
  2. A set of certain set of operation is only available to a certain clients when the application is in specific state For example, the operations that a user can perform are typically different depending on whether that user is logged in or not.                       
Client construction :
          Client can construct segregated interfaces in 2 ways  as below.
  1. Single implementation, single instance : all of the segregated interfaces are implemented in a     single class, a single instance is sufficient for all of the related  dependencies on the client.
  2. Multiple implementations, multiple instances : If each segregated interface is given its own       implementation, each of those implementations needs to be constructed and supplied to the       client.
The Interface Soup anti-pattern    :
A common mistake is to take the segregated interfaces and reunify them in an aggregate as below.
In the above fig, the segregated interfaces are reunified in a single interface forming “interface soup”, resulting in providing implementations of all operations and so there is no scope for targeted decoration

The open/closed principle


It defined as “Open for extension and closed for modification ”

Exception to “Closed for modification” rule :
  •  Client awareness :Any change in source code is allowed to existing code as long as it does     not also require a change to any client of that code.
  • Bug Fixes :Steps for fixing bugs (follows “Arrange, Act, Assert” and  “Red, green, refactor”  patterns)    
                            1. Write a failing unit test and/or integration test 
                   that specifically targets the bug
                        2. The source code is modified so that the unit test 
                   passes
  • At this juncture ,It is necessary to modify the source code which is exception to OCP rules

Extension Points : Classes that honor the OCP should be open to extension by containing defined extension points where future functionality can hook into the existing code and provide new behaviors and there are 3 extension points as below.
  • Virtual methods : Any class that marks one of its members as virtual is open to extension. This type of extension is via implementation inheritance.
  • Abstract methods : This is an example of the Template Method pattern, in which an algorithm is modeled but its general steps are customizable because of delegation to abstract methods. In effect, the base class delegates the individual steps of  the process to subclasses.
  • Interface inheritance : the client’s dependency on a class is replaced with interfaces

Note : Extension points should carefully be created for cases where requirements are unclear, changeable, or difficult to implement

Protected variation : Identify points of predicted variation and create a stable interface around them and suggests that you identify parts of the requirements that are likely to change or that are particularly troublesome to implement, and factor these out behind extension points
  • Predicted variation : The requirements of an individual class should be linked directly to a business client’s requirement
  • Stable Interfaces : all interfaces chosen to represent an extension point should be stable. The likelihood and frequency of interface changes should be low, otherwise you will need to amend all clients to use the new version.



Monday, June 15, 2015

Single Responsibility Principle

              The single responsibility principle (SRP) instructs developers to write code that has one and only one reason to change. If a class has more than one reason to change, it has more than one responsibility.Classes with more than a single responsibility should be broken down into smaller classes, each of which should have only one responsibility and reason to change.
              The SRP is primarily achieved through abstracting code behind interfaces and delegating responsibility for unrelated functionality to whichever implementation happens to be behind the interface at run time. Some design patterns are excellent at supporting efforts to strictly regiment the SRP— in particular, the Adapter pattern and the Decorator pattern. The former enables much of your code  to maintain first-party references to interfaces under your direct control, although in reality utilizing  a third-party library. The latter can be applied whenever some of a class’s functionality needs to be removed but it is too tightly coupled with the intent of the class to stand alone.

Decorator Pattern: This pattern can also be used with events and properties(unless they use auto property)
The Composite Pattern :
The predicate Pattern :It is useful construct for hiding the conditional execution of code from clients
Branching Decorators :
Logging Decorators :
Limitations :
  • Any private state contained in the decorated class remains unavailable to the logging decorator,which cannot access this state and write it to a log.
  • logging decorator would need to be created for every interface in the application. logging is better implemented as a logging aspect(AOP in PostSharp)


Using the strategy pattern instead of switch :

            In the example, for each case of the switch statement, the behavior of the class changes. This presents a code maintenance problem because the addition of a new case option requires a change to this class. If, instead, you replace each case statement with a new implementation of an interface, further implementations can be created to encapsulate new functionality—and the client would not
need to change. This is shown as below




Interfaces and Design Patterns



Null Object Pattern: Its purpose is to allow you to avoid accidentally throwing a NullReferenceException and a plethora of null object checking code

The isNull Anti Pattern : Sometimes the Null Object pattern involves adding a Boolean IsNull property to the interface(IAbstraction). All real implementations(real object ) of this interface return the value false for this property. The Null Object implementation of the interface returns true.

The Adapter pattern : The Adapter pattern allows you to provide an object instance to a client that has a dependency on an interface that your instance does not implement. An Adapter class is created that fulfills the expected interface of the client but that implements the methods of the interface by delegating to different The Class Adapter pattern methods of another object. It is typically used when the target class cannot be altered to fit the desired interface. This could be because it is sealed or because it belongs to an assembly for which you do not have the source.
The Class Adapter pattern :

The object adapter pattern :
The strategy pattern: The Strategy pattern is used whenever a class needs to exhibit variant behavior depending on the state of an object. If this behavior can change at run time depending on the current state of the class.
the Strategy pattern is a perfect fit for encapsulating this variant behavior.










Unit Testing and Refactoring

Unit testing is the discipline of writing code that tests other code.
  • It is concerned with  most atomic behavioral units of  a system
  • In procedural code, The units are often functions
  • In OOs ,The units are classes.
  • Testing in isolation is an important part of a unit tests
Problems with Large Tests :
  • Error localization is difficult
  • Longer execution time( that takes more than 1/10th of a second to run )
  • Coverage
Qualities of good unit tests :
  • They run fast
  • They help us localize problem
  • Not talking to database
  • Does not communicates across a network
  •  Does not  touches the file system
  •  Does not need to do special things to your environments( such as editing configuration files ) to run it
The Legacy Code Change Algorithm :
  •  Identify change points  : The places where you need to make your changes depend sensitively on your architecture
  • Find test points
  • Break dependencies
  • Write tests
  • Make changes and refactor
Arrange, Act, Assert Pattern :
Every unit test is composed of three distinct parts:
  •         The arrangement of the preconditions of the test
  •         The performance of the act that is being tested
  •         The assertion that the expected behavior occurred
Test-driven development : it is preferential not to have a working system under test before you write the unit tests.

Red, green, refactor Pattern :
  • Write a failing test that targets the expected behavior of the SUT.
  • Implement just enough of the SUT so that the new test passes without breaking existing successful tests.
  • If any refactoring can be done on the SUT to improve its design or overall quality, now is the   time to do so.
Testing with Fakes :In TDD ,Actual implementations may not be available initially, We can fake implementations and use them in unit testing and fakes does not depend on any other third party libraries

Testing with Mock :Moq is the popular option for mocking implementations.

Test over-specification : The test  is over specified when It has knowledge of the SUT’s implementation rather than its expected behavior.

Avoiding test over-specification :
  • The first option is to test behavior only. State-based tests are the best example of testing expected behavior. If a method accepts data as  input and returns altered data as output, the method can be treated as a black box for testing purposes. If the method accepts  inputs A, B, and C and returns outputs X, Y, and Z, it is irrelevant to the test how it arrived at such answers. The method can then be refactored without breaking the unit tests.
  •  The second option is less attractive but is sometimes the only option. You can treat the unit test and the implementation that  it tests as one atomic unit: if one changes, so must the other .This is akin to accepting that the unit test is over-specified and  planning to throw away the unit test along with the production implementation if a refactor is ever required. This isn’t quite as wasteful as it might seem.
Writing tests for defect fixes : Write a failing unit test that captures two things: the exact reproduction steps required to force the defect to occur, and the expected behavior that is not currently enforced

Refactoring is the process of improving the design of existing code—after it has already been written .Each refactor differs in size and scope. A refactor could be a small tweak to a variable name to aid clarity, or it could be a more sweeping architectural change such as splitting user interface logic from domain logic when the two have become inappropriately intimate.

        Refactoring can be achieved in many ways like constants ,polymorphism, factory method, factory class  ..etc.

Dependencies and layering

In above figure , Client A depends on service B  but Service B does not depend on the Client A
·        Unless Client A truly makes use of the service B, The Client A  does not load assembly of the service B
·        Cyclic dependencies ( suppose Service B depends on the service B) is not allowed in Visual Studio
·        Types :
o   First dependencies(Both Client A and service B belong to same visual studio solution )
o   Framework dependencies(like System,System.core ,They always loads these dependencies)
o   Third party dependencies(these dependencies are developed by third-party developers e.g. Entity Framework)
·        The simplest way to organize dependencies that are external to your project and the .NET Framework is to create a
solution folder called Dependencies under the Visual Studio solution of a project and to add the .dll files to that folder

Code Smells: It is a way of saying that some code is potentially problematic and presence of “new” keyword is generally consider as code smells
 Issues with Code Smells if present :
  • Inability to enhance the implementations
  • Creates Chain of dependency
  • Lack of test-ability
Alternatives to object construction :
  • Coding to interfaces
  • Using dependency injection
The Entourage anti-pattern :
  • Keeping the interfaces and implementations in the same assembly.
  •  Entourage means ask for one assembly and it gives all it assemblies
The Stairway Pattern :
  • Keep the interfaces and implementations in the different assembly so that we can vary the     two independently, and clients only need to make a single reference—to the interface assembly.
  •  Interfaces should not have any external dependencies. As far as possible, this should always be adhered to
  •  Interfaces should not have methods or properties that expose any data objects or classes defined in third-party references
  •   It can depend on classes and data types from other projects in the solution and common .NET  Framework libraries
  •   A reference to infrastructural entities(Third party dependencies ) should be avoided.
  •   Third party library such as Log4Net, NHibernate, and MongoDB are  packaged using the  entourage anti-pattern.
  •   To work around the above issue, make use of a simple interface that hides the third-party dependency behind a first-party dependency and an adapter
Layers vs. tiers :
         The difference between layers and tiers is the difference between the logical organization and physical deployment of code. Logically, you could separate an application in three or four layers, but physically deploy it into one tier. The number of tiers is somewhat related to the number of machines that the application is deployed to. If you deploy to a single machine, you are deploying an application in one tier. If you deploy the application to two machines, split by at least two layers, you are deploying to two tiers.

Cross-cutting concerns :
  • Sometimes ,Component’s responsibilities(exception logging) does not fit into any of layers like MVC layers and are applicable to any layers
  • Aspect- oriented programming is application of cross-cutting concerns and in .NET ,we have POSTSHARP
Command/query separation (CQS) :

       1. CQS-compliant and non–CQS-compliant command methods















2 .CQS-compliant and non–CQS-compliant query methods.












Command/Query Responsibility Segregation :