
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 --classLow{}classMiddle{privatelow=newLow();}classHigh{privatemiddle=newMiddle();}// usageconsthigh=newHigh();// -- flat --classLow{}classMiddle{constructor(privatelow:Low,){}}classHigh{constructor(privatemiddle:Middle,){}}// usageconsthigh=newHigh(newMiddle(newLow()));
React component
// -- nested --constLow=()=><low/>;constMiddle=()=><middle><Low/></middle>;constHigh=()=><high><Middle/></high>;// usage<High/>// -- flat --constLow=()=><low/>;constMiddle=({children})=><middle>{children}</middle>;constHigh=({children})=><high>{children}</high>;// usage<High><Middle><Low/></Middle></High>
Function
// -- nested --functionlow(){}functionmiddle(){low();}functionhigh(){middle();}// usagehigh();// -- flat --functionlow(){}functionmiddle(low:()=>void):()=>void{return()=>{low();}}functionhigh(middle:()=>void):()=>void{return()=>{middle();}}// usagehigh(middle(low))();
Interface
// -- nested --interfaceLow{}interfaceMiddleextendsLow{}interfaceHighextendsMiddle{}// -- flat --interfaceLow{}interfaceMiddle{}interfaceHighextendsMiddle,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)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse