Tate Hsumsor wrote:I've been writing a fraction class...
Oddly enough, I did exactly the same thing a few years back, except with BigInteger's, so here's a few suggestions for you:
1. Consider implementing
Comparable<Fraction>, rather than separate
lessThan() and
greaterThan() methods.
2. Your
lessThan() method doesn't look right (haven't checked the other one).
3. Normalizing (also called 'reducing') can be done "in arrears" - ie, when the Fraction is
used, rather than every time you get a result. You may also find it useful to have
normalize() return a
Fraction - ie,
this, after you've reduced it.
4. Consider adding an
invert() method.
5. You never check for overflow, despite the fact that pretty much
any arithmetic on a Fraction will tend to increase the sizes of the numerator and/or divisor.
6. Fractions have a lot in common with floating-point numbers, so you might want to consider whether you want to support "infinites" (n/0) and/or "NaN" (0/0).
7. You keep the sign in the numerator, which is fine (and probably simplest); but an alternative arrangement is to store the sign separately and make your numerator and divisor positive (sometimes called "sign-magnitude"). One thing this does is allow you to store ±0 as distinct values if you want to; but it's not wildly important.
8. Consider making the class immutable and have your arithmetic methods return
new Fractions, rather than updating
this one. I think you'll find the API becomes a lot simpler.
and a few "efficiency" things for you:
1. When adding or subtracting, you don't need to normalize if the divisors are equal.
2. When muliplying or dividing, you don't have to normalize if either operand is 1 or -1.
3. When comparing, check the signs first, and then whether one operand is "vulgar" and the other isn't. You only need to compare products if
both of the those cases are false.
HIH
Winston