Writing Clean Code – List of things you can do to make your code clean

Writing readable, maintainable and clean code has been my passion both as a developer and as a mentor guiding other fellow developers. With clean code, I have been able to throw so much garbage that I have actually reduced the lines of code that we have in the system significantly. This list is just a tip of iceberg in what you can do to make your code clean, but is a good start for those who seek to be better developers.

In now way I am imposing these as a standards. Situation could be different with different developers and organizations and the same rule of thumb might not apply for all.
Clean code features:

  1. Code should have a straightforward logic, no unnecessary twists and turns.
  2. No nests for bugs to hide. If you write a bad code, it’s a sweet home for the bugs to get born and grow.
  3. Code should have reduced or minimized dependency. Heavily dependent code is not clean, it’s a mess.
  4. Proper error handling strategy. Don’t let your code fail everywhere.
  5. Tuned for performance. No code is clean and good if it takes forever to run.
  6. Efficiency is the key.
  7. Leaves no broken windows (Dave Thomas and Andy Hunt). If you leave a bad code, chances are there will be more sprouts of bad codes.
  8. No Memory Leaks
  9. Consistent and meaningful Naming
  10. Clean code should do one thing and that one thing should be done well (Bjarne). Bad code tries to do too much stuffs at a time and leaves rooms for inefficiencies, maintenance horrors etc.
  11. Classes, functions or modules need to be unpolluted. They should contain only what is absolutely necessary. Don’t leave the unused variables, and objects around.
  12. Readability: Clean code should read like well written prose. There should be proper indentation etc. Huge list can go in this topic. But you might guessed what I am talking about.
  13. Understandability: The code should be easy to read and understand. Avoid the abbreviated variables, class names or methods.
  14. Should have proper unit tests. Code coverage matters. Although 100% code coverage is not practicable, the unit test code coverage should be as high as possible. But don’t focus on the coverage percentage, focus on what you are testing. Do not write test cases for just covering the code. Write the test cases that test the intent.
  15. All the unit tests that are written for the code should pass. Don’t leave the failing unit tests in your code.
  16. Should have proper acceptance test criteria.
  17. Any exposed interfaces and APIs must be clear and minimal
  18. Clean code should be easily maintainable by the non-original developers
  19. Clean code should be the code that has been taken care of (Michael Feathers)
  20. Should have reduced number of entities (objects, classes, methods, modules etc.)
  21. Should not have redundant logic scattered around the code.
  22. Should follow the Boy Scout Rule – ‘Leave the campground cleaner than you found it.’ This means, if you find a bad code around the classes and methods that you are writing, don’t curse the original author. Clean the code right away, so you have one less mess in your code.

Read XML File In JAVA using DOM – A Simple Tutorial

This tutorial is about reading xml file in a java program using the DOM (Document Object Model).

The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Objects under the DOM (also sometimes called “Elements”) may be specified and addressed according to the syntax and rules of the programming language used to manipulate them. The rules for programming and interacting with the DOM are specified in the DOM Application Programming Interface (API).

The sample XML document which the program will be reading is:

<?xml version="1.0"?>
<MyProduct>
  <Product>
    <ProductId>123</ProductId>
    <Description>Laptop</Description>
    <Price>$870</Price>
    <Quantity>1</Quantity>
    <Size>1</Size>
    <Total>$870</Total>
  </Product>
  <Product>
    <ProductId>124</ProductId>
   <Description>Monitor</Description>
   <Price>$200</Price>
   <Quantity>3</Quantity>
   <Size>4</Size>
   <Total>$600</Total>
   </Product>
</MyProduct>

The following is a java class that will read the XML file above.

