Hi Nacho,
I wouldn't throw an error because otherwise one must know beforehand that an
equation is non-resolvable or must use #on:do: everywhere.
Since that when you ask to resolve an equation you get back a collection of
solutions, a non-resolvable equation could just return an empty collection,
couldn't it?.
If you really want to consider that asking to resolve a non-resolvable
equation is an error, another solution would be to provide a #rootsIfNone:
method. That's a common pattern in Smalltalk.
I would also rename 'checkNegative' to 'discriminant', because it's not
obvious to see what that variable represents at first glance.
Very good points. I came up with a third draft. This is evolving good!
Thanks
Nacho
In fact, what I meant is that the function that compute the roots should be called #calculateRootIfNone: and take a block as parameter:
QuadraticEquation>>calculateRootsIfNone: aBlock
| discriminant |
discriminant := linearCoefficient squared - ( 4 * quadraticCoefficient * constant).
discriminant >= 0
ifFalse: aBlock
ifTrue: [ ^ self solveRoots: discriminant]
Like this, you can provide a #calcultaeRoots method like this:
QuadraticEquation>>calculateRoots
^ self calculateRootsIfNone: [ self error: 'No real solution for the equation' ]
And you could even provide a #calculateRootsSafely that just return an empty array.
QuadraticEquation>>calculateRootsSafely
^ self calculateRootsIfNone: [ { } ]
This is a common pattern in Smalltalk. Look at collection methods like #detect:ifNone: #at:ifPresent: #at:ifAbsent: ,etc ...
BTW, is it expected that when the discriminant equals 0, the same root is returned twice?