Notes: 07. Use Number Methods
At this point, you’ve simplified your algorithm to calculate the difference down to a few lines of code. That’s good, but we can do even better.
It turns out that in Dart, numbers like integers are objects. This differs from other languages like Java, where number types are known as what is called “primitive types”.
Since numbers are objects, it means we can call methods on them.
One handy method included in the dart core libraries is a method to get the absolute value of a number. Both of these expression shown here evaluate to positive 42.
In this exercise, we’ll finalize our revisions to the difference algorithm. Let’s dive in!
Okay, to get started, open your project in progress or download the starter project for this episode. Open up main.dart and scroll down to the _pointsForCurrentRound method.
We’re going to use a method called abs meaning absolute value. The absolute value is the distance from zero on the number line so the number is always positive.
Update the method to the following:
int _pointsForCurrentRound() {
const int maximumScore = 100;
int difference = _model.target - _model.current;
return maximumScore - difference;
}
Now we want to get the absolute value of the target minus the current. To do this, we wrap the expression in parenthesis.
int difference = (_model.target - _model.current);
Now we call the abs method on the parenthesis itself.
int difference = (_model.target - _model.current).abs();
When this line is evaluated, the current value is subtracted from the target value. After which, the abs method is called on the resulting number.
And that’s it - we’ve simplified our code down to one line and made it easier to read in the process. That’s a net win. Nice work!