Prefer Domain-Specific Types to Primitive Types

From WikiContent

Revision as of 20:27, 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] is in many ways about this. The benefits from its use are many, more readable code, fewer code lines, increased re-use etc.

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