DEV Community

Cover image for Depth of composition
Mike Skoe
Mike Skoe

Posted on • Edited on

Depth of composition

When developing applications, it is common to split a large amount of code into smaller units. However, one of the difficulties is how to compose these parts together. In this post, we will emphasize the "depth" of a composition. This refers to how nested composition differs from flat composition in different contexts.

Image description

Class

// -- nested --
class Low {}

class Middle {
    private low = new Low();
}

class High {
    private middle = new Middle();
}

// usage
const high = new High();

// -- flat --
class Low {}

class Middle {
    constructor(
        private low: Low,
    ) { }
}

class High {
    constructor(
        private middle: Middle,
    ) { }
}

// usage
const high = new High(new Middle(new Low()));
Enter fullscreen mode Exit fullscreen mode

React component

// -- nested --
const Low = () => <low />;

const Middle = () => <middle><Low /></middle>;

const High = () => <high><Middle /></high>;

// usage
<High />

// -- flat --
const Low = () => <low />;

const Middle = ({ children }) => <middle>{children}</middle>;

const High = ({ children }) => <high>{children}</high>;

// usage
<High>
  <Middle>
    <Low />
  </Middle>
</High>
Enter fullscreen mode Exit fullscreen mode

Function

// -- nested --
function low() {}

function middle() {
  low();
}

function high() {
  middle();
}

// usage
high();

// -- flat --
function low() {}

function middle(low: () => void): () => void {
  return () => {
    low();
  }
}

function high(middle: () => void): () => void {
  return () => {
    middle();
  }
}

// usage
high(middle(low))();
Enter fullscreen mode Exit fullscreen mode

Interface

// -- nested --
interface Low { }

interface Middle extends Low { }

interface High extends Middle { }

// -- flat --
interface Low { }

interface Middle { }

interface High extends Middle, Low { }
Enter fullscreen mode Exit fullscreen mode

Why flat?

  • Easier to navigate between layers
  • More control over each layer of the code
  • Easier to manage and modify
  • It facilitates mocking
  • It encourages reliance on interfaces

Why nested?

  • More intuitive structure
  • Easier to implement and use
  • It hides inner details from the API
  • It provides a simpler interface for users

By considering these factors, developers can choose the most suitable approach for their specific needs and context.

Top comments (0)