Showing posts with label naming convention. Show all posts
Showing posts with label naming convention. Show all posts

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.