Geeks With Blogs
Ram Kinkar Pandey

How to write a good code – 2

 

Following design principles makes design/ architecture of your project good and we developer don’t have much role in this. This is primarily taken as role of software/ solution architect. So what developer can do to make code better and understandable?

 

So it’s in hand of to write an easily understandable, well refactored and clean code developer (at least in agile world, where everything is not documented).

 

So I collected some useful information from “Clean Code – Robert C. Martin” and “Refactoring Improving the Design of Existing Code – Martin Fowler” and trying to present here.

These two books are amazing books and nobody can present everything written in these books on blogs so I urge every programmer to read these. But I hope that this small article from those books will give a good start.

 

These information / tips are divided into few categories.

 

Comments

 

Inappropriate Information

You should not write irrelevant information in comments like Change History, Author Name, Company Name etc. Comments should tell viewer about technical things like code and design.

 

Obsolete Comment

In agile world its always advised not to write comments at all and reason behind this is with time code gets modified and no one cares about modifying comment related to these modification so after some time comments becomes misleading. So if you writing code then make it sure that comments are always up to date or simply delete it. Have your function name meaningful. Your function should say what its doing.

 

Redundant Comment

Now if comments above function or near code are saying same what function name or code is saying then this is a redundant comment. So it’s wise to remove such kind of comments.

 

Poorly Written Comment

If you have to write comments because of any policy in your company or some other reason then write it properly and manage it properly. Take some time while writing these and write wisely.

 

Commented-Out Code

If you go through some old code then you may see some code commented. So these commented code doing nothing just increasing size of your file and making code base heavier in version control system. This also makes your code look bad and irritate you when you scroll through your code. So simply delete it, this is not going to harm you as it was already commented and how you can recover it from your version controlling application.

 

Functions

 

Too Many Arguments

You should avoid passing so many arguments in a function, if you have to pass many arguments then better to refactor your code and extract a class or structure containing these all variables and pass an instance of this class. Passing so many variables makes code look ugly, hard to understand and debug. It’s also bad according to abstraction to have so many arguments in any function.

 

Output Arguments

Output arguments as very confusing as viewer expects arguments to input not output.

 

Flag Arguments

Flag arguments like some Boolean values based on which we performs differently inside function are also very confusing and make code tougher to understand. So try not to have any kind of flag arguments in your function and use polymorphism to avoid these.

 

Dead Function

Dead functions are function which is no body in use but resides in code. So try to find these and delete it. It may be some time tough to find these kinds of functions because you also may have some unit test around these functions so you will always find reference or usage of these functions. So delete it carefully and delete it quickly and even you have broken your code you can always get this back from version controlling application.

 

General

 

Obvious Behavior Is Unimplemented

Avoid things of surprises and follow principle of least astonishment. You function should return or do things which is expected. Like GetDateOfJoining function is expected to return a date not a string.

 

Incorrect Behavior at the Boundaries

Often we don’t test our functions or code for boundary conditions generally we assume that they will work, this is always wise to test them for their boundary condition and just not assume.

 

Duplication

Don’t let any of your code to duplicate, extract that piece of code in another class and all other code will access it from there only. This decreases your maintenance cost and makes your code easy.

If code look doing similar thing but that is not 100% similar then follow some design patterns like template or strategy pattern for avoiding duplication in code.

 

Code at Wrong Level of Abstraction

Follow correct level of abstraction. Your base classes should not contain code or variable which your derived class is to use. Keep lower level things separated from higher level things. Try creating thin interfaces so that you need not to define unnecessary behaviors and give a dummy implementation to those. These functions/ behaviors can lead to a great level of confusion.

 

Base Classes Depending on Their Derivatives

Base class thing should know nothing about derived class. Base class should not depend upon derived class both should depend upon abstraction.

 

Too Much Information

Create thin (fine grained) interfaces so that coupling remains low. Follow correct level of abstraction and encapsulation. Don’t create classes with lots of methods/ functions. And don’t allow function/ methods to do many things.

 

Dead Code

Remove part of code which never gets executed. For this try writing unit tests for all possible scenarios and use some code coverage measuring tool and see which part of code never gets executed, delete that code.

 

Vertical Separation

Declare your local variables just before their usage and should have small scope. Declare your private function just below their first usage. This helps managing your code better.

 

Inconsistency

What ever you do, do in consistent manner. Name your variables, functions etc in consistent manner. Follow consistent code separation and design. Even a code not having good design but written in consistent way is easy to understand.

 

Clutter

Avoid clutters. i.e. remove all function, variables, constructors etc. which is never used or never executed in any condition.

 

Artificial Coupling & Feature Envy

Declare variables, functions, enums etc in the modules where they should be. Take your time to decide where they should go. This will reduce unnecessary coupling between different/ independent modules. If a function is using many variables from some other class then it indicates that function is declared at wrong location, it should be moved to then class which variables it using.

 

 

Inappropriate Static

Prefer non-static methods over static methods, only declare those methods static which need to be and in doubt make it non-static. In case your function can behave polymorphically then make it non-static.

 

Use Explanatory Variables

Variable name should say what purpose this variable is serving. Don’t hesitate to have a longer and explanatory name for your variable.

 

Function Names Should Say What They Do

Use explanatory name for your function, its name should say what function is doing.

 

Understand the Algorithm

If you working on some old code base and you are modifying some function then give proper time to understand how this function works and what all code lines are doing.

 

Prefer Polymorphism to If/Else or Switch/Case

According to Robert C. Martin “switch statements are probably appropriate in the parts of the system where adding new functions is more likely than adding new types” and he recommends “One Switch” rule : There may be no more than one switch statement for a given type of selection. The cases in that switch statement must create polymorphic objects that take the place of other such switch statements in the rest of the system.

 

Follow Standard Conventions

Follow standard conventions published by your company or team. This will eliminate the need of documentation and anyone who is new to project will find code very easy to understand.

 

Replace Magic Numbers with Named Constants

Replace all variables with Constants which values are not going to be changed through out the application.

 

Be Precise

When ever you have to make any decision in your code, make it very precisely. Like always think why have you give some specific scope to your variables functions, always think why you have declared any variable integer why float was not valid at this point. Always think of having transactions, locks, exception handling etc. Simply think about all parts of your code and think precisely.

 

Structure over Convention

Always prefer design decision with structure over convention. Its right that conventions makes your code readable but its design decision which makes code simpler and manageable.

 

Encapsulate Conditionals

Always try to encapsulate your conditions. Like if condition having many decision separated with || and && sometimes becomes hard to understand and it also not very manageable it increases chances of duplication too. So always try to move these things in function and keep if condition small.

 

Avoid Negative Conditionals

Negative conditions are not easy to understand so always try to check for positive conditions.

Like if(!fileNotCreated()) is hard to understand than if(fileCreated()).

 

Functions Should Do One Thing

One function should do one thing only, if it is doing more than one thing then refactor it and extract few more functions out of this function.

 

Keep Configurable Data at High Levels

Keep all constants, read-only variables and other configurable data at one position and that is at top position.

 

Avoid Transitive Navigation

If module 1 is dependent on module 2 and module 2 is dependent on module 3 then 1 should not know about 3.

 

Replace Temp with Query

Avoid temporary variables with query like functions. Though calling function every time may decrease performance but it makes code more readable. Using temporary variables makes code hard to manage and understand.

 

Replace Error Code with Exception

Instead of returning any error code tries throwing exception back. Exceptions carry much detail with itself which make debugging and problem solving easy. Just returning error code may lead to confusion sometime.

 

Posted on Sunday, January 3, 2010 5:59 AM Design Principles , OOPs Concepts | Back to top


Comments on this post: How to write a good code – 2

# re: How to write a good code – 2
Requesting Gravatar...
i am doing mca and as programminer i want to do my job so pls help me to write a simple and effective code
Left by nasim on Jun 24, 2011 6:05 AM

Your comment:
 (will show your gravatar)


Copyright © ramkinkarpandey | Powered by: GeeksWithBlogs.net