Casting a lot?

Discussion in 'Plugin Development' started by Symphonic, Dec 17, 2019.

Thread Status:
Not open for further replies.
  1. Offline

    Symphonic

    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?
     
  2. Offline

    KarimAKL

    @Symphonic Yes but, make sure to check if it's an instanceof that before casting.
    Example:
    Code:Java
    1. // Don't do this alone (unless you're absolutely sure there's no way it can be anything else)
    2. Player player = (Player) sender;
    3.  
    4. // Do this instead
    5. if (sender instanceof Player) {
    6. Player player = (Player) sender;
    7. }
     
    Strahan likes this.
  3. Offline

    Symphonic

    Okay, thanks! You should be a mod on here, I see you helping out a lot.
     
    KarimAKL likes this.
  4. Offline

    Strahan

    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.
     
    0ct0berBkkitPlgins and KarimAKL like this.
  5. Offline

    KarimAKL

    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)
     
    Strahan likes this.
Thread Status:
Not open for further replies.

Share This Page