Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You have a 'Java' tag, so assuming this is in fact Java friendly, I'd do it with an Enum:</p> <pre><code>enum USStates { TEXAS(TX_RATE), OHIO(OH_RATE), MAINE(MN_RATE), OTHER(1); final double rate; USStates(double rate) { this.rate = rate; } public double calc(double base) { double amt = amt(base); return 2.0 * basis(amt) + extra(amt) * 1.05; } public double amt(double base) { return base * rate; } } </code></pre> <p>Then, in your actual executable code:</p> <pre><code> rate = state.rate; amt = state.amt(base); calc = state.calc(base); if (USStates.OHIO == state) { points = 2; } </code></pre> <p>If "base" is a constant (that wasn't clear from the example code) this can be simplified further by accessing it directly as a final rather than passing it in as a parameter.</p> <p>This solution has a few benefits. Firstly, the actual rates for a state do not actually need to be in their own separate constant using a naming convention, but can actually be stored as part of the Enum itself (so instead of "TEXAS(TX_RATE)" you could actually just enter "TEXAS(1.4)" (or whatever its value is)) and the rate is then maintained as part of the "TEXAS" enumerated type.</p> <p>It also has the benefit that the calculation logic is captured (encapsulated, even) along with the constants it operates on.</p> <p>By using Enums, you ensure that people can't accidentally use invalid operations on your constants (like accidentally performing mathematical operations on them).</p> <p>By reducing the number of conditional statements, you significantly reduce the number of possible execution paths. Fewer possible paths means fewer possibilities for null pointers and uninitialized variables. (As the sample code stands, there's a risk of an uninitialized variable error in "points" for any states other than OHIO)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload