Inside or Outside the ADT


Identity: InOrOut
Category: Data MultiModule
Classifiers: data abstraction
Internal cross references:
External cross references:

Language: This has been described in terms of Haskell, but will apply to any language with abstract data types.

Description: Move a definition over an ADT into or out of the capsule in which the concrete representation is accessible.

module Tree (Tree, leaf, node, isLeaf, 
       isNode, val, left, right, flatten) where

data Tree a 
 = Leaf a |
   Node a (Tree a) (Tree a)

flatten :: Tree a -> [a]

flatten (Leaf x) = [x]
flatten (Node x s t)
  = x : flatten s ++ flatten t

... other definitions hidden ...

module Client where

import Tree


module Tree (Tree, leaf, node, isLeaf, 
       isNode, val, left, right) where

data Tree a 
 = Leaf a |
   Node a (Tree a) (Tree a)

... other definitions hidden ...







module Client where

import Tree

flatten :: Tree a -> [a]

flatten t
  | isleaf t = [val t] 
  | isNode t 
    = val t : flatten (left t) ++ 
              flatten (right t)

General comment:

This is a good example of a refactoring which can be applied in either direction. The left-hand code allows more efficiency, and direct access to the representation, whereas the right-hand code has the advantage of being representation-independent.

Left to right comment:

This has the effect of making flatten independent of the representation; it is therefore defined once and for all, and does not require re-definition when the implementation of Tree is changed.

Right to left comment:

This refactoring allows the definition of flatten access to the representation; for example, the definition might be more efficient in such a case. The disadvantage of this is that flatten has to be re-defined each time the representation of Tree is changed.

Left to right conditions:

There are no conditions on performing this refactoring.

Right to left conditions:

The refactoring can be effected simply by moving the definition to the capsule. Conversion to a full pattern-matching form of definition requires definitions to be written in an appropriate form.