Software Design/Use class instead of primitive type

From Wikiversity
Jump to navigation Jump to search

Checklist questions:

  • Can use a class or a type alias for variables of quantities such as money or temperature instead of a primitive numeric type such as int?

Why[edit | edit source]

The greater apparency of semantics of function parameter declarations, variable declarations, and function return types.

The smaller probability to make a programming mistake by passing a wrong argument to the function (interface robustness), or returning a wrong variable from the function, or using a wrong variable in an expression (code robustness).

Certain operations on quantities sensitive to the accuracy can be prohibited or fail fast: for example, when a money amount cannot be divided without a remainder by the specified value, or when a single 64-bit value cannot hold the requested amount without integer overflow, an exception could be raised. Equivalent functions could be defined on the primitive numeric types as well (or already present in the standard library), but it may be not possible to enforce their usage even with static analysis rules within the existing static analysis frameworks.

Why not[edit | edit source]

In languages that don't support type aliases (for example, Java), using objects instead of primitive types negatively affects the performance and memory usage of the program.

In languages that don't support operator overloading manipulating with variables of quantity classes instead of primitive numeric variables can reduce the clarity and the naturality of the expression.

Related[edit | edit source]