Wednesday, October 9, 2019

Java: Optional or just null

So I was making a simple game on the weekend, as we do, and there was a simple (again) player class:

public class Player {
    public final String name;
    private Team team;
    ....
    public boolean friendly(Player other) {
        return team.has(other);
    }
}

But the obvious thing is, can it be null? Yes it can, in cases where the player does not have a team. So I said 'Let's try Optional, why not`.

    private Optional<Team> team;

Then the possibilities for the return statement where limitless from the most straight forward to the most elegant:

    return team.isPresent() && team.get().has(other)

    return team.map(i -> i.has(other)).orElse(false);

    return team.filter(i -> i.has(other)).isPresent();

    return team.orElse(Team.EMPTY).has(other);
    
Or I could remove the Optional again and have just the old thing:

    return team != null && team.has(other);

But 'How will you remember that it can be null in other places?' said the guy. Its a private field, how many places are there really. Also it is logical to null so I would probably check it anyhow.


done_