Data types tells about what kind and range of data we want to store in a given variable or field or column (in case of database). Those are equally important in both source code and test code. While writing tests, if we select not suitable data type, we may encounter errors which will have impact on the test results or validations. How can we choose the right kind of data type in our code? Well, the definition of "right" may depends on many factors. In this small post, I am covering few important tips to keep in mind while selecting data types for variables.
Why do we need to care while selecting data type for a variable?
- Knowing the data type used in code and reason behind is very important in certain situations when requirements needs to be tested against some specific business rules. For example date and time with time zones, monetary calculations etc.
- This will help to avoid and take necessary precautions well in advance for certain type of errors for example overflow errors.
- If performance is a major factor for the application we are developing, we can take some steps while selecting data types which are faster.
- If thread safety is a game changer for our application, then we should look for thread safe options while selecting the data types.
Let's explore this with few examples from Java. Java has eight primitive data types - byte, short, int, long, float, double, boolean and char. There are corresponding wrapper classes available to use.
Performance:
If performance is main criteria for the selection variables, primitive types are always faster than the corresponding wrapper classes ( needs to be auto unboxed before use)
Default value (Zero or Null):
If default value zero (except boolean which is false) is acceptable as per our requirement, we can use primitive data types.
Using long, int or BigDecimal for storing money and performing monetary calculations are recommended than using float and double. BigDecimal represents a signed decimal number of arbitrary precision with an associated scale. BigDecimal provides full control over the precision and rounding off the number value. Lets see the outcome using a simple example:
Date and time
We need to be extra care full when using data and time data type due to following reasons:
- Date and time can be represented using different formats. We need to choose the appropriate format based on the use case referred by requirement.
- We need to be aware also when to use time zones.