Usage of Optional in the documentation from Sponge

I want to think that Sponge is a server implementation that’s way better than Bukkit or Spigot, and I want to believe that I choose it whenever I have the chance, but unfortunately I don’t know whether Sponge is great or over engineered (as people I talk to about Sponge say).

I came across many faulty usages of the Optional class (introduced in Java 8) when I was reading through the documentation. An example is the documentation titled The Data API

It simply throws away any benefits that the Optional class brings with itself, because the Optional#ifPresent(T) method would be of great use in this scenario (and many others in the documentation), but it isn’t used.

import org.spongepowered.api.data.DataHolder;
import org.spongepowered.api.data.key.Keys;

public void heal(DataHolder target) {
    if(target.supports(Keys.HEALTH)) {
        target.get(Keys.MAX_HEALTH).ifPresent(max -> {
            target.offer(Keys.HEALTH, max);
        }
    }
}

And even if the code shown in the documentation is shorter, it will still throw a NoSuchElementException if there is no data with the specified name as the key.

What’s worse is that the code shown rather throws a NoSuchElementException than not doing anything.

I may be nitpicking right now, but it seems that the Optional class is used repeatedly by Sponge (knowing that there is a whole part in the documentation dedicated to the Optional class), so I wanted to say something about it in the hope that it will change something.

The documentation is always evolving so its highly likely that it just hasn’t been updated. The docs project also takes PRs.

1 Like

SpongeDocs didn’t appear out of wishful thinking. I’ve tried to rope in everyone who knows what they’re talking about and point them at our Issues list. You’re more than welcome to join in and add your own input, be it a PR, commenting on an issue, or helping proofread things as they come out. If you have more to add to our documentation of optional, please do so ASAP.
The fact remains that SpongeDocs do not generally get a lot of contributions, so we take what we can get.

5 Likes