HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Check if more engineers are happy than not happy

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arethanmorehappyengineerschecknot

Problem

I wish to use this sample to make my code more readable. Could you share with me your ideas on method naming, variable naming, if-statements etc.

It would be great if you have any URLs.

private boolean areEngineersHappy (List engineers) {
  int notHappyEngineers = 0;
  int happyEngineers = 0;
  for (Engineer engineer : engineers) {
    boolean notHappy = !engineer.isHappy();
    if (!notHappy) {
      happyEngineers++;
    }
    if (notHappy) {
      notHappyEngineers++;
    }
  }
  return happyEngineers > notHappyEngineers;
}

Solution

Consider

private boolean isMajorityHappy(List engineers) {
    int netHappiness = 0;

    for (Engineer engineer : engineers) {
        if (engineer.isHappy()) {
            netHappiness++;
        } else {
            netHappiness--;
        }
    }

    return netHappiness > 0;
}


Name the method based on what it does. What it does is check if the majority of the members of the list are happy. The fact that the list is of engineers is mostly beside the point.

I would expect areEngineersHappy to return false if any engineer is unhappy.

Note that we don't need two variables to tell if the majority is happy. We can use a single variable and subtract for unhappy members of the list. If netHappiness is positive, then the majority of the members of the list are happy.

I would try to avoid constructs like if (! notHappy) {. It would be much simpler to change the logic around so that you can say if (happy) { instead.

You don't need to say if (happy) and if (! happy). This is exactly the situation for which an else is designed.

Code Snippets

private boolean isMajorityHappy(List<Engineer> engineers) {
    int netHappiness = 0;

    for (Engineer engineer : engineers) {
        if (engineer.isHappy()) {
            netHappiness++;
        } else {
            netHappiness--;
        }
    }

    return netHappiness > 0;
}

Context

StackExchange Code Review Q#107581, answer score: 35

Revisions (0)

No revisions yet.