CodesJava

Easy learning with example program codes

DRY (Don’t repeat yourself) in java

DRY object-oriented design principle refers to don’t repeat yourself. In programming it means don’t write the same code repeatedly. If we have a block of code at two or more places than to place it in a separate method. For constants if we are using a hard-coded value at two or more places than make them public final constant.

Let us understand the DRY principle with help of below example. In the below example we have a Mechanic class which services bus and cars.

Example:

 public class Mechanic {
	public void serviceBus() {
		System.out.println("Servicing bus now");
	}
	public void serviceCar() {
		System.out.println("Servicing car now");
	}
}

Mechanic class have two methods serviceBus() and serviceCar() which will perform respective tasks. Now consider the case when workshop is offering you other services like washing the vehicle after service. After updating the code in Mechanic class.

public class Mechanic {
	public void serviceBus() {
		System.out.println("Servicing bus now");
                //Process washing
	}
	public void serviceCar() {
		System.out.println("Servicing car now");
                //Process washing
	}
}

As we can see washing processing code is duplicate. We can put this code in a separate method and use it wherever required.

public class Mechanic {
	public void serviceBus() {
		System.out.println("Servicing bus now");
                washVehicle();
	}
	public void serviceCar() {
		System.out.println("Servicing car now");
                washVehicle();
	}
        public void washVehicle() {
               //Process washing
	}
}
Please follow and like us:








Copyright © 2019 CodesJava DMCA.com Protection Status