Funding for 'IT Lab' Project, Phase 1: Progress of sticker sales. Purchase a sticker to help us reach our target.Updated: 2010-02-28 11:53
10.7%
How to Write Better Code


by M.A.C.Sandarenu


Hope you all enjoyed my last two articles. This month I’m going to discuss about another important topic, writing better methods/functions.  Functions or methods are the building blocks of any computer programs.  Therefore the way we write them has a big impact on the quality and readability of the complete program. So let’s discuss some important point which we can follow, in order to make them more readable and easy to understand.

Use Descriptive Names

Hope you can recall that we discuss about this in my first article about writing better code.  Putting a good name to the method is the first step of a long journey. Method name should be either a verb or a verb phrase such as calculateTax, saveCashflow and sendMessage. It is better if you can have some common naming pattern. Avoid using synonyms of same word in different places of the program.  For example let’s say you want to add some business entities to the database. If you use method names like insertClient in one class, addProperty in another and saveExpenses in another just to save data to the DB, for a reader it can be really confusing.  Avoid this kind of practice and stick to one pattern of names throughout the program. So in above example we can use insertClient, insertProperty and insertExpense which are more clear and easy to understand.


Make It Small

This is one of a golden rule in writing better code. Size of the method you are writing has big effect on the readability of the code. If the method is really big and has lot of condition statements, loops; then it is really hard to read and understand the code. This is not only about the ability of someone else to read and understand the code; even you yourself may not be able to understand the code after some time.

When we begin coding, in our early stages, we tend to write everything in one method. Our whole program will consist of few giant methods. I have personally done that. In one of my projects I have a method which has more than 1000 lines of code. Yes, I typed the number correctly; it has 1000+ line of code.  I wrote the program few years back and now it is really difficult for me to understand the logic. I had to stare at the code for few hours to understand it. I think this is very common scenario among beginners.

So how short should be a good method? Actually there is no hard and fast rule for this.  General rule is like your method should be small so that anyone can easily understand it just by having a single look. They may not be able to understand each and every details of the code, but they should be able to get a brief overview without requiring putting lot of effort.   I personally think that methods should not exceed more than 30 lines. It is better if you can have methods much smaller than that.  

In one day we can’t learn how to write these kinds of small methods. It comes with experience.  I’ll share what I do when I’m coding. I start writing the code normal way. When I write some code which I feel that can be extracted in to separate method, I use the refactoring tools provided by my IDE to create new method.  I repeat the process till I get nice readable small set of methods.

Single Responsibility

One of the main reasons for methods to be large and difficult to understand is that they are going to do lot of things. There is principle known as “Single Responsibility Principle” which describes that your program should only have one reason for change. In simple terms it says that your programming elements should do only one thing, so they have only one reason for change. Actually this single responsibility principle can be applied to other programming elements such as classes, packages and modules as well.

Method doing lot of things usually means that it is doing actions belongs to many different levels of abstractions. So when you are writing methods you have to be clear of, at what level of abstraction does your function should operate. Instead of doing all the things in one huge method, break the functionality in to different levels of abstraction and put them in to different small methods.  Each of those methods should have single and clear responsibility. When one method is only doing one thing, it becomes really easy to read and understand the code; inside one method you only have to concentrate on one thing.  This also makes the maintenance of the code much easy, since it is more readable, easy to understand and you can change one feature without breaking the code.

Limit Number of Arguments Passed

Methods having lot of arguments are difficult to read and understand and they are also highly error prone. If your methods require more than three arguments to be passed, then you better have a good justification for it. Things become more difficult if your method is having arguments of same type. When there are many arguments of same type needs to be passed, there is a high probability of you swapping few of them. These kinds of things errors are very difficult to track as well.  

If you needs to have more than 3 arguments one thing you can do is to wrap them in to their own class, so you can pass single object argument rather than 10. See the difference in following two methods.





Avoid Flag Arguments

This is another bad practice we do; we pass a Boolean flag to the method and method do one of two things based on the value of the flag.  Instead of using a flag for this just use two separate functions to handle two scenarios.

Exception and Error Handling

We generally tend to return an error code based the status of the processing (success/failure) from our methods and then process those error codes. The problem with this approach is that we are forcing ourselves to handle the error situations immediately. There will be few if else statements to handle different error situations.  And generally error codes will be defined as set of Enums in a separate class and all other modules and classes will be depending on this ErrorCode class.

We can use Exceptions to handle these error scenarios more clearly. With that we can have a clear separation of success path and error paths.  But when putting try-catch blocks to handle different error situations you have be careful since they can have a big effect on the readability of the code. If you try to handle different exceptions inside same method then you are breaking the single responsibility principle; you are doing both error handling and processing is not one thing, they are clearly tow things. Best practice is to extract the error processing code into its own method. This clearly separate the processing and error handling.

Do not repeat yourself

Duplicate code is a magnet for errors and maintenance nightmare. Duplication commonly happen when you copy-paste few lines of code since you are too lazy to put separate method to handle common functionality where all others can access. It becomes really hard to keep up with the changes when you have lot of duplicate code. When you want to change something you’ll have to change it in multiple places. It is really common to miss some when you do changes, which can leads to hard to track bugs.


How to follow all these things?

Yes, that is a fair question, and the answer is also very simple. There is no way for us to write very clear code at first shot, rather it is an iterative process. Lets imagine how you write some important project report at the university, you write a draft, review it, add new things, remove some paragraphs, review it again, and the process goes on until you get near perfect report. Writing code is also a similar process. You write code,  then read through it and refractor that to make it more readable, write again, clean and refractor it and the process goes on until you get nice beautiful code.

Firs time when you write a method it may be long, and full of duplications. Then what you have to do is to go through it, extract duplicate code into separate functions, renaming, and split out functions and so on. This process can make much easier if you are having test cases. So when you are doing changes you can track breaking points very easily.  We’ll discuss about Test Driven Development in some other article.


                                                                                                   Previous article


about Duplicating code

--quote--
Duplicate code is a magnet for errors and maintenance nightmare. Duplication commonly happen when you copy-paste few lines of code since you are too lazy to put separate method to handle common functionality where all others can access. It becomes really hard to keep up with the changes when you have lot of duplicate code. When you want to change something you’ll have to change it in multiple places. It is really common to miss some when you do changes, which can leads to hard to track bugs.
--quote--

Personally, I already told that I am not a java programmer , and I can't understood the java geek code.
However, in the C++ there is a preprocessor and inline functions where you need to use duplicates.

The beautiful code should avoid the preprocessor , Yes preprocessor will save you :KLUDGE: hard to
debug bugs.But it's a tool on the other hand. My idea is to use it when you need to duplicate the
code. and the newest way is use of inline functions. But we can't put away the preprocessor completely.

there are some places like string concentration in C++, that ## operator that helps in many ways
when we dealing with the duplicated code. so we can't completely avoid the C++ preprocessor.

length of a function

I agree with you in the C++ but not in other languages like java.

Because in C++ the implicit code generation is inline if you write the
methods in the helder files ( inside the class body). Otherwise you can
make non-inline or even you can explicitly define it inline. So in C++
with the default implicit inline behavior you can have the same performance
even you decompose the code.

Personally I always write the constructor inside the class body as a
practice. and I push only the longer methods to the outside cpp file.

Yes this concept have a less performance loss when related to the C++,
but don't know what effects in java , C# and other computer programming
languages.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options