[TUTORIAL] Safe Commands

Discussion in 'Resources' started by beastman3226, Nov 25, 2012.

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

    beastman3226

    I see and I am also guilty of writing terrible commands because I was too lazy to write a couple more lines of code. Also enabling a plugin on a server with no Console commands sucks and it's not the hard to allow admins to do stuff from console.
    First, the onCommand methd:
    Code:java
    1. @Override
    2. public boolean onCommand(CommandSender sender, Command cmd, String string, String[] arg)
    3.  

    Not too hard?
    Second, if statements:
    Code:java
    1. @Override
    2. public boolean onCommand(CommandSender sender, Command cmd, String string, String[] arg){
    3. if(sender instanceof ConsoleCommandSender{
    4. if(cmd.getName().equalsIgnoreCase("bawse"){
    5. if(args.length > 1) {
    6. if(args[0].equalsIgnoreCase("stop"){
    7. //whatever
    8. }
    9. }
    10. }
    11. } else {
    12. //samething
    13. }
    14. return true;
    15. }
    16.  

    Thats a lot better than:
    Code:java
    1. //...method
    2. if(cmd.getName().toLowerCase().equals("bawse"){
    3. }
    4.  

    Because you have widdled out; the sender, the command name, and args length! In the above example the sender can be either one, and you have no idea how many args there will be.

    Errors that I commonly see and I have learned from:
    Code:java
    1. @Override
    2. public boolean onCommand(CommandSender sender, Command cmd, String string, String[] args){
    3. Player target = (Bukkit.getServer().getPlayer(args[0]));
    4. if//....
    5. }


    That code will throw an ArrayIndexOutOfBoundsException because you don't know if there are more than one args. You need to define your variable after you "if(args.length...)" statment. Avoid args.length ==, because it will save you time in the future.

    If you can think of anymore things that will benefit this tutorial don't be afraid to share.
     
  2. Offline

    hice3000

    Theres an error in you code, I think, you missed the if-closing ) on line 3 in your second code block.
     
  3. This are just examples, no one has said that these examples also compile...
     
  4. Offline

    hice3000

    I just said that there is a bug, not critilized his work ...
     
Thread Status:
Not open for further replies.

Share This Page