Skip to content

Commit e8da28d

Browse files
committed
Updating approach bob
1 parent b017e6c commit e8da28d

File tree

6 files changed

+88
-179
lines changed

6 files changed

+88
-179
lines changed

exercises/practice/bob/.approaches/config.json

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,29 @@
44
"bobahop"
55
],
66
"contributors": [
7-
"jagdish-15"
7+
"jagdish-15",
8+
"kahgoh"
89
]
910
},
1011
"approaches": [
1112
{
1213
"uuid": "6ca5c7c0-f8f1-49b2-b137-951fa39f89eb",
13-
"slug": "method-based",
14-
"title": "Method based",
15-
"blurb": "Uses boolean functions to check conditions",
14+
"slug": "if-statements",
15+
"title": "if statements",
16+
"blurb": "Use if statements to return the answer.",
1617
"authors": [
1718
"jagdish-15"
1819
],
1920
"contributors": [
20-
"BenjaminGale"
21+
"BenjaminGale",
22+
"kahgoh"
2123
]
2224
},
2325
{
2426
"uuid": "323eb230-7f27-4301-88ea-19c39d3eb5b6",
25-
"slug": "if-statements",
26-
"title": "if statements",
27-
"blurb": "Use if statements to return the answer.",
27+
"slug": "nested-if-statements",
28+
"title": "nested if statements",
29+
"blurb": "Use nested if statements to return the answer.",
2830
"authors": [
2931
"bobahop"
3032
]
Lines changed: 54 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,88 +1,86 @@
11
# `if` statements
22

33
```java
4-
import java.util.function.Predicate;
5-
import java.util.regex.Pattern;
6-
74
class Bob {
8-
9-
final private static Pattern isAlpha = Pattern.compile("[a-zA-Z]");
10-
final private static Predicate < String > isShout = msg -> isAlpha.matcher(msg).find() && msg == msg.toUpperCase();
11-
12-
public String hey(String message) {
13-
var speech = message.trim();
14-
if (speech.isEmpty()) {
15-
return "Fine. Be that way!";
16-
}
17-
var questioning = speech.endsWith("?");
18-
var shouting = isShout.test(speech);
19-
if (questioning) {
20-
if (shouting) {
21-
return "Calm down, I know what I'm doing!";
22-
}
23-
return "Sure.";
24-
}
25-
if (shouting) {
5+
String hey(String input) {
6+
var inputTrimmed = input.trim();
7+
8+
if (isSilent(inputTrimmed))
9+
return "Fine. Be that way!";
10+
if (isShouting(inputTrimmed) && isQuestioning(inputTrimmed))
11+
return "Calm down, I know what I'm doing!";
12+
if (isShouting(inputTrimmed))
2613
return "Whoa, chill out!";
27-
}
14+
if (isQuestioning(inputTrimmed))
15+
return "Sure.";
16+
2817
return "Whatever.";
2918
}
19+
20+
private boolean isShouting(String input) {
21+
return input.chars()
22+
.anyMatch(Character::isLetter) &&
23+
input.chars()
24+
.filter(Character::isLetter)
25+
.allMatch(Character::isUpperCase);
26+
}
27+
28+
private boolean isQuestioning(String input) {
29+
return input.endsWith("?");
30+
}
31+
32+
private boolean isSilent(String input) {
33+
return input.length() == 0;
34+
}
3035
}
3136
```
3237

33-
In this approach you have a series of `if` statements using the private methods to evaluate the conditions.
34-
As soon as the right condition is found, the correct response is returned.
38+
In this approach, the different conditions for Bob’s responses are separated into dedicated private methods within the `Bob` class. This method-based approach improves readability and modularity by organizing each condition check into its own method, making the main response method easier to understand and maintain.
3539

36-
Note that there are no `else if` or `else` statements.
37-
If an `if` statement can return, then an `else if` or `else` is not needed.
38-
Execution will either return or will continue to the next statement anyway.
40+
## Explanation
3941

40-
The `String` [`trim()`][trim] method is applied to the input to eliminate any whitespace at either end of the input.
41-
If the string has no characters left, it returns the response for saying nothing.
42+
This approach simplifies the main method `hey` by breaking down each response condition into helper methods:
4243

43-
~~~~exercism/caution
44-
Note that a `null` `string` would be different from a `String` of all whitespace.
45-
A `null` `String` would throw a `NullPointerException` if `trim()` were applied to it.
46-
~~~~
44+
### Trimming the Input
4745

48-
A [Pattern][pattern] is defined to look for at least one English alphabetic character.
46+
The `input` is trimmed using the `String` [`trim()`][trim] method to remove any leading or trailing whitespace. This helps to accurately detect if the input is empty and should prompt a `"Fine. Be that way!"` response.
4947

50-
The first half of the `isShout` [Predicate][predicate]
48+
### **Delegating to Helper Methods**:
49+
50+
Each condition is evaluated using the following helper methods:
5151

52-
```java
53-
isAlpha.matcher(msg).find() && msg == msg.toUpperCase();
54-
```
52+
- **`isSilent`**: Checks if the trimmed input has no characters.
53+
- **`isShouting`**: Checks if the input is all uppercase and contains at least one alphabetic character, indicating shouting.
54+
- **`isQuestioning`**: Verifies if the trimmed input ends with a question mark.
55+
56+
This modular approach keeps each condition encapsulated, enhancing code clarity.
5557

56-
is constructed from the `Pattern` [`matcher()`][matcher-method] method and the [`Matcher`][matcher] [`find()`][find] method
57-
to ensure there is at least one letter character in the `String`.
58-
This is because the second half of the condition tests that the uppercased input is the same as the input.
59-
If the input were only `"123"` it would equal itself uppercased, but without letters it would not be a shout.
58+
### **Order of Checks**:
59+
60+
The order of checks within `hey` is important:
61+
- Silence is evaluated first, as it requires an immediate response.
62+
- Shouted questions take precedence over individual checks for yelling and asking.
63+
- Yelling comes next, requiring its response if not combined with a question.
64+
- Asking (a non-shouted question) is checked afterward.
6065

61-
A question is determined by use of the [`endsWith()`][endswith] method to see if the input ends with a question mark.
66+
This ordering ensures that Bob’s response matches the expected behavior without redundancy.
6267

6368
## Shortening
6469

65-
When the body of an `if` statement is a single line, both the test expression and the body _could_ be put on the same line, like so
70+
When the body of an `if` statement is a single line, both the test expression and the body _could_ be put on the same line, like so:
6671

6772
```java
68-
if (speech.isEmpty()) return "Fine. Be that way!";
73+
if (isSilent(inputTrimmed)) return "Fine. Be that way!";
6974
```
7075

71-
or the body _could_ be put on a separate line without curly braces
76+
or the body _could_ be put on a separate line without curly braces:
7277

7378
```java
74-
if (speech.isEmpty())
79+
if (isSilent(inputTrimmed))
7580
return "Fine. Be that way!";
7681
```
7782

78-
However, the [Java Coding Conventions][coding-conventions] advise to always use curly braces for `if` statements, which helps to avoid errors.
79-
Your team may choose to overrule them at its own risk.
83+
However, the [Java Coding Conventions][coding-conventions] advise always using curly braces for `if` statements, which helps to avoid errors. Your team may choose to overrule them at its own risk.
8084

81-
[trim]: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()
82-
[pattern]: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
83-
[predicate]: https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html
84-
[matcher]: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html
85-
[matcher-method]: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#matcher-java.lang.CharSequence-
86-
[find]: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#find--
87-
[endswith]: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#endsWith(java.lang.String)
85+
[trim]: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()
8886
[coding-conventions]: https://www.oracle.com/java/technologies/javase/codeconventions-statements.html#449
Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
if (questioning) {
2-
if (shouting)
3-
return "Calm down, I know what I'm doing!";
4-
return "Sure.";
5-
}
6-
if (shouting)
1+
if (isSilent(inputTrimmed))
2+
return "Fine. Be that way!";
3+
if (isShouting(inputTrimmed) && isQuestioning(inputTrimmed))
4+
return "Calm down, I know what I'm doing!";
5+
if (isShouting(inputTrimmed))
76
return "Whoa, chill out!";
8-
return "Whatever.";
7+
if (isQuestioning(inputTrimmed))
8+
return "Sure.";

exercises/practice/bob/.approaches/introduction.md

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
In this exercise, we’re working on a program to determine Bob’s responses based on the tone and style of given messages. Bob responds differently depending on whether a message is a question, a shout, both, or silence. Various approaches can be used to implement this logic efficiently and cleanly, ensuring the code remains readable and easy to maintain.
44

5-
## General Guidance
5+
## General guidance
66

77
When implementing your solution, consider the following tips to keep your code optimized and idiomatic:
88

@@ -13,7 +13,7 @@ When implementing your solution, consider the following tips to keep your code o
1313
- **Return Statements**: An early return in an `if` statement eliminates the need for additional `else` blocks, making the code more readable.
1414
- **Curly Braces**: While optional for single-line statements, some teams may require them for readability and consistency.
1515

16-
## Approach: Method-Based
16+
## Approach: `if` statements
1717

1818
```java
1919
class Bob {
@@ -22,25 +22,25 @@ class Bob {
2222

2323
if (isSilent(inputTrimmed))
2424
return "Fine. Be that way!";
25-
if (isYelling(inputTrimmed) && isAsking(inputTrimmed))
25+
if (isShouting(inputTrimmed) && isQuestioning(inputTrimmed))
2626
return "Calm down, I know what I'm doing!";
27-
if (isYelling(inputTrimmed))
27+
if (isShouting(inputTrimmed))
2828
return "Whoa, chill out!";
29-
if (isAsking(inputTrimmed))
29+
if (isQuestioning(inputTrimmed))
3030
return "Sure.";
3131

3232
return "Whatever.";
3333
}
3434

35-
private boolean isYelling(String input) {
35+
private boolean isShouting(String input) {
3636
return input.chars()
3737
.anyMatch(Character::isLetter) &&
3838
input.chars()
3939
.filter(Character::isLetter)
4040
.allMatch(Character::isUpperCase);
4141
}
4242

43-
private boolean isAsking(String input) {
43+
private boolean isQuestioning(String input) {
4444
return input.endsWith("?");
4545
}
4646

@@ -50,9 +50,9 @@ class Bob {
5050
}
5151
```
5252

53-
This approach defines helper methods for each type of message—silent, yelling, and asking—to keep each condition clean and easily testable. For more details, refer to the [Method-Based Approach][approach-method-based].
53+
This approach defines helper methods for each type of message—silent, shouting, and questioning—to keep each condition clean and easily testable. For more details, refer to the [`if` Statements Approach][approach-if].
5454

55-
## Approach: `if` Statements
55+
## Approach: nested `if` statements
5656

5757
```java
5858
import java.util.function.Predicate;
@@ -84,9 +84,9 @@ class Bob {
8484
}
8585
```
8686

87-
This approach utilizes nested `if` statements and a predicate for determining if a message is a shout. For more details, refer to the [`if` Statements Approach][approach-if].
87+
This approach utilizes nested `if` statements and a predicate for determining if a message is a shout. For more details, refer to the [nested `if` Statements Approach][approach-nested-if].
8888

89-
## Approach: Answer Array
89+
## Approach: answer array
9090

9191
```java
9292
import java.util.function.Predicate;
@@ -118,17 +118,17 @@ This approach uses an array of answers and calculates the appropriate index base
118118

119119
## Which Approach to Use?
120120

121-
Choosing between the method-based approach, `if` statements, and answer array approach can come down to readability and maintainability. Each has its advantages:
121+
The choice between the **`if` Statements Approach**, **Nested `if` Statements Approach**, and the **Answer Array Approach** depends on readability, maintainability, and efficiency:
122122

123-
- **Method-Based**: Clear and modular, great for readability.
124-
- **`if` Statements**: Compact and straightforward.
125-
- **Answer Array**: Minimizes condition checks by using indices, efficient for a variety of responses.
123+
- **`if` Statements Approach**: This is clear and easy to follow but checks conditions multiple times, potentially affecting performance. Storing results in variables like `questioning` and `shouting` can improve efficiency but may reduce clarity slightly.
124+
- **Nested `if` Statements Approach**: This approach can be more efficient by avoiding redundant checks, but its nested structure can reduce readability and maintainability.
125+
- **Answer Array Approach**: Efficient and compact, this method uses an array of responses based on flags for questioning and shouting. However, it may be less intuitive and harder to modify if more responses are needed.
126126

127-
Experiment with these approaches to find the balance between readability and performance that best suits your needs.
127+
Each approach offers a balance between readability and performance, with trade-offs in flexibility and clarity.
128128

129129
[trim]: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()
130130
[endswith]: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#endsWith(java.lang.String)
131131
[dry]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
132-
[approach-method-based]: https://exercism.org/tracks/java/exercises/bob/approaches/method-based
132+
[approach-nested-if]: https://exercism.org/tracks/java/exercises/bob/approaches/nested-if-statements
133133
[approach-if]: https://exercism.org/tracks/java/exercises/bob/approaches/if-statements
134134
[approach-answer-array]: https://exercism.org/tracks/java/exercises/bob/approaches/answer-array

exercises/practice/bob/.approaches/method-based/content.md

Lines changed: 0 additions & 83 deletions
This file was deleted.

exercises/practice/bob/.approaches/method-based/snippet.txt

Lines changed: 0 additions & 8 deletions
This file was deleted.

0 commit comments

Comments
 (0)