WHY?
The following code is:
- unreadable
- very long
void start () {
double myLength = 1.90;
double lengthJohn = 1.80;
boolean iAmBigger = false;
if (myLength > lengthJohn) {
iAmBigger = true;
}
double lengthFrank = 1.70;
if (myLength > lengthFrank) {
iAmBigger = true;
} else {
iAmBigger = false;
}
double lengthJimmy = 1.60;
if (myLength > lengthJimmy) {
iAmBigger = true;
} else {
iAmBigger = false;
}
if(iAmBigger == true) {
System.out.println("I am Bigger");
} else {
System.out.println("I am not");
}
}
Working with methods would result in this:
static final double MYLENGTH = 1.90;
void compareLengths(double inputLength) {
if(MYLENGTH > inputLength) {
System.out.println("I am Larger");
} else {
System.out.println("I am not");
}
}
void start () {
double lengthJohn = 1.90;
double lengthFrank = 1.60;
double lengthJimmy = 1.70;
compareLengths(lengthJohn);
compareLengths(lengthFrank);
compareLengths(lengthJimmy);
}
extra
you can also optimise the code:
static final double MYLENGTH = 1.90;
void compareLengths(double inputLength) {
if (MYLENGTH > inputLength) {
System.out.println("I am Larger");
} else {
System.out.println("I am not");
}
}
void start () {
double lengthJohn = 1.90, lengthFrank = 1.60, lengthJimmy = 1.70;
compareLengths(lengthJohn);
compareLengths(lengthFrank);
compareLengths(lengthJimmy);
}