Quack Like A Duck

TYPING PART II
 
Cbachellam
Atlanta, GA
April  14, 2016

Introduction

Today’s blog post comes with bells, whistles and an announcement that, the underlying theme of all the posts in this blog is: “there is always a chasm between theory and practice, but a well essayed technical work can bridge this gap, and seamlessly connect the two disparate world, though the latter is a precursor”. Now let us get back to science, we are in the continuum of the second part, in the chain of posts about TYPING. (checkout my previous post about TYPING PART I). We left with the need for typing and definition of typing in the previous post. In this post, we plunge into nominal and structural typing.
 

Nominal-Typing Vs Structural-Typing Alias Duck-Typing

Predominantly all high level compiled languages are baked with the typing feature called as Nominal Typing, which means that –

“a fully qualified unique name/identifier of the class and its contract / interface (which specifies the behavioral features or methods the class ought to implement) are matched/compatible by the name against the instantiated objects”. – cc

 
This idea or notion of tying down the object instances against the names of class / interface is called Nominal Typing (Object Oriented languages like C#/JAVA/C++). To paraphrase the above definition: Having class names as part of the meaning of objects is called nominality [1]. Also according to Benjamin Pierce [2], “The fact that recursive types come essentially for free in nominal systems is a decided benefit [of nominally-typed OO languages]”. 
 
On the contrary if the objects are matched against the structural equivalence of the entities in comparison (there by avoiding the fully qualified name / nominal information), then it is called as Structural Typing. Also Structural Typing is commonly called as Duck Typing. 
 
“If it walks like a duck and quacks like a duck, it must be a duck.” – unknown
 
– what it means is an object need not be tied down to its class merely by name of its class / interface, rather than, a perfect or close to perfect harmony with its class’s fields / properties and methods is deemed as passable.

TYPESCRIPT Code Snippet for Structural / Duck Typing example 

interface IVector2D {
    x: number;
    y: number;
}

interface IVector3D {
    x: number;
    y: number;
    z: number;
}

var vector: IVector2D = { x: 0, y: 10, }

var vector3D: IVector3D = { x: 0, y: 10, z: 20 }

function iTakePoint2D(vector: IVector2D) {
/* do something */
}

iTakeIVector2D(vector2D); // exact match okay

iTakeIVector2D(vector3D); // extra information okay

iTakeIVector2D({ x: 0 }); // Error: missing information `y`
 
References:
  1. Moez A. AbdelGawad.  An Overview of Nominal-Typing versus Structural-Typing in Object-Oriented Programming. 
  2. Benjamin C. Pierce. Types and Programming Languages. MIT Press, 2002.

Leave a comment