Software Development

Write Clean Code in one Statement

Clean Code

When someone talks about clean code programming, does these questions ever bother you :

  • I can get things done, does it really matter to think about a clean code?
  • Do I need to learn about it?
  • Is this going to bring more money into my pocket?
  • Is this in a fashion to talk about clean code?
    Ultimately, what matters is a thing which works.
  • I have already completed coding very complex applications but I never realized something called CLEAN.
  • I have been through a lot of pressure from my boss, are you really asking me to think about Clean Code?

If you have ever come across any of these questions, you are at the right place. I am going to explain each and everything about clean code.

Don’t worry, I won’t share a dozen of links and neither a book of 200 pages. This will be very brief and simple. Only that much, which is required for the success of a software system.

SUCCESS OF A SOFTWARE SYSTEM, yes I mentioned it. A clean code can lead to a successful software system.

In fact, it will be just ONE STATEMENT which is going to do wonders. I will come back to that, but let’s understand what it is and why its required?

“CLEAN” represents completeness. If we plug “CODE” with it, it simply becomes a snippet which in all aspects brings clarity.

Lets look at the aspects of a Clean Code programming:

1. Naming Conventions.
2. Logs.
3. Code Formatting.
4. Adding small modules.
5. GIGO (Garbage-in-garbage-out).
6. Code Maintenance.
7. Conclusion

I understand you might have heard of these terms many times before. Don’t worry about any of these points right now.

I will simply highlight these aspects here.

Clean Code Naming Conventions

Naming Conventions sound really boring to me, but if I call a “BOOK”, piece of papers or a “TABLE” to wood or a “GLASS” to metal.

How difficult would it be to understand what the later means. Same is the case with the software code. Writing a constant name, I prefer
SERVER_DEFAULT_URL rather than ABC or XYZ.
This applies to variables, method names, class names, etc..

Use proper names, if they are not exact but, at least close in the meaning to what they are suppose to perform.

Example :

Write a small function/method which performs data validation for the JSON type input.

I suggest you to try this out yourself and compare with the below code snippet. Just mention the flow, rather than the complete code.

Private int validate(String jsonData) {

	Log.information(LogModule.DATA_VALIDATION, "Validation Initiated...(timestamp)" + jsonData);

	if(jsonData == null || jsonData.length <= 0) {

		Log.debug(LogModule.DATA_VALIDATION, "Validation Failed, empty input received");
		return ErrorCode.INVALID_INPUT;
	}
	
	//validate JSON
	if( !(validateJson(jsonData)) ) {

		Log.debug(LogModule.DATA_VALIDATION, "Invalid Json received");
		return ErrorCode.INVALID_JSON;
	}

	//TODO: process rest of the validation here...
	.
	.
	.

	Log.information(LogModule.DATA_VALIDATION, "Validation succeeded successfully!");
	
	return ErrorCode.VALIDATION_SUCCESSFUL;
}

 

You might have observed Error Codes, Log types, Log Modules. These are the generic utilities which shall be utilized throughout the entire application.

If the above code snippet has to be used as a library by some one else, it should be straight forward and easy to use. As with jsonString input name, one can identify that it is not going to work with any other string types.

Here, this input name ‘jsonString’ is forcing user to check for the input being sent. It will be a good practice to add some documentation about your code, but sometimes that can also be ignored.

Clean Code LOGS

I have also added enough Logs while writing the above source file. Logs should be treated as a story telling book, rather than fully technical and alien to the tester or anyone else. I have seen people writing horrendous log files which are too technical and definitely of no use to anyone other than the self. And, sometimes not even self.

The advantages of writing this story book are as follows :

– Tester who is accompanying you in testing your piece of code can get the benefit of analyzing and performing white box testing.
– It will be easy to find out bugs in the code by just going through the logs rather than scrabbling and digging into the source code.
– Any body in a team can contribute to bug fixes with the help of human readable log files.

Things you need to take care while writing your log files:

1. Keep your Logs as a separate utility:

One can easily enable/disable all or any particular log category.
By category I mean following types : Log.warning(), Log.debug(), etc…
Also because, sometimes you may have to disable certain or all type of logs from a final product.

2. Logs should be written as you start with the source code:

I have seen developers writing logs at later stage when they start finding bugs or it is required to dump some data.
At later stage you may not be fully aware about everything or you may forget things which are important to mention in the logs.

3. Only one utility for Logs:

In the entire software system, ideally, there should be only one utility for logs being utilized by all team member of that software product, rather than everyone doing it in their own way.

Applying these small tactics can really help you write ‘clean code’.

Clean Code Formatting

Every programming language have its own way of formatting software code. I will try to explain it using some examples.

Please forgive me if you find these examples vague. Somehow, people think the coding has to be very different and cumbersome, so that it becomes impossible to understand what this code means or what it does.

Rather, I think it should be simple enough for anyone to understand. You may be having valid reasons to debate for this thought. Please skip, if so.