package com.kushal.utils;
/**
 * Read XML File Using Java
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 21st July 2009
 */
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXMLFile {

public static void main(String argv[]) {

try {

File file = new File("c:/temp/MyProduct.xml");

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();

System.out.println("Root: "
+ doc.getDocumentElement().getNodeName() + "n");
NodeList nodeLst = doc.getElementsByTagName("Product");

for (int i = 0; i < nodeLst.getLength(); i++) {

Node myNode = nodeLst.item(i);

if (myNode.getNodeType() == Node.ELEMENT_NODE) {
/** Product ID* */
Element productElement = (Element) myNode;
NodeList productIdList = productElement
.getElementsByTagName("ProductId");
Element productIdElement = (Element) productIdList.item(0);
NodeList productId = productIdElement.getChildNodes();
System.out.println("Product ID : "
+ ((Node) productId.item(0)).getNodeValue());

/** Product Description* */
NodeList productDescriptionList = productElement
.getElementsByTagName("Description");
Element productDescriptionElement = (Element) productDescriptionList
.item(0);
NodeList productDescription = productDescriptionElement
.getChildNodes();
System.out.println("Product Description : "
+ ((Node) productDescription.item(0))
.getNodeValue());

/** Price* */
NodeList priceList = productElement
.getElementsByTagName("Price");
Element priceElement = (Element) priceList.item(0);
NodeList price = priceElement.getChildNodes();
System.out.println("Price : "
+ ((Node) price.item(0)).getNodeValue());

/** Quantity* */
NodeList quantityList = productElement
.getElementsByTagName("Quantity");
Element quantityElement = (Element) quantityList.item(0);
NodeList quantity = quantityElement.getChildNodes();
System.out.println("Quantity : "
+ ((Node) quantity.item(0)).getNodeValue());

/** Size* */
NodeList sizeList = productElement
.getElementsByTagName("Size");
Element sizeElement = (Element) sizeList.item(0);
NodeList size = sizeElement.getChildNodes();
System.out.println("Size : "
+ ((Node) size.item(0)).getNodeValue());

/** Total* */
NodeList totalList = productElement
.getElementsByTagName("Total");
Element totalElement = (Element) totalList.item(0);
NodeList total = totalElement.getChildNodes();
System.out.println("Total : "
+ ((Node) total.item(0)).getNodeValue());

System.out.println();

}

}
} catch (Exception e) {
e.printStackTrace();
}
}
}

===============================

Here is the output of this program.

Root: MyProduct
Product ID : 123
Product Description : Laptop
Price : $870
Quantity : 1
Size : 1
Total : $870

Product ID : 124
Product Description : Monitor
Price : $200
Quantity : 3
Size : 4
Total : $600


I received some comments on one of the posts about using POI to write to excel format. One of my blog users asked me how to read a XML document and then write to an EXCEL format.

  • You can use this post to see how the XML file is being read.
  • After reading the XML file you can store those values in a domain object, you can create any Product object with various attributes (id, description, price, quantity, size and total as field). You can store these objects in an array because there will be various products defined within a single XML file (two in above sample).
  • Once you have an array of objects, you can use my previous tutorial to write those values back to Excel Format

US 5 and 9 Digits Zip Code Validation In Java Using Regular Expressions

ZIP codes are a system of postal codes used by the United States Postal Service (USPS) since 1963. The term ZIP, an acronym for Zone Improvement Plan, is properly written in capital letters and was chosen to suggest that the mail travels more efficiently, and therefore more quickly, when senders use the code in the postal address. The basic format consists of five decimal numerical digits. An extended ZIP+4 code, introduced in the 1980s, includes the five digits of the ZIP code, a hyphen, and four more digits that determine a more precise location than the ZIP code alone. The term ZIP code was originally registered as a servicemark (a type of trademark) by the U.S. Postal Service, but its registration has since expired. [Wikipedia / Creative Commons]

The following java class uses the regular expressions to validate the zip code. It also has tests for various sample valid and invalid zip codes.

package com.kushal.tools;
/**
 * @author Kushal Paudyal
 * Last Modified on 2010/12/12
 * www.sanjaal.com/java
 * This class demonstrates the use of regular expressions to validate US Zip code.
 * It basically validates two rules:
 * - Zip code should have five digits initially.
 * - The last four digits along with the hyphen sign are optional and can be present or absent from the zip code.
 */
import java.util.regex.Pattern;

public class ZipcodeValidatorUS {
	/**
	 * Regular Expression to match the US Zip-Code
	 */
	static final String regex = "^\d{5}(-\d{4})?$";

	/**
	 * Testing the zip code validation with some sample zip codes
	 */
	public static void main(String args[]) {

		String mixedZips[] = { 	"50266-234A", "50266-2342", "5026A-2344",
								"5026A-234A", "50266", "230" };

		int index = 0;
		boolean isMatch = false;
		while (index < mixedZips.length) {
			isMatch = isAValidZipCode(mixedZips[index]);
			System.out.println("Zip " + mixedZips[index] + " - "
					+ (isMatch ? "Valid" : "Invalid"));
			index++;
		}

	}
	
	/**
	 * This method returns true if the parameter string is a valid zip code
	 */
	public static boolean isAValidZipCode(String zip) {
		return Pattern.matches(regex, zip);
	}

}

The following is the output of this program:

Zip 50266-234A - Invalid
Zip 50266-2342 - Valid
Zip 5026A-2344 - Invalid
Zip 5026A-234A - Invalid
Zip 50266 - Valid
Zip 230 - Invalid