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.
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()));
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>
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))();
Interface
// -- nested --
interface Low { }
interface Middle extends Low { }
interface High extends Middle { }
// -- flat --
interface Low { }
interface Middle { }
interface High extends Middle, Low { }
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)