home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
lect08b
booleans
We will talk about the hw briefly.
We mentioned last time, that
boolean is just another type,
and we can do the same things with it as with other types:
make variables to hold booleans,
write methods which return a boolean,
and
write methods with boolean parameters.
Here are exapmles:
-
Methods returning a boolean: We must register for selective service
if we are 18 or older, and less than 26.
boolean mustRegisterForSS( int age ).
(In math we might write “a ≤ x < b”;
we can make our Java code look similar, by writing
the inequalities in the same order.)
-
Methods taking in a boolean:
boolean mustRegisterForSS( int age, boolean isMale ).
-
What if a law is passed so that
females must also register for selective service,
but use the age bracket 19 to 26, instead of 18 to 25?
Thoughts:
We could either use one big boolean expression,
or we could use boolean expressions mixed
with if-else — which do you prefer?
Can we be clever, and instead first calculate an age-offset (1yr, in
the case shown),
for men vs. women?
Is this approach better?
Your answer might depend on which of the two scenarios
you thought more likely:
-
Perhaps women's eligibility for selective service might be changed
to be fewer or more years than men.
-
Perhaps,
women's eligibility for selective service might be changed
to different initial-age,
but would always be the same number of years as for men.
Good code reflects how you think about the problem!
-
The book has a similar problem regarding income-tax rates
(section textbook),
which depends on ones income
as well as whether one is filing jointly.
-
You'll notice the book uses named constants,
such as
private static final double RATE1 = 0.15;
|
What are the advantages of using named constants in the program?
One guideline for good programming:
No magic numbers.
A “magic number” is a literal number in the code
which makes the the code work “like magic”, if you
don't already happen to know what the number means.
Compare:
6.28318 * r
2 * 3.14159 * r
2 * Math.PI * r
|
Even when we know the constant isn't ever going to be
changed/modified, giving it a name is still helpful!
(Note that 0, 1, and often 2 are not usually considered
magic numbers.)
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs