-
Notifications
You must be signed in to change notification settings - Fork 1
DRY Code
Tstream edited this page Apr 26, 2017
·
1 revision
DRY stands for Don't Repeat Yourself and is a principal in computer science aimed at reducing repetition of information/code.
- the same chonk of code should not be repeated over and over again.
- if there is repetition in your code, the repeated code can most likely be put into a separate function that can the called where ever needed
Repeated Code Example 1:
public void example_one(){
int[] array_a = {1,2,3,4,5,6,7,8,9};
int sum_a = 0;
int average_a = 0;
for (int i = 0; i < array_a.length; i++){
sum_a += array_a[i];
}
average_a = sum_a / array_a.length;
int[] array_b = {2,4,6,8,10,12,14,16,18};
int sum_b = 0;
int average_b = 0;
for (int i = 0; i < array_a.length; i++){
sum_b += array_b[i];
}
average_b = sum_b / array_b.length;
}Repeated Code Example 2:
public void exampleTwo(int amount, String type){
double finalAmount = 0.0;
String displayAmount = "";
switch (type.toUpperCase()) {
case "CEO":
finalAmount = (amount - (0.9 * amount)) - 0.99 * (amount - (0.9 * amount));
DecimalFormat df=new DecimalFormat("0.00");
displayAmount = df.format(finalAmount);
break;
case "MGR":
finalAmount = (amount - (0.4 * amount)) - 0.50 * (amount - (0.4 * amount));
DecimalFormat df=new DecimalFormat("0.00");
displayAmount = df.format(finalAmount);
break;
case "AMRG":
finalAmount = (amount - (0.4 * amount)) - 0.50 * (amount - (0.4 * amount));
DecimalFormat df=new DecimalFormat("0.00");
displayAmount = df.format(finalAmount);
break;
case "SE":
finalAmount = (amount - (0.2 * amount)) - 0.25 * (amount - (0.2 * amount));
DecimalFormat df=new DecimalFormat("0.00");
displayAmount = df.format(finalAmount);
break;
case "JE":
finalAmount = (amount - (0.2 * amount)) - 0.15 * (amount - (0.2 * amount));
DecimalFormat df=new DecimalFormat("0.00");
displayAmount = df.format(finalAmount);
break;
case "LC":
finalAmount = (amount - (0.1 * amount)) - 0.10 * (amount - (0.1 * amount));
DecimalFormat df=new DecimalFormat("0.00");
displayAmount = df.format(finalAmount);
break;
case "FF":
finalAmount = (amount - (0.1 * amount)) - 0.10 * (amount - (0.1 * amount));
DecimalFormat df=new DecimalFormat("0.00");
displayAmount = df.format(finalAmount);
break;
default:
finalAmount = amount;
DecimalFormat df=new DecimalFormat("0.00");
displayAmount = df.format(finalAmount);
break;
}
}