Note that there are some explanatory texts on larger screens.

plurals
  1. POmethod parameter vs. getter in subclass
    primarykey
    data
    text
    <p>We had a discussion in the office, but neither side was convinced. Lets say we have</p> <pre><code>enum Food { CHICKEN, HAMBURGER, FISH; } </code></pre> <p>We need multiple implementations of Dog, which need to answer, whether they are happy, which depends on whether they like food given to them and maybe some other stuff. It needs to be very flexible. Which is better: <strong>A:</strong></p> <pre><code>abstract class Dog { //not sure if this can be abstract in reality, but does it matter? abstract Set&lt;Food&gt; getFavoriteFoods(); boolean isFoodOk(){ return getFavoriteFoods().contains(Food.CHICKEN); } //in reality sometimes more conditions are needed here... boolean isHappy(){ return isFoodOk(); } } public class BullDog extends Dog { static final Set&lt;Food&gt; FAVORITE_FOODS = new HashSet&lt;Food&gt;(); static { FAVORITE_FOODS.add(Food.CHICKEN); FAVORITE_FOODS.add(Food.FISH); } Set&lt;Food&gt; getFavoriteFoods(){ return FAVORITE_FOODS; } } </code></pre> <p><strong>OR B:</strong></p> <pre><code>abstract class Dog { abstract boolean isHappy(); boolean isFoodOk(Set&lt;Food&gt; f){ return f.contains(Food.CHICKEN); } } public class BullDog extends Dog { static final Set&lt;Food&gt; FAVORITE_FOODS = new HashSet&lt;Food&gt;(); static { FAVORITE_FOODS.add(Food.CHICKEN); FAVORITE_FOODS.add(Food.FISH); } @Override boolean isHappy() { return isFoodOk(FAVORITE_FOODS); } } </code></pre> <p>If the answer will be A I will have another question.</p> <p><strong>NOTE:</strong> I edited the code because there was a silly mistake there - of course FAVORITE_FOODS should be declared in BullDog, not Dog. But that does not answer the question.</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.
 

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