5a. Android Studio: create new Java CONSTANTS class

Sometimes is worth to extract a bunch of code to a separate class to keep the original short and sweet (readable and maintainable).




In our Activity class I had a lot of constants:

   private final static double CONVERSION_METERS_TO_YARDS = 1.093613298;
   private final static double CONVERSION_KILOMETERS_TO_MILES = 0.621371192;


One way to maintain them was to move them to a new Java class ConversionConstants






















  • Make sure you write the JavaDoc /** my description */ for each class you create
  • constants are public - available form any other class
  • constants are final - the value cannot be changed by the code
  • constants are static - indicate that the constant will belong to class and not the instance, you don't have to have an instance to get it e.g. ConversionConstants.METERS_TO_YARDS

package com.chicagoandroid.cit299.calc;
/**
* This class will contain hundreds of possible conversion constants.
*/
public class ConversionConstants {
    public final static double METERS_TO_YARDS = 1.093613298;
    public final static double KILOMETERS_TO_MILES = 0.621371192;
}


Now I can access these constants from any other class and use them in my calculations:





Note: I am not providing the source code on purpose because copy-and-paste is not a good learning experience.



As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles