Java

Clean Code Tip 1: String Constants Comparison

Introduction

Today, I will share very quick and simple tip that could help you to improve your code. I am quite sure that you are using string comparasion quite often and that this tip could you help to avoid null pointer exceptions. With this tip you will make your code a little bit cleaner and easier to read.

I guess that all of you know that is a good practice to use constant values instead of typing values every time you need them. So, I am quite sure that there is in your code something like this:

public class CleanCodeTip {
  
  public static final String NOTIFICATION_TYPE = "distance";

  public static void main(String[] args) {
    
    String distance = "distance";
    
    if(distance.equals(NOTIFICATION_TYPE)){
      System.out.println("Notification type is: "+ distance);
    }			
  }
}

Since we have value for distance and it is equal to value of constant NOTIFICATION_TYPE we will get expected output:

Notification type is: distance

What is the problem?

If we are getting distance value from some other source that is not controlled by us, like web services, database, text file or some other external resources, then we might get null pointer exception if would compare strings in the same way as above. We can get NPE, since we are not sure that string received from external resource will have any value. Take look at the example:

public class CleanCodeTip {
  
  public static final String NOTIFICATION_TYPE = "distance";

  public static void main(String[] args) {
    
    String distance = null;
    
    if(distance.equals(NOTIFICATION_TYPE)){
      System.out.println("Notification type is: "+ distance);
    }			
  }
}

Output:

Exception in thread "main" java.lang.NullPointerException
  at CleanCodeTip.main(CleanCodeTip.java:10)

How to solve this?

It is obvious that we are getting null pointer exception because we can not compare null to some string value. How we can solve this problem and be safe that our application wont crash if we got null from external data resource?

public class CleanCodeTip {
  
  public static final String NOTIFICATION_TYPE = "distance";

  public static void main(String[] args) {
    
    String distance = null;
    
    if(NOTIFICATION_TYPE.equals(distance)){
      System.out.println("Notification type is: "+ distance);
    }			
  }
}

The solution is to use constant first, since we can compare string to null and we will get false result. With this simple clean code tip you can be sure that your application wont crash when you are doing string compassion against constants.

You Might Also Like

No Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.