The 'best' way to check for args[n].

Discussion in 'Plugin Development' started by Wolfy9247, Feb 24, 2012.

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


    So this is a plain and simple question, what's the 'best' or most efficient way of checking if args[n] (such as args[0], args[1], etc.) exist without returning an NPE? You can't exactly do args[0].isEmpty() or .length() > 0 on it as, if it doesn't exist, it'll return null.

    So really, my solutions have mostly been something like:
    1. if(args.length == 1)


    1. try { (code) }
    2. sender.sendMessage(ChatColor.RED + "Insufficient arguments provided!");

    But, which is most efficient, and, are there better methods than this? Thanks for the help / input!
  2. Offline


    I've always just used args.length, when using a command executor that's the typical way most do.
  3. Offline


    If I need to use a lot of typical parameters (for example setting the variables values), I'm using loop:

    if (args.length>0)
      for (int i = 0; i<args.lenght; i++) {
          if (args[i].startWith ("variable1=")){
    //  setup the variable1, show message
          } else if (args[i].startswith ("variableN=")) {
    And you can call your command: /command parameter1=15 parameter2=off parametet3=15.25
  4. I prefer not to use exceptions for things I already know. For example:

    2. if (args != null && args.length > 0) {
    3. doStuff();
    4. } else {
    5. sender.sendMessage(String.format("%sInsufficient arguments provided!",
    6. ChatColor.RED));
    7. }

    The rule I use in Java is that Exceptions are for exceptional cases. If this one may frequently or commonly be null, just do the check.
Thread Status:
Not open for further replies.

Share This Page