Number helpers
- Dart course
- Intermediate
- Lesson 15/116
- 6 min
Add number conversion and calculation methods.
The clamp method
We'll write a clamp method to keep a number in a given range. If the number is below the range it returns the lower bound, if above it returns the upper bound, otherwise it returns itself.
Example: clamp(15, 0, 10) gives 10 because 15 is greater than 10. clamp(-3, 0, 10) gives 0 because -3 is less than 0. clamp(5, 0, 10) gives 5. This helper fits user input, percentage calculation and graphic positioning.
Conditional return
The clamp method starts with two if statements; each checks one bound. If the condition holds, return gives back the relevant bound. Finally the value itself is returned.
Example: if (value < min) return min; if (value > max) return max; return value;. The first two conditions catch lower and upper bound violations; the last line covers the case where the value is within the range. This shape works cleanly without an extra else when the value is in range. return exits the method immediately, so later lines do not run.
Practice Add clamp to Helper
Keep the existing Helper class. Add an int clamp(int value, int min, int max) method to the class. In the body write if (value < min) return min;, if (value > max) return max; and return value;. In main, create an instance with var h = Helper(); and call print(h.clamp(15, 0, 10)).
Starter code
class Helper {
final String version;
Helper() : version = '1.0';
String slugify(String text) {
return text.toLowerCase().replaceAll(' ', '-');
}
}
void main() {
var h = Helper();
print(h.slugify('Hello World'));
}
// Add the clamp method and call it on an instanceSample solution
class Helper {
final String version;
Helper() : version = '1.0';
String slugify(String text) {
return text.toLowerCase().replaceAll(' ', '-');
}
int clamp(int value, int min, int max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
}
void main() {
var h = Helper();
print(h.clamp(15, 0, 10));
}Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the clamp signature
int clamp(int value, int min, ____) {
if (value < min) return min;
if (value > max) return max;
return value;
}
int clamp(int value, int min, int max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
Explanation: int max holds the upper bound value.
2 What does clamp(15, 0, 10) return?
- 0
- 5
- 10 Correct answer
- 15
Explanation: Since 15 is greater than the upper bound 10, clamp returns 10.
3 Match the clamp parts
| Term | Meaning |
|---|---|
clamp |
Method name |
min |
Lower bound |
max |
Upper bound |