Pharo Smalltalk Users mailing list wrote
> Hello, 
>     
>     Im trying to solve a challenge from exercism where  I have to
>     calculate the points somehow gets on a very simple darts board. 
>     
>     I solved it like this : 
>     
>       
>       scoreX: anInteger y: anInteger2 
>           | distance | 
>           distance := (anInteger squared + anInteger2 squared) sqrt. 
>           distance > 10 
>               ifTrue: [ ^ 0 ]. 
>           distance > 5 
>               ifTrue: [ ^ 1 ]. 
>           distance > 1 
>               ifTrue: [ ^ 5 ]. 
>           ^ 10 
>       
>       
>       but now I use three if then and I think it's ugly code. 
>       
>       Is there a way I can make it more the smalltalk way ? 

Roelof, this example is too simple to "really do it the Smalltalk way".

In a more realistic scenario, you would have classes for each "rule" with
corresponding differences in behaviour. In the above example, you could get
away with a single class with two instance variables and configure three
instances of it appropriately.

In more complex scenarios, your start up code instantiates the various
rules, with precedence determined by the order of the rule instances. Then
when you need to determine which rule to apply, you use #detect:ifNone: to
find the rule that applies with the #ifNone: block providing the fallback
result.

Sometimes, you work with classes themselves to determine which class to use,
but I have described working with instances for the general concept. (After
all, classes are instances.)

Using rules with a #select: allows you to handle a scenario where multiple
rules apply. A good example is rules to provide the default coverages for an
auto insurance policy, where each possible coverage can have one or more
rules to assess the many characteristics of the applicants and so determine
the one rule that applies for each possible coverage. (And yes, it is
reasonable that a possible coverage has no rule applicable, in which case
the coverage is not included in the default offering.)


As mentioned, you /could/ apply this to your scenario, as an exercise. You
might be tempted to utilize an existing class with two instance variables.
That would be a bad design practice, but reasonable for a /disposable/
experiment to quickly study how it works. Always (create and) use classes
which truly reflect their purpose and have named properties which truly
reflect the objects they hold. In your scenario, #distance and #score seem
appropriate.

      

>       
>       Regards, 
>       
>       Roelof





--
Sent from: http://forum.world.st/Pharo-Smalltalk-Users-f1310670.html

Reply via email to