How to write clean Java code

One of the fundamental aspects that I have learnt progressively over time as a software engineer is the value of clean code. Honestly I never realized the value when I was only a junior programmer. But now looking back I realize - how critically important for a tech savvy company to have clean code to minimize the technical debt over time.

So in this blog, I am going to present some very basic but really helpful tips to write clean code. So here you go:

If a code is written with such intention revealing names, it is always very easy to find out bug from existing code and also easier to maintain such code by a new team and hence the technical debt and overall cost of ownership goes down.

Let me try to explain this to you with some example:

	public class OCPTester {
	
	private Vehicle vehicle;
	public void Vehicle(Vehicle vehicle) {
		this.vehicle= vehicle;
	}
		move() {
			if ((vehicle) instanceOf  (Train)) {
				....
			} else if ((vehicle) instanceOf (Tram)) {
				....
			}  else if ((vehicle) instanceOf (Bus)) {
				....
			}
		}
	}

	public subclass Train extends Vehicle {
	}
	public subclass Tram extends Vehicle {
	}
		public subclass Bus extends Vehicle {
	}	

Main problem of the above code is that the superclass Vehicle knows about the subclasses and it contains logic (within the move method) about the subclass behaviour. This is very bad because if new subclasses (new vehcle types like plane) are added in future, the superclass needs to change. So the above logic should be re-factored as below:

public class OCPTester {
	private Vehicle vehicle;
	public void Vehicle(Vehicle vehicle) {
		this.vehicle= vehicle;
	}
	move() {
		vehicle.run();
	}
}

	public subclass Train extends Vehicle {
		run (){
		}
	}

	public subclass Tram extends Vehicle {
		run (){
		}
	}
	
	public subclass Bus extends Vehicle {
		run (){
		}
	}	

So essentially what we have done is that we have moved out the logic to the corresponding sub classes where it should ideally reside.