Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As @tafa said, it seems to me an interface would be a good choice. Based on your signature for <code>average</code>, I came up with the below.</p> <p><strong>AveragableValue</strong></p> <pre><code>public interface AveragableValue&lt;T&gt; extends Value { public T average(T value); } </code></pre> <p><strong>NumberValue</strong></p> <pre><code>public class NumberValue implements AveragableValue&lt;NumberValue&gt; { private int _n; public NumberValue(int n) { this._n = n; } @Override public void doSomething() { // from Value interface } @Override public NumberValue average(NumberValue value) { return new NumberValue((this._n + value._n) / 2); } } </code></pre> <p>Then you can have your collection be of type <code>AveragableValue</code>. Already in your code you must have some kind of <code>if/else</code> clause somewhere to differentiate <code>NumberValue</code> and <code>StringValue</code> to figure out whether to call <code>average</code> or not. So I don't see how this would be more complicated. The hierarchy make sense - <code>AveragableValue</code>s are a subtype of <code>Value</code>, and a <code>NumberValue</code> is a type of <code>AveragableValue</code>.</p> <p>However, that signature for <code>average</code> doesn't look right. It only takes 2 values (<code>this</code> and the argument) and averages them. You then lose the total count of things that have been averaged before. So assuming integers as the values (as I did), something like this:</p> <pre><code>(new NumberValue(4)).average(new NumberValue(8)).average(new NumberValue(12)); </code></pre> <p>would give you the value <code>9</code> instead of <code>8</code>. Is this what you want? It makes it bad for many calculations done iteratively, as you may be doing with collections.</p> <p>If you show us some of your code - how these classes are used, the collections holding them, how you are doing averaging right now - I can maybe give a better answer.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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