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


    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.

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

    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


    Are default values okay?

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


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

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


    What is so messy about this?
  4. Offline


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


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

Share This Page