This question may be a little bit subjective, but I'm just trying to follow the best programming practices for organization of code.
I have a class Polynomial
that makes a lot of reference to the class Rational
, and in many different methods it uses a Rational
value that is equivalent to 1, 0, or -1 for comparisons.
As such, I have the following constants defined:
public static final Rational ZERO = new Rational(0);
public static final Rational ONE = new Rational(1);
public static final Rational NEG_ONE = new Rational(-1);
However, the thing I'm not certain about is where to store these values in a meaningful way.
On the one hand, Polynomial
is what uses them, so storing them inside of the class localizes it to where it is going to be used. This also means that it can be changed to private so that it is only used within the one class.
On the other hand, if it is defined inside of Rational
, then all calls to the values become Rational.ZERO
, Rational.ONE
,Rational.NEG_ONE
-- which makes it very human-readable, and organizes it in a lexically understandable manner. It also gives the opportunity to define similar constants in Polynomial
as well if ever it were needed.
So basically, opinions aside, what's the most common practice for organization in something like this? Are my thoughts right for either of the locations for it, or is there another solution that I hadn't considered?
They should be in the Rational
class since they are abstraction for rational numbers. It would be debatable if you would want to move them to a RationalPolynomial
class, but even then I believe keeping them in Rational
would be better.
A big requirement for doing this is making your Rational
class immutable; otherwise you shouldn't expose them as public. Effective Java mentions at page 76:
Immutable classes should take advantage of this by encouraging clients to reuse existing instances wherever possible. One easy way to do this is to provide public static final constants for frequently used values. For example, the Complex class might provide these constants:
public static final Complex ZERO = new Complex(0, 0);
public static final Complex ONE = new Complex(1, 0);
public static final Complex I = new Complex(0, 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With