Breaking methods down into less than five lines is generally a sign that you have gone a bit too far (But not always!). This Software Engineering post is a good overview.
Instead of breaking your methods into userInputWidth
and userInputHeight
, I would recommend creating a helper method named getPositiveInput
that accepts a prompt string and using that instead.
For example:
private double getPositiveInput(String prompt) {
Scanner reader = new Scanner(System.in);
double result;
do {
System.out.println(prompt);
result = reader.nextDouble();
if (result <= 0) {
System.out.println("Enter a number greater than zero.");
}
} while (result <= 0)
return result;
}
This makes it possible to reduce the duplication of your code without breaking your methods down so far that you have to have one for every property on your class.
The trick is what the definition of "one task" is. Deciding what each method should do to keep the code modular is made much easier by experience. I've found the following guidelines help.
- Describe the method out loud, if you say "and" or "then" more than once, the method is probably doing too much and should be split up.
- If you say the same thing for more than one method, extract the code that does that thing into it's own method.
- If you catch yourself copy/pasting code stop and put it in a method.
Here's an example:
Given the following code (combined your methods to get what I presume was the original method), here's how I would describe the method.
private void userInputDimensions() {
Scanner reader = new Scanner(System.in);
double loopCondition = 0;
while (loopCondition <= 0) {
System.out.println("Please enter the width of the rectangle ");
double nextDouble = reader.nextDouble();
loopCondition = nextDouble;
if (nextDouble <= 0) {
System.out.println("Enter a number greater than zero.");
} else {
this.rectangleWidth = nextDouble;
break;
}
}
loopCondition = 0;
while (loopCondition <= 0) {
System.out.println("Please enter the length of the rectangle");
double nextDouble = reader.nextDouble();
loopCondition = nextDouble;
if (nextDouble <= 0) {
System.out.println("Enter a number greater than zero.");
} else {
this.rectangleLength = nextDouble;
break;
}
}
}
- Prompt the user for the width of the rectangle until they enter a number greater than zero
- Set the rectangleWidth to the number
- Prompt the user for the length of the rectangle until they enter a number greater than zero
- Set the rectangleLength to the number
Notice that the duplicate "code" here is the prompt and validation input. By contrast, consider the following code using the getPositiveInput
method.
private void userInputDimensions() {
this.rectangleWidth = this.getPositiveInput("Please enter the width of the rectangle");
this.rectangleLength = this.getPositiveInput("Please enter the length of the rectangle");
}
This method can be described by "set the width and length of the rectangle to the user input" and does not need to be broken down further.