I've been using casts to get the player object from CommandSenders and Events a lot, is this what I should be doing for that?
@Symphonic Yes but, make sure to check if it's an instanceof that before casting. Example: Code:Java // Don't do this alone (unless you're absolutely sure there's no way it can be anything else)Player player = (Player) sender; // Do this insteadif (sender instanceof Player) { Player player = (Player) sender;}
Yep. Casting is not a problem, so long as A. the data can be cast to that type and B. that it isn't the same type. I've seen people do things like String playerName = (String)args[0]; before. If the var is already a String, then the (String) is superfluous. It won't cause any problems or hit resources, but it's just an eyesore when reading the code. One other thing I'd add; this is totally subjective and just a question of personal style but in KarimAKL's example above if you are doing a command and it's only for players, rather than do: Code: public boolean onCommand(yadda yadda) { if (sender instanceof Player) { Player player = (Player)sender; // do whatever command stuff } else { sender.sendMessage("You need to be in game to use this!"); } } I personally prefer negative checking: Code: public boolean onCommand(yadda yadda) { if (!(sender instanceof Player)) { sender.sendMessage("You need to be in game to use this!"); return true; } Player player = (Player)sender; // do whatever command stuff } Reduces indentation. I've seen methods posted that have like 8+ level deep indentation where switching to negative checks would've reduced the meat of the method to 1 level, which IMO is much easier on the eyes. But again, that's subjective. Nothing wrong with positive checks if the indents are beneficial to you.
I'd usually do the same but, i just thought it would be easier to read as an example. (only because it's 1 indention more)