Thursday, August 30, 2012

Coding Standards I follow

This one is long so take time out to read this. I have numbered it so that you can always come back and continue where you left.

One of the main concerns today in IT industry is maintenance of software.
Well, we all know that it is 90% of a SDLC. We, as developers, must do our part to ensure that maintenance is easy and hassle free. One of the first step to do this is to write good quality code. I am going to illustrate some of the techniques and standard coding patterns that is prevalent in current industry. These coding techniques are not my own but what I have gained from experience and by seeing code from Microsoft developers and Microsoft Partners. What is surprising is that the patterns are similar in nature and was mostly written by developers having more than 15 years of coding and design experience in US and EU. There must be a very strong reason why developers across the globe adopt the similar patterns in code.

When I do code review of my peers and subordinates, I usually see most of the basics missing.
They are following:

1. Refactoring
2. Irregular naming conventions
3. No advanced constructs used
4. No effort to reduce LOC
5. Code redundancy
6. No design patterns
7. No focus on performance issues
8. No focus on extensibility
9. No xml documentation
10. Scarcely used configurations
11. Dead blocks of code
12. No focus on making the application distributed and multithreaded
13. No focus on cross platform accessibility
14. Use of proper logging techniques and exception handling techniques.
15. No Decoupling

I am sure there will be many more factors which cause bottlenecks in maintenance.

What I am going to do is give you some pointers (not extensive) on how to address these issues while writing good c# code.




1. Refactoring

If a particular method that you are writing has several logic to implement it will  for sure be lengthy. In my view, if a particular block of code, unless pertaining to continual quantifiable logic, is more than 10-15 LOC it should be refactored. Refactoring increases the number of method calls but CLR is intelligent and capable enough to handle the call stack. Refactoring helps in code reuse and reduces code redundancy.


2. Naming Conventions.

Taking care of this one only will make your code look a lot legible and clean. In all code by my seniors with lot of experience do the following

  • Use double hunched camel casing for variables or beginning with underscore
  • Use All Caps for constants with underscores in between to make it legible.
  • Use First letter caps for Properties and Methods followed by camel casing
  • Classes, structs and enums can be written in any format but should be consistent
  • Arguments to methods and delegates should start as “arg
  • Objects’ names can start with “o” or “obj”. One good technique is prefixing the object name with english grammar articles i.e. “a”, “an”, “the”. Lists and Enumerables can be named as plurals beginning with “list” or “arr” or “lst” or “coll”.


3. Using Advanced constructs

Microsoft comes up with new advanced constructs and features in c# for a reason. Use them as much as you can to reduce your LOC and fast development(coding). Some of the advanced constructs are as below

  • Use generics as much as possible. It makes code generic and reusable.
  • Use lambda expressions and linq to handle iterations and filtering data
  • Use built in delegates Func, Predicate and Action as much as possible
  • Use reflection wherever possible to make code dynamic and generic.E.g. if there are a lot of properties on a class,use reflection to set and get the values sorted by property types.
  • Use interfaces and abstract classes (both built-in and custom). They make life much easier. [Did you know you can define “Properties” in interfaces and you can use interfaces for callbacks ?]
  • Write extension methods wherever possible. Use built-in extension classes as well such as Select, Where, Find, FindAll
  • Use Managed Extensibility Framework if you are in an iterative SDLC for non-thin client based software (you can use it for Silverlight though).
  • Use ternary operator “?:”and “??” for nullable types
  • Use scope resolution constructs wisely. i.e. private, public, internal, sealed,etc
  • USE WCF and try to make your widely used methods async.
  • Try and make your code decoupled as much as possible. Use MVVM design pattern for this purpose.

4. Reduce LOC
Try and make your code short and crisp. If your project is very large break it into smaller projects and assemblies.

5. Code Redundancy

Revise the entire code and find out dead blocks of code. Use “Find All References” feature to search method calls for this. If two or more methods nearly perform the same function but are in separate classes put it in a separate common utility class. Put a method in utility class if you are just using the class for calling the method. If you think a particular method can be used in multiple applications then write a new assembly and register in gac or put in a common WCF service and don’t forget to make it async.

6. Design Patterns
Use of Design Patterns is a must. Read “Head First”’s design patterns ebook to learn it.There are legacy 22 design patterns in all.
For heads up and to start with read the following:

  • Singleton
  • Command
  • Factory

Reading and implementing the design patterns will clear up your design concepts for sure.

7. Performance Issues

To tackle this you have to read and implement all pointers mentioned in this post. I will take up application, database and distribution level performance tuning in another blog post.

8. Extensibility

Extensibility can be achieved in many ways. Some of the techniques are as below:
  • Make your code decoupled as much as possible.
  • Make your solution multi-layered and if possible multi-tiered.
  • Use a good framework which supports extensibility such as MEF, Pipeline
  • Use a good design pattern such as MVVM
  • Make use of constructs such as extension methods.
  • Make your code enabled to tackle dynamic scenarios using Reflection

9. Documentation
This is a hectic task. Most developers don’t like to do this but are compelled to.
To make it easy for you there are many tools available on web such as Regionerate and Documentum which generate xml documentation and group your code automatically. This usually works based on your meaningful naming of your constructs.

10. Using Configuration
We all know that at some point of time while coding you gave to go the hard coded way for some specific values. This happens because the GUID of master records may vary between systems while migrating the solution to other systems. So the only option is to hard code and compare to implement logic. There is no way out of this i.e. you cannot make your code absolutely “hard-code” free. But what you do is reduce it by configurations. So use configured values as much as possible and do not use singleton class to read configuration.

11. Dead blocks of Code
When you finish finalizing your code make sure you have no dead blocks of code. Use process mentioned in point 5 to determine the blocks.

12. Making Application Distributed and Multithreaded
Lets face it ! your code is usually not multi-threaded if it is not a web app. Multithreading, multiprocessing and multi tasking all get the task done faster. So consider implementing the technology while taking care of the shared resources to avoid deadlocks. Even in web app when you are implementing a distributed system, you should take care that the resource sharing (static variables, application variables, etc) is handled properly. If not, you may face data inconsistency.

13. Cross Platform accessibility
This is a huge debatable topic. The entire world wide web or the W3C is working towards this. Common protocols are being adopted, standard are being baselined in order to facilitate cross platform accessibility. What you can do is start using components which make your application accessible irrespective of platform. You can follow some of the following
  • Different browser have different way of parsing/interpreting html and css. So use browser specific css.
  • Each browser has its own javascript engine. The engine may even changes if the version changes for a browser. So find out a way to handle the discrepancies in javascript libraries.
  • Use WCF. It supports a number of protocols and is platform independent. You can host it in multiple ways.
  • Do not write unmanaged code. Avoid it as much as possible.

14. Logging and Error Handling Techniques
Use the following for logging and error/exception handling
  • Application blocks
  • log4net
Whenever you are doing exception handling use “bubble up” method of throwing the exception to client (not the end user). What you expose to the client and on what level is up to the technical policy/standard of the organization. If your code is huge then use bookmarks and codes to point to the exact location and nature of the error. This helps a lot while development also. Use Fault contracts for WCF. There is detailed documentation in msdn for this.

For logging use the following targets
  • Eventlog as Default target if the error is uncategorised and not handled.
  • Database - This is the best place to log but can be a overhead since it makes a hit to DB.
  • Local files - This is very fast but take care of shared log files. If you use locks to handle shared resources then keep a lock counter limit to gradually baseline the logging threads.
When you log, remember to include the following in your log among other messages
  • Application Source
  • Module Name
  • Stack Trace
  • Date Time stamp (localized)
  • Log level (severity: Error, Critical, Fatal, Warning, Information, Alert, etc)

Housekeeping is a necessity for log files because you need to clean up and purge old logs which are not needed anymore. The recycle time needs to be decided by the technical policy of your organization.

You can also schedule jobs to clean up logs or alert you (email, sms, voice mail, etc) in case of fatal/critical errors when they occur.

15. Decoupling
Last but not the least “Decoupling”. When you are writing code try to make it “layered” as much as possible keeping in mind the following things

  • Changes made in one layer should not impact other.Even if it makes an impact, it should be only the subsequent layer and not all layers.
  • When developing web application use handler and modules.
  • Develop components like it were to be plugged into an unknown source (other components or layers). This will require it to be as generic as possible.
  • The decoupled component can be used elsewhere as an api.
Please go through MVVM model (used in silverlight) to know how an application is decoupled.

Please feel free to share or point out anything that seems irrelevant. These are standards that I personally follow and am comfortable with. You may choose to follow other better standards.

Wednesday, August 08, 2012

Building Pipeline Infra into Microsoft based designs - Part I


Today I going to take up one of the topics I mentioned in my earlier blog i.e. "Building Pipeline Infra into Microsoft 
based designs". I chose this topic because this is going to be one of the building blocks of my future topics. There will be 2 parts of this topic ".NET" part and "Pipeline Design" part.

.NET Part

Before starting I would like to go back to some .NET basics. If you do not have these concepts then this is going to help you.

In almost all the interviews you have attended in Java or .NET you have been asked about this - Interfaces and Abstract classes.
In most of my encounters with colleagues and other acquaintances and in interviews, no one was able to answer the real use of interfaces and abstract classes when asked. 

Can you ? I always ask this:What is the difference between an "interface" and an "abstract class". The answer that I usually get is "Interface can contain only method definition while abstract classes can contain method implementation too". 

Correct ! But my next question usually bowls them out. "What is the difference between an interface an "abstract class with all abstract methods" ? Why has Microsoft provided us with a separate construct which can act as a contract ?"

The answer lies in OOPS concepts "Principle of substituality" and "Late or Dynamic Binding". 


public class A
{
public A(){}
public string Display(){ return "A";}
}
public class B : A
{
public B(){}
public string Display(){ return "B";}
}

A objB = new B();


Moral of the above is that a parent or base class reference can contain child or derived class instance of an object.

[But there are different scenarios where a reference, as mentioned above, calls a method which exists both in parent and child class - which method is actually called ? Thats another topic to discuss which will be taken up in another blog.]

Lets now come to "interface".

Taking moral from above, we can also define as below.

Example:

public interface IData
{
int GetValue();
}

//classes implementing the above interface
public class MyData1: IData
{
public int GetValue()
{
return "1";
}
}

public class MyData2: IData

{
public int GetValue()
{
return "2";
}
}


//calling
IData o1 = (IData)(new MyData1());
IData o2 = (IData)(new MyData2());

o1.GetValue();

o2.GetValue();

The output of the above 2 statements is quite predictable i.e. 1 and 2. How is this concept helpful ?
This concept is helpful is various ways 
1) to make a design "Pipelined" 
2) make it extendible 
3) Make a design contextual

[The scenarios serving these will be discussed in next part of this topic].

How does this simple concept which you think you knew makes up for all the designs mentioned above ?
The answer lies in "Reflection" and concept of contract.

Say you have an interface I1 which is exposed by you in your product sdk. By exposing this interface publicly you are giving the developer (who is using your product and sdk) a way to implement his own logic in your product's processing "pipeline" [Pipeline programming]. Now there will be certain "hook" points exposed by you [and known to developer] in your product pipeline. 

Think of the product pipeline as a simple pipe or tube with holes at certain points along its length. You will be able to insert you own logic into this processing pipeline.

Now say the developer has written a class C1 implementing you interface I1. Since the class is bound by the I1's contract, it will for sure have all methods defined in I1. Now your task is to execute the logic implemented in the C1 class at the hook points in the pipeline. 

The process is simple, say one of the methods defined in I1 is "void Execute(object context);"

then...

I1 objC1 = (I1)(new C1());
objC1.Execute(null);

When you call "objC1.Execute(null)" [for now consider the context as null], the code written in Execute methodof C1 is executed. In this way you actually injected the custom developer logic in your product's processing pipeline.

Now there must be a question in you mind. How the hell do I get hold of this developer's class and where do I find it? This is where "Reflection" comes to our rescue.

Say the developer has written a class implementing your interface and built an assembly. nad you have registered this assembly in GAC or uploaded it in a database as a file blob. 
Then you have to dothe following:

1)Load this assembly in your executing pipeline
2)Get hold of the class implementing your interface.
3)Instantiate the class and get the object. Store it in interface reference.
4)Call the method.

Code:

//Load Assembly [e.g. from GAC]
Assembly asm = Assembly.Load("TestLib,Version=1.0.0.0, Culture=neutral, PublicKeyToken=421348bbd2628966");

//Get the types or classes in assembly implementing your interface
var type = typeof(I1);
Type[] types = asm.GetTypes();
List interfacetypes = new List();
foreach (Type p in types)
{
if (type.IsAssignableFrom(p))
        interfacetypes.Add(p);                
}

//Instantiate the class object
I1 objC1 = null;
if(interfacetypes.Count > 0)
objC1 = (I1)asm.CreateInstance(interfacetypes.ToArray()[0].FullName);

//Call the method
if(null != objC1)
objC1.Execute(null);


If you have any clarifications email me at purbarag@gmail.com