I was wondering which is the best way to code, i mean how code extructure should be: Some examples: Code: public String getItemName(Player player) { ItemStack stack = player.getItemInHand(); if(stack == null || stack.getType().equals(Material.AIR)) { return null; } if(!stack.hasItemMeta()) { return null; } ItemMeta im = stack.getItemMeta(); if(!im.hasDisplayName()) { return null; } return im.getDisplayName(); } public String getItemName(Player player) { if(player.getItemInHand() != null && !player.getItemInHand().getType().equals(Material.AIR)) { ItemStack stack = player.getItemInHand(); if(stack.hasItemMeta()) { ItemMeta im = stack.getItemMeta(); if(im.hasDisplayName()) { return im.getDisplayName(); } } } return null; }
The best way would probably be something like this: Code:java public String getItemName(ItemStack item) {if (item == null || item.getType() == Material.AIR || !item.hasItemMeta()) return null;return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : null;}
@FisheyLP i would also sugest to make it "silent" so instead of null i would return an empty string, it makes no difference and it is "null safe"
I employ the first way. The less subscope, the better. That's a terrible idea. Lack of values should be null, that's what null means.
@1Rogue hm, i see your point yes it does mean that but i was aiming for a silent method meaning you dont need to null check each time you invoke it, but indeed it makes more sense to use null.
"Silent method" isn't really even a term, and if it was it would refer to not throwing an exception, not erroneous output. Null (or an Optional<T>, which is what should be used post-Java7) should always be used in place of guessing what the user wants, or an unexpected type return. For example, say you have a method #getCustomName: Code:java public class Foo { private final String name; public Foo() { /*...*/ } public String getCustomName() { return this.name; } } Given this, this code works perfectly: Code:java public void doSomething(Foo foo) { if (foo.getCustomName() == null) { System.out.println("Foo does not have a name!"); } else { System.out.println(String.format("Hello from %s!", foo.getCustomName())); }} Now if we were to change our original implementation of Foo: Code:java public String getCustomName() { return this.name == null ? "" : this.name;} We will now get the output below from the previous method: Code: Hello from ! By convention, this is simply how it has worked in the past (across many languages). You shouldn't begin supplying default values in that manner to anything.
@1Rogue i didnt use it as a term, i know it is for exceptions (seen on Apatche commons mostly) but thanks for the tutorial :- )