What is composition in Solidity?
Composition is a powerful feature in the Solidity programming language that enables developers to create complex programs. Composition allows developers to create multiple contracts that can interact with each other. This is done by creating an object of a parent contract in the child contract, where the child contract can use public and external functionalities of the parent contract. Let’s look at the following diagram to understand the composition:
Basic structure
The basic structure of composition in Solidity is as follows:
pragma solidity ^0.5.0;contract ContractA {// code block}contract ContractB {ContractA contractA;// code block}
Coding example
Let’s look at the following code:
pragma solidity ^0.5.0; //compiler versioncontract ContractB { //contract B//test1 function to return 0function test1() public pure returns(uint) {return(0);}}contract ContractA {//ContractA using object of ContractBContractB contractB; //composition//constructorconstructor(address helperAddress) public {contractB = ContractB(helperAddress);}// test function to call contractB's test1 functionfunction test() public view returns(uint) {return contractB.test1();}}
Code explanation
Line 1: We specify the compiler version.
Lines 2–6: The
ContractBis deployed, which contains thetest1function.Lines 8–10: The
ContractAis created, which has an object ofContractBnamedcontractB.Lines 13–15: The
ContractAhas a constructor which is given an address of already deployedContractB.Lines 17–19: We make a function
testthat is callingContractB's functiontest1.
We deploy ContractB and then create an instance of ContractA with the now-deployed ContractB address. Now, we can call test, which will, in turn, call test1.
Benefits of composition
The benefits of using composition in Solidity are as follows:
By using composition, developers can break their code into smaller, more manageable sections, allowing for easier debugging and maintenance.
This can also improve code readability, allowing for a more efficient development process.
Additionally, with multiple contracts working together, developers can create more complex and powerful applications that would otherwise be difficult to achieve with a single contract.
Composition is also a great way to reuse code. This allows developers to create multiple contracts with similar functionality, saving time and effort.