8 Signs your code sucks

 
 

As a wide eyed junior developer when I first began working on large projects I simply accepted that it is difficult to fix bugs or find where an action is being executed. If only I knew then what I know now, I would had saved myself hours of frustration. The first step to writing good code is accepting the code you write (or work on) is crap, but sometimes you need to know what to look for. Here are some signs that your code sucks.

A method is larger than the screen – A method should only perform one specific task. A method should not contain the logic code to determine if the username field contains data, is valid, and that user exists. If a method is too large to fit within a single screen, that is a (very) good sign it is doing too much.

You are reusing variables – Unless you are working on embedded devices, memory is cheap. Don't be a memory scrooge and knee cap code maintainability, which in nearly all instances trumps performance, by reusing the same variable for multiple uses.

You are directly accessing the request/session – It not only makes writing unit tests (much) harder, but it is also difficult to know what data the application has access to. All data should be taken out of the session/request and stored in a bean. A bean, through its getters and setters, creates a “contract” of what data the application has access to, which greatly helps with code maintainability.

You need to use comments to explain the code – Code should be able to explain itself and should be in a format that is easily readable. If you find yourself needing to explain what your code is doing then you may want to look into rewriting that code.
EDIT: This is not referring to using comments (e.g. javadoc) to explain the purpose of a method/class and its inputs and outputs.

An exception's stack trace doesn't return the original problem -  You should never “eat” an exception, that is catch an exception, but not print its stack trace. How can a bug be fixed if you don't even know where the bug is occurring?

Your code is a mud ball – Just the name sounds ugly. A “mud ball” is when there is little separation between the layers or concerns of an application. Code should be modular allowing for ease of reusability and modifiability. Anything concerning the user interface happens in the view, program flow and usually data validation is the domain of the controller, handling business logic is the model's job, and only the model should be interacting with the data access layer.

It is hard to write a unit test – If you find a bug or write a new piece of code and it takes you more than a few minutes to write a unit test then that portion of code is handling too complex of a task.

Link:http://www.turnleafdesign.com/?p=246 

 
posted @ 2009-10-26 13:03  MagicLetters  阅读(410)  评论(0编辑  收藏  举报