When you hold a book with fantastic nice title and of your interest, if the text is not aligned or the paragraphs are not divided into proper groups. It would be really hard to read that book, despite of your interest, you may end up keeping that book in the corner.

Similarly, it is there with the software code. You may have experienced this in your coding career.

If you are assigned to work on the software code written by someone else, most likely your first intention would be to avoid being part of that mess. Rather, you prefer to work on a fresh feature or piece of code. And, same is the reason you are here, reading this tutorial.

So, if we keep our code properly formatted. It might not be all that hard for anyone to get involved with it. Give it a try and ask your colleagues to be part of your ‘clean code’.

Add Small Modules to Clean Code

You may have heard of this many times before, keep your code modular or divide your method into smaller pieces. But, I could see the compiler doesn’t have any issue with it, so why do you?

Let me explain why?

Take an example :
You have a shelf cluttered with books of different categories.
Write a program to group these books as per the category (sa. Fiction, Adventure, Business, etc.)
 and print that categorized list into one file.

Before you try to solve this problem with your computer program or using pseudocode. I would suggest you to try it out manually before reading it further.

Doing it manually, you will hold each book at a time and look for the category. Once you identify the category you will place it at appropriate location. And, you keep on doing this till the last book has approached.

Finally, you will have a nice clean shelf shinning with books.

Try to arrange your books and find out different ways of doing it, so you can improve on your algorithm as well.

I am dumping the sample source code for this. I will only add the portion of code.

Example Code for Small Modules to Clean Code

public Map<String, List> categorizeBooks(List booksInput) {

		Logs.warning(Logs.BOOK_UTILS, "Book processing stated..." + booksInput.toString());
		
		boolean validInput = validateInput(booksInput);
		
		if( !(validInput) ){
		
			Logs.warning(Logs.BOOK_UTILS, "Operation Failed, invalid input received");
			return null;
		}
		
		Map<String, List> categorizedList = new HashMap<String, List>();

		for (int counter = 0; counter < booksInput.size(); counter++) {

			Book book = booksInput.get(counter);
			String category = fetchCategory(book);

			if (category == null || category.length() <= 0) {

				//Books without category shall be stored into "Unknown" Category
				Logs.warning(Logs.BOOK_UTILS, "Category could not be found, marking it Unknown");
				category = "Unknown";
			}

			// This is to check, if particular category has already been created
			boolean resultIndex = getResultIndex(categorizedList, category);
			
			if (resultIndex) {

				Logs.information(Logs.BOOK_UTILS, "Category already exists, adding new book " + category);
				
				List categoryList = categorizedList.get(category);
				categoryList.add(book);
				
				categorizedList.put(category, categoryList);
				
			} else {
				
				Logs.information(Logs.BOOK_UTILS, "Creating new category of books " + category);
				
				List newBook = new ArrayList();
				newBook.add(book);
				
				categorizedList.put(category, newBook);
			}

		}

		return categorizedList;
	}

public void storeBooks(List booksInput) {
	
		Map<String, List> books = categorizeBooks(booksInput);
		
		if(books == null || books.size() <= 0 ){
			
			Logs.warning(Logs.BOOK_UTILS, "Operation Failed, no books found");
			return;
		}
		
		boolean isSuccess = FileUtils.writeIntoFile(books);
	}

In the above code snippet, I have tried to divide it into smaller portions of code. You might observe these methods :

– categorizeBooks(List booksInput);

– validateInput(booksInput);

– fetchCategory(book);

– getResultIndex(categorizedList, category);

– Log.information, Log.warning, ..

– FileUtils.writeIntoFile(books);

Where Log and FileUtils shall be part of generic utilities and can be utilized through out the whole application.

Entire portion of the source code could also be executed within one method but dividing it into smaller portions can be helpful for testing, bug fixing, and maintenance. You also get the benefit of reduced, compact source code by reusing the existing utility methods or libraries. Dividing your biger files into smaller chunks can lead to ‘clean code’.

GIGO (Garbage-in-garbage-out)

This is the most interesting one. You might have heard of situations where the piece of software code which was working till yesterday has stopped working now. This is a funny situation to be in.

The occurrence of such problems are very frequent. There could be different reasons for the occurrence, but most likely it is something to do with data.

Let me share the problem I recently came across.

My application at client side was configured to pull maximum 3 records at a time from the server. The data pull was happening using the greatest timestamp stored at client.

For some unknown reason, the utility which was used to store the current timestamp with each record did not work. It caused to create duplicate entries of timestamp for 7 new records.

It looked something like this:

Data 1 : Timestamp 1000
Data 2 : Timestamp 1001
Data 3 : Timestamp 1001

Data 4 : Timestamp 1001
Data 5 : Timestamp 1001
Data 6 : Timestamp 1001
Data 7 : Timestamp 1001
Data 8 : Timestamp 1001

Data 9 : Timestamp 1002
Data 10 : Timestamp 1003

EXECUTION 1 : Fetch Data > Timestamp (NULL or 0)
Since, my code could only pull 3 records at a time.
So the result : Data 1, Data 2, Data 3
Greatest Timestamp : 1001

EXECUTION 2 : Fetch Data > Timestamp 1001
So the result : Data 9, Data 10
Greatest Timestamp : 1003

You will observe that the data for records from 4, 5, 6, 7 and 8 as marked with orange color, above, couldn’t be retrieved .

It is because of the garbage entered into the database. By the time you realize the bug in the system, your database has already grown with thousands of new records. Now, these type of problems are really hard to identify.

In my situation customer wasn’t all that patient. Luckily, I observed the duplicate entries and fixed the problem. Here, if you try to solve the problem with data pull API, you may never be able to resolve the issue and it would keep on bothering you at some random intervals.

Data is a crucial component of a software system and passing garbage to the system will only result in the garbage. It is important to take care of your data towards ‘clean code’.

Code Maintenance

You might agree to the fact that majority of the successful software systems have surrounded us since substantially long time, such as iPhone released at June 29, 2007 and even some of them are around since generations such as Windows, released at 20 November 1985.

With this, we can make the judgement that it is worth talking about ‘Code Maintenance’.

Success of a software system relies on many factors. Out of which, Software Source Code plays an important role.

Though ‘Code Maintenance’ is a standard and people have it, in their software product presentations. It looks nice and beautiful.

But, you might have experienced it yourself, that, there is no place for ‘Maintenance’ when the actual coding starts. And, that’s so common to ignore because it is clearly shown in the software life-cycle as the last stage.

So, by the time maintenance starts, most likely, I won’t be there to be part of it.

Products such as iPhone or Windows are still booming the market because of their maintenance strategies. And, also because they didn’t keep on re-writing their entire software code. Rather, maintaining whatever was there.

Lets understand this with the help of the above example of “grouping books”. How a poorly written software code will be of no use after some time.

Rather than using separate libraries or utilities if I simply put everything into one method. This will definitely work, but for a limited time.
Now, as time goes source code would also be required to be updated or maintained.
Since, everything is cluttered like the books in the above example. It will be almost impossible to provide updates to the same source code. If one wants to update Log functions and file writing utilities, since it is not separated from the main operation, you might end up throwing and re-writing the same after some time.

This mistake is so horrendous that even if you spend years in writing your source code. It will be of no use at some point.

Where as, had it been a separate class/utility. It can be fairly easy to modify and all the methods utilizing this will automatically adhere to it.

History has already shown us that many good companies just got vanished because of the poorly written software code.

If we take care of all the above aspects, it can be fairly easy for people to maintain it as well. It will be rare or impossible to keep the same person engaged who has initially build it.

Conclusion

There can be many such tutorials or ideas being shared by different people as per their knowledge and expertise. But, if I tell you to keep all this aside including whatever I just shared above.

Since you are here, I assume you have already qualified the test of patience. Let me take you back to the title, I am revealing the secret of “writing clean code in one statement”.

The only statement which is ultimately going to work is this.

“a mindset, a mindset as if someone else is going to maintain your code”

This is the key.
Even before you say ‘no’, I would suggest you to try this out for few days. Share your comments about your trial, I would love to hear!

I was lucky to know this secret in the very beginning of my industrial career. This key has kept me among the best coders in the companies I worked.

The mindset has not only helped me to write beautiful software code but also pushed me to be helpful and co-operative in a team.

Don’t miss to subscribe, I will be sharing more contents on software programming practices.

If you haven’t tried the ‘Code Generator’ as yet, I would suggest you do. It not only gives you a source code which is properly formatted or clean code in a manner, but also helps you save your time in writing so much of source code. Click here for free download.

0

34 thoughts on “Write Clean Code in one Statement

  1. Wonderful web site. A lot of useful information here. I am sending it to some buddies ans also sharing in delicious.
    And certainly, thanks on your sweat!

    1+
  2. whoah this blog is wonderful i love reading your articles.
    Stay up the great work! You understand, lots of individuals are hunting around for this information,
    you could aid them greatly.

    0
  3. Greetings! I know this is somewhat off topic but I was wondering if you knew
    where I could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having trouble finding
    one? Thanks a lot.!

    0
  4. Pretty section of content. I just stumbled upon your weblog and
    in accession capital to assert that I acquire actually enjoyed account your blog
    posts. Anyway I’ll be subscribing to your augment and
    even I achievement you access consistently quickly

    0
  5. I’m not that much of a internet reader to be honest but your blogs really nice, keep it up!
    I’ll go ahead and bookmark your site to come back in the
    future. Cheers

    0
  6. Hello there, You’ve done an excellent job. I will definitely digg it and personally
    suggest to my friends. I am sure they’ll be benefited from this web
    site.

    0

Leave a Reply

Your email address will not be published. Required fields are marked *