Solved Hashmap null checks w/ minimal if statements

Discussion in 'Plugin Development' started by TerraVale, Oct 28, 2012.

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

    TerraVale

    Hi there!
    I've just run into an issue that involves the need to go through a ton of if statements and copy/paste code in several spots. Surely there's a way to get around this that I am unaware of, if not, then I'll have to tackle what I'm doing differently. No big deal.

    Code:JAVA
    1.  
    2. String m = event.getMessage();
    3. String t = PluginCommands.nametag.get(p.getName());
    4.  
    5. oPlayer.sendMessage(("[" + t + "] " + ChatColor.RED
    6. + event.getPlayer().getName() + ": "
    7. + ChatColor.GRAY + m));
    8.  


    These are the important snippets.
    I am modifying the players' chat events to allow each user to add in their own nametag (or prefix) via commands. I run into a problem here though, as I use hashmaps to store information that each player specifies! You can see that String t grabs the nametag inside of the hashmap I have created. Unfortunately, without a check to see if t is null, in the chat event, t will show as "null". This is no problem when dealing with ONLY t, but when I introduce the ability for players to set their own color "c", nametag "t", and parenthesis "pL" & "pR", things will get VERY messy when dealing with checks to see if anything is null. Is there a workaround?

    EDIT: As I mentioned earlier in my post, I can tackle this differently if it's not possible to work around all of the if statements by having the user specify the nametag, coloring, and parenthesis all in one command. Preferably, I'd like to introduce /tag set <tag>, /tag color <color>, and /tag par <parenthesis> though. As a challenge, without sloppy if statements permeating throughout.
     
  2. Offline

    coldandtired

    Are default values okay?

    String s = something != null ? something : "default";
     
  3. Offline

    andf54

    String pR = parenthesisL.get(name);
    if(pR != null) tag = pR + tag;

    Color c = colors.get(name);
    if(c != null) tag = c + tag;

    etc

    What is so messy about this?
     
  4. Offline

    Courier

    You could have a method such as this:
    Code:java
    1. private static String nullCheck(String original)
    2. {
    3. return original == null ? "" : original;
    4. }
    Then you could write:
    Code:java
    1. oPlayer.sendMessage(nullCheck(c) + nullCheck(pL) + nullCheck(t) + nullCheck(pR));
     
    TerraVale likes this.
  5. Offline

    TerraVale

    I definitely like this method of doing things and will give it a try!
     
Thread Status:
Not open for further replies.

Share This Page