I have to implement Java.Polynomial as a school assignment. Part of the methods are add(polynomial), multiply(polynomial) etc.
In the case of something like
p.add(q); // computes p + q
is it better to return void and keep the sum of the polynomials in p? or is it better to return a polynomial and keep the former value of p intact?
My instinct tells me that i should do the following
- implement p.add(q) as a ‘destructive’ method… it adds q to the value of p and stores the sum in p
- also implement a static method Polynomial.add(p,q) which returns the sum of the polynomials.
What do you think?
Personally I really like immutable types. I would write
p.plus(q)instead ofp.add(q)and make it return a new polynomial. Immutability has a lot going for it, not just in terms of thread-safety (which sounds like it won’t be an issue in this case) but also in terms of reasoning about your code. It’s a lot easier to predict what’s going to happen if you know that nothing can change the contents of an object under your feet once you’ve stashed a reference to it.