Prefer Domain-Specific Types to Primitive Types

From WikiContent

Revision as of 16:10, 24 November 2008 by Kevlin (Talk | contribs)
Jump to: navigation, search

One of the main features provided by object-oriented languages are abstract data types and strong typing. Still many developers uses the primitive data types offered by the language such as String. Wrapping complex data structures as strings are simple as the object method basically can take any data, but it's also an unsafe style of programming, where the developer avoids delegating appropriate quality control to the compiler.

Ada developers are encouraged to utilize the strong typing offered by the language. The benefit is safer code as can be seen from the example below:

subtype Velocity_In_Knot is Float range 0..500.00;

subtype Velocity_In_Km is Float range 0..300.00;

V1: Velocity_In_Knot;

V2: Velocity_In_Km;

Speed: Float;

With these types and variables defined the statement Speed:=V1+V2; will be caught by the compiler as a type error.

The same level of strong typing can be achieved by any object-oriented programming language such as Java, C++, and C# by defining the appropriate data type as a class. The Value Object pattern from Eric Evans book Domain-Driven Design provide good programming practices for these languages. By defining values for velocity, money, and distance in terms of classes, safe arithmetical operations can be supported combined with many other benefits such as more readable code, fewer lines of code and increased reuse.

Therefore, developers should stop to misuse primitive data types for convenience, and start on the journey of exploring the power of strong typing and the Value Object pattern.

By Einar Landre

This work is licensed under a Creative Commons Attribution 3

Back to 97 Things Every Programmer Should Know home page

Personal tools