Prefer Domain-Specific Types to Primitive Types

From WikiContent

Revision as of 20:48, 21 November 2008 by Elandre (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 String's are simple as the object method basically can take any data, but its 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 more safe 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 catched 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 as Velocity, Money and Distance as classes safe arithmetical operations can be supported combined with many other benefits such as: More readable code, fewer lines of code and increased re-use.

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