Note that there are some explanatory texts on larger screens.

plurals
  1. POWhich of the below three java class designs is better and why?
    primarykey
    data
    text
    <p>Example 1:</p> <pre><code>public interface Adder { public int getSum(); } public class AdderImpl implements Adder { private int v1; private int v2; public AdderImpl(final int v1, final int v2) { if (validate(v1,v2) == false) { throw some exception; } this.v1 = v1; this.v2 = v2; } public int getSum() { return this.v1+this.v2; } } </code></pre> <p>Example 2:</p> <pre><code>public interface Adder { public int getSum(final int v1,final int v2); } public class AdderImpl implements Adder { public int getSum(final int v1, final int v2) { if (validate(v1,v2) == false) { throw some exception; } return v1+v2; } } </code></pre> <p>Example 3:</p> <pre><code>public interface Adder { public int getSum(); } public class AdderImpl implements Adder { private int sum; public AdderImpl(final int v1, final int v2) { if (validate(v1,v2) == false) { throw some exception; } this.sum = v1 + v2; } public int getSum() { return this.sum; } } </code></pre> <p>I have simplified my production scenarios here into this simple class and interface.Example 1 has the disadvantage that if someone eyeballs the interface he will not be able to know the inputs on which the interface acts. Example 2 overcomes this advantage. By just looking at getSum interface user will be able to know the inputs on which interface acts. However if later on someone adds another function to this interface with Example 2 design and both interfaces are used then input validation will be repeated. Example 3 gives an obvious advantage of not computing the sum if caller calls getSum multiple times. For me all three of them works right now. I'm more confused between example 1 and example 2, the responsibility of input validation should be with constructor (example 2) or more easy to understand interface should be preferred (example 1) ? </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.
 

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