Zero as a Constant – Coding Style and Readability

coding-styleconstmaintenancereadability

I have come across this programming idiom recently:

const float Zero = 0.0;

which is then used in comparisons:

if (x > Zero) {..}

Can anyone explain if this is really any more efficient or readable or maintainable than:

if (x > 0.0) {..}

NOTE: I can think of other reasons to define this constant, Im just wondering about its use in this context.

Best Answer

Possible reasons are caching, naming or forcing type

Caching (not applicable)

You want to avoid the cost of creating an object during the act of comparison. In Java an example would be

BigDecimal zero = new BigDecimal ("0.0");

this involves a fairly heavy creation process and is better served using the provided static method:

BigDecimal zero = BigDecimal.ZERO;

This allows comparisons without incurring a repeated cost of creation since the BigDecimal is pre-cached by the JVM during initialisation.

In the case of what you have described, a primitive is performing the same job. This is largely redundant in terms of caching and performance.

Naming (unlikely)

The original developer is attempting to provide a uniform naming convention for common values throughout the system. This has some merit, especially with uncommon values but something as basic as zero is only worth it in the case of the caching case earlier.

Forcing type (most likely)

The original developer is attempting to force a particular primitive type to ensure that comparisons are cast to their correct type and possibly to a particular scale (number of decimal places). This is OK, but the simple name "zero" is probably insufficient detail for this use case with ZERO_1DP being a more appropriate expression of the intent.

Related Topic