Click here to Skip to main content
15,885,546 members
Articles / All Topics

Improving The Code I Write

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
3 Feb 2010CPOL5 min read 12.6K   5   9
The main reason I write articles is so that I have a place to put all the cool things I find regarding coding in one place.  Something has recently been coming up that has captured my attention: “Code Smells”...

The main reason I write articles is so that I have a place to put all the cool things I find regarding coding in one place. Something has recently been coming up that has captured my attention: “Code Smells”. By Code smells, I mean the ability to look or evaluate any piece of code that has been written and assess its value based on a number of indicators.

The question that started me on this path is: “How many developers look at ways of improving the way they write code?”. I have been writing recently to try and learn and refresh my knowledge on technologies as a way to improve the code I write. BUT this brings up a big question, does knowing a lot of technologies make you a better coder? I would assume that the more you know makes you more valuable since the company you work for would not need to train you, but does this make you a better coder? I don't think so because you could still write messy code that is difficult to maintain.

So in my quest to better the code I write, I have been looking at ways of improving and making sure that code I am writing does not have the following smells:

Duplicate Code

One of the best indicators for me is code duplication. I am sure that people add duplicated code into an application for many reasons: not enough time to extract the logic into a common method library, ease of copy and paste, etc. The reason I put this at the top is that it when you come to maintain an application that has a lot of code duplication or duplicated logic, it show on the amount of time it takes to do simple changes. Many times, changes that have been made to a system will not have been updated in all the duplicated methods and lead to easily avoidable bugs being introduced. The Principle DRY: Don't Repeat Yourself is a good way of making sure when you are coding to try and look at the bigger picture. It may take a little longer when you are initially writing the code, but I promise it will save time in the long run.

The God Object

This is something that can creep into any application. My guess is that the coder is trying to make it simple and keep related logic in one place or the team is being lazy when adding to existing factories/objects. The problem with this is that you end up with a method that does EVERYTHING and again becomes a nightmare to maintain. I have seen coders propose frameworks that would be guilty of this, that down the line cause maintenance teams endless hassles.

Overly Long Methods

This is closely tied to the god method I mentioned above. It refers to methods with too much logic and there are hundreds of lines long. Obviously when another developer comes along, they struggle to understand what the purpose of the method is and how everything works. A solution to this would be to try and break up the method into components that help make it more manageable.

Large Chunks of Commented Out Code

I haven't seen too many complaints regarding this, but it I can't stand it when I see it. What is the point of leaving code commented out for a considerable time. I obviously don't mind code commented out if it is causing a problem or will be reinstated after a short period. But large chunks of code commented out for large periods of time makes no sense. Most projects I hope are in some kind of source control. If that is the case, the developer could go back, find the code if it is needed again and correctly labelled / branched?

Global Variables

Global variables can be bad for many reasons, I will relate the issues I have had with them. The reason they show bad practice is that they can be accessed and changed from any method. They can be changed anywhere not to mention shadowed and increase the likelihood of bugs. Please don't misunderstand me, I have no problem with properties on web forms. The issue I am talking about would be variable that is used by multiple methods, i.e. a Data Set that get set and reset in different places.

Throwing an Exception in a Catch Block

I have never really understood this practice. If you need to make sure that you are closing streams or there is code that needs to run, you can and a finally clause. The code I am talking about is:

C#
try
{
    throw new Exception("Test");
}
catch (Exception exception)
{
    throw exception;
}
finally
{
    //Code that needs to run
}

Re-throwing the exception destroys the stack trace information and causes headaches when trying to debug the error.

If you need to log the error you could use the following to re-throw the error without destroying the stack trace:

C#
try
{
    throw new Exception("Test");
}
catch (Exception exception)
{
    Logger.LogError(exception)
    throw; //Preserves the stack trace
}
finally
{
    //Code
}

Non Descriptive Variable Names

This has to be my pet hate. In a few projects, I have looked at the naming convention seems to be the use of single char variable names as in int a; string b;. This isn't minified JavaScript, this was working C# code. There must be some reason people do it, maybe they want people to not meddle with their code or make it hard to understand. Personally I stay away from code that does this simply because making any changes could cause errors. Not to mention that trying to remember what variable is what or used for what can be difficult.

I was going to add Non descriptive Method names as in two or three letter method names but I think it could all go under the same category since it is really the same thing. I think it goes without saying that while reading through code that references the method ssd which gets back the variable w and goes on to use it in a method named Adw does really go a long way in making the code easy to understand.

In closing, the reason I am bringing up these points is that I want to have pride in the work that I do. I do see it as a work of art. Not only are we creating things, but they are useful (hopefully) to people that need to get their job done.

I am always keen on suggestions and ways of keeping my code clean and practices that aid this, so if you have suggestions please reply to this post.

kick it on DotNetKicks.com

This article was originally posted at http://www.makecodingeasy.com?p=56

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralDuplicate code [modified] Pin
Rozis3-Feb-10 11:13
Rozis3-Feb-10 11:13 
GeneralRe: Duplicate code Pin
supercat93-Feb-10 12:04
supercat93-Feb-10 12:04 
GeneralRe: Duplicate code Pin
Rozis4-Feb-10 12:31
Rozis4-Feb-10 12:31 
supercat9 wrote:
I'm not quite clear what you mean here. While a programmer should generally try to avoid redundant tests, if the natural sequence of events would be to (1) do some stuff based upon a condition, (2) do some stuff independent of the condition, and (3) do some more stuff based on the first condition, the natural way to write it would be to test the condition in step (1) and again in step (3).


Generally speaking (you may have lots of examples that disagree with it) i think this style of coding is not a good because the condition is 'too low'. The code handles 2 situations: a situation where condition A is true and one where condition A is not true. If this is your design you should write if A .. else .. endif (in pseudo code). The fact that both branches have some same parts is not relevant (although it is an indication that it is a 'bottom-up component' meaning it can be placed in a separate identity (function or method)). Now if we have to change our code because of changing demands there will be a chance our initial design (situation A and not A) will hold, but the same codepieces not. This is likely because the situations A and not A came from our design (thus where dictated by the problem) but the equal code pieces not. (the retest condition came in our code because we saw a pattern of repeating code). Generally speaking i think every condition in a program should have its base in the problem (otherwise it is potentially unneeded).

What i try to say is that we have to be cautious about the fact that 2 situations carry some pieces of equal code. Maybe we see a structure that is actually not there (in the long run).

I tend to write my code so to keep the 'conceptual view'. If this means i have some duplicate code in the 2 branches i don't care. Performance is the same, the exe may be a bit bigger. The advantage comes when the code needs to be changed: because the concept is clear in the code i know quickly where to make adjustments. My background is this is JSP (Jackson structual programming - Google if you like)


supercat9 wrote:
Further, if the code needs to do perform action1true or action1false based upon a condition so as to manage some aspect of the system, and then perform action2true or action2false based upon the case condition to manage some other aspect, it may be more efficient to say if (condition) {action1true; action2true;} else {action1false; action2false;} but it may sometimes be cleaner to group the code for each aspect of the system even if that requires restesting a condition.


I agree on this one: this makes the code more readable.

Duplicate conditions are for me code like this:

x=10
....
if x=10
...

Mostly it is covered better then in the one above...
GeneralRe: Duplicate code Pin
supercat94-Feb-10 16:08
supercat94-Feb-10 16:08 
GeneralRe: Duplicate code Pin
Rozis6-Feb-10 11:47
Rozis6-Feb-10 11:47 
GeneralRe: Duplicate code Pin
supercat98-Feb-10 6:10
supercat98-Feb-10 6:10 
GeneralCommented-out code; Rethrowing exceptions; Variable names Pin
supercat93-Feb-10 7:17
supercat93-Feb-10 7:17 
GeneralTypo Pin
alex turner3-Feb-10 1:12
alex turner3-Feb-10 1:12 
GeneralRe: Typo Pin
stephen.vaubell3-Feb-10 1:17
stephen.vaubell3-Feb-10 1:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.