Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create conventions for T get(K keyLike) variants #665

Open
supersaiyansubtlety opened this issue Nov 18, 2024 · 0 comments
Open

Create conventions for T get(K keyLike) variants #665

supersaiyansubtlety opened this issue Nov 18, 2024 · 0 comments
Labels
discussion changes that need discussion before being implemented documentation improvements or additions to documentation

Comments

@supersaiyansubtlety
Copy link
Contributor

It's been discussed a couple times in PR comments, I propose the following conventions:

// net/minecraft/state/State

@Nullable
public <T extends Comparable<T>> T get(Property<T> property) {
    Comparable<?> comparable = (Comparable<?>)this.entries.get(property);
    return comparable == null ? null : property.getType().cast(comparable);
}

public <T extends Comparable<T>> T getOrThrow(Property<T> property) {
    Comparable<?> comparable = (Comparable<?>)this.entries.get(property);
    if (comparable == null) {
        throw new IllegalArgumentException("Cannot get property " + property + " as it does not exist in " + this.owner);
    } else {
        return property.getType().cast(comparable);
    }
}

public <T extends Comparable<T>> Optional<T> getOrEmpty(Property<T> property) {
    return Optional.ofNullable(this.get(property));
}

public <T extends Comparable<T>> T getOrDefault(Property<T> property, T defaultValue) {
    return Objects.requireNonNullElse(this.get(property), defaultValue);
}

I've seen getOrNull suggested for the first variant.
I prefer get because I think one of them should be just get, and this matches java.util.Map::get.

If only one single-param variant is present, I think get should be used regardless of which variant it is (getOrDefault should always be getOrDefault).

Note that I'm not suggesting a convention for differentiating between methods that get values based on various different key-likes, such as Identifier id and int rawId, which I don't think should be generalized into a convention.

@supersaiyansubtlety supersaiyansubtlety added documentation improvements or additions to documentation discussion changes that need discussion before being implemented labels Nov 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
discussion changes that need discussion before being implemented documentation improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant