Hi everybody, I'm just wondering what is the more eficient and compact way to write statements like this

if(site.next(1) == null) {
      return false;
}
if(site.next(2) == null) {
      return false;
}
if(site.next(3) == null) {
      return false;
}

Dani AI

Generated

— good question. is right that the three identical checks can be collapsed; here are a couple of compact, readable alternatives that avoid repeating the same code and scale better if you need more checks.

A simple loop keeps intent clear and shortens the code:

for (int i = 1; i <= 3; i++) {
    if (site.next(i) == null) {
        return false;
    }
}
return true;

For Java 8+ you can express the same idea with an IntStream if you prefer a functional style:

boolean allPresent = IntStream.rangeClosed(1, 3)
    .mapToObj(i -> site.next(i))
    .allMatch(Objects::nonNull);

return allPresent;

If you will check varying sets of indices, extract a small helper so callers stay clean:

private boolean allNextNonNull(Site site, int... indices) {
    for (int idx : indices) {
        if (site.next(idx) == null) return false;
    }
    return true;
}

Notes and cautions:

  • Short-circuiting (returning as soon as a null is found) preserves the early-exit behavior and is efficient.
  • Avoid calling site.next(...) repeatedly if the method has side effects or is expensive. In that case call it once and store the result before testing.
  • For only three checks, readability matters more than micro-optimizations. Pick the form that fits your codebase style.

These patterns keep the logic compact, make future changes (more indices) trivial, and reduce duplication.

Recommended Answers

All 2 Replies

  1. You can combine multiple tests in one if, in this case ORing them together, as in
    if ( site.next(1) == null || site.next(2) == null ...

  2. The contents of the if must be a boolean expression, so you don't need an if to turn that into a booelan result, eg
    return ! ( site.next(1) == null || site.next(2) == null

Thank you !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.