SIGN UP MEMBER LOGIN:    
ARTICLE

How Does Your "Code Smell"

Posted by Javeed M Shaikh Articles | .NET 4.5 October 21, 2011
In computer programming, code smell is any symptom in the source code of a program that possibly indicates a deeper problem. We are going to look at some of them here.
Reader Level:

So how does your "Code smell"
 
In computer programming, code smell is any symptom in the source code of a program that possibly indicates a deeper problem. We are going to look at some of them here.
 
1. Catch me if can you handle: Whenever you are doing an exception handling in your code do not just use the throw keyword to throw the exception to your parent method but instead us throw with the current exception so that the current stack trace information is also sent and you do not loose original exception information.
 
Do not use 
 
Catch (Exception ex)
{
throw ;
}
instead use
Catch (Exception ex)
{
 throw ex;
}
 
2. InPlace Replace: We have used the string functions so many times but one among them is the Replace function which returns back the replaced string instead of inplace replacing the string.
 
For example:
 
string s = "this is my string";
s.Replace("this", "that");  //this will not replace the word
s = s.Replace("this", "that");  //this will replace the word
 
3. Number Magix: There are instances where we need to use hard coded numbers or strings which are also known as "magic numbers/strings" in your code. Try to avoid scattering them in your code but instead create enums or store it in the config files.
 
// bad code
if(day == 3) { ... }
else if(day == 4) { ... }
Use Enumerations wherever possible, so the meaning and not the number, is displayed in the code, it helps debugging and readability for you and others who may maintain your code:
// good  code
if(day == MyEnum.ThirdDay) { ... }
else if(mode == MyEnum.FourthDay) { ... }
 
4. Builder by your side: One should whenever trying to concatenate a lot of string should not try to use the string object since theyt create a lot of footprints in your memory but instead use StringBuilder 
 
// bad code
string s = string.Empty;
for (int i=0;i<100;i++)
{
s = s+"This is number " + i.ToString();
}
//good code
StringBuilder mBuilder = new StringBuilder();
for (int i=0;i<100;i++)
{
mBuilder.Append("This is number " + i.ToString());
}

Please also look into String.Concat() if you want to concat less number of string as that would be more ideal.
 
5. Wire/UnWire: Whenever you are writing code to Wire an event also remember to unwire that event as that might give you unexpected result. I have seen comments which discusses that unwiring is taken care by the garbage collector but that is not the case. So one should unhook event handlers appropriately after wiring them.
 
6. What to catch finally: Many a times we have seen programmers use the try catch block but they do not write anything in the catch block as they just want to pass the code, this may hold true in a case which I will discuss below but ideally one should not do the following:
 
// bad code
try
{
    // my code may have errors here
 }
Catch (Exception ex)
{
    //I do nothing with this error, just gulp it.
}
You should do some logging of the exception or throwing the exception to the parent caller. The case where this could be a possibility is below, but again there are ways to overcome this scenario and if you happen to fall in one of these please leave in the comment on what you did:
try
{
// my code may contain error.
}
catch(Exception ex)
{
try
{
LogMyException(ex); // this might also throw an error
}
catch(Exception ex)
{
// what to do here now?
}
}
 
Also I have seen coders writing catch block always use generic Exception object and not specific to the expected error, one should first try to catch specific error and also keep the generic as a fall back like below:
 
catch(OutOfMemoryException outmemex)
{
// do something to release the memory, logging
}
catch(Exception ex)
{
// I don't know why error has occurred, log it.
}
How can one not use the finally block which guarantees execution of the piece in spite of an exception so please do not forget to add finally block to release objects and connections used in your code.
 
7. Warn ok please: I am sure most of the coders here don't even bother about Compiler Warnings they receive when they are compiling their solutions, it is also important for you to look into the compiler warnings that are showed up. 
 
8. Initialization: We have seen in our code that many time that we do unnecessary initialization of objects like the one below:
 
DataTable mytable = new DataTable();  // Initialization is not necessary
mytable = GetDataTable();
one should instead use
DataTable mytable = GetDataTable ();
 
9. Get, Set, Tools: Use more of productivity tools and addins that makes your life easier while coding ,  few of them
 
and you may find this link very helpful:
10. Are you NULL: So many times we get a null reference exception and that is probably because we always assume that there will be no null data, but that is always not true. One should always check for null before they use the object just to avoid these situations and have an alternate route to your code.
 
mType mobj= x as mType;
   if (mobj!=null) { 
      //more code here
    }
 
11. Follow standards and conventions while coding in not doing so you are taking a lot of others time in your team to understand the code by making it hard to read and may be re-use the code.
 
12. There is no need to call GC.Collect() in your code, the .NET GC is always there to collect your objects in most of the cases. It is a rare case when we need to interfere with the Garbage Collector work.
 
13. String the String: I have seen many coders doing this just top give you an example
 
Request.QueryString["myvariable"].ToString(); //there is no need for ToString here
Request.QueryString returns a string, so one should not call .ToString() here.
 
14. Comment: Comment and document your code often as you might also not remember that complex piece or a variable++ had solved some problem in the past. So not commenting on your code will create hard to read code for complex blocks for both you and your peers. Properly commented code is your friend.
 
15. Save the world: Stop thinking you as a Hero, so when you are stuck with your code just ask for help. It will not only help you solve your problem but also give a second eye to your issue and might come up with an more efficient way to solve the issue.
 
16. Avoid writing duplicate code, just put that logging code in a utility module and keep calling from your code.

17. Do not tempt to write long methods. What I mean here is method code which runs in thousands of line.

18. Do not have too many parameters in your methods, be reasonable and not confuse the caller of the method and have method readable.

19. Test, Test, Test: This will eliminate a lot of your bugs/defects and make your code more robust. This will increase the quality of your code and in turn your product reputation.
 
I hope these points were helpful to you and make your code smell better !

Login to add your contents and source code to this article
share this article :
post comment
 

These are useful and v important points to b remembered when coding. Thanks for the info. Regards

Posted by rsCode Dec 08, 2011

good informations.

Posted by shahid mojid Nov 28, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Become a Sponsor