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:
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}
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();}}
Line 1: We specify the compiler version.
Lines 2–6: The ContractB
is deployed, which contains the test1
function.
Lines 8–10: The ContractA
is created, which has an object of ContractB
named contractB
.
Lines 13–15: The ContractA
has a constructor which is given an address of already deployed ContractB
.
Lines 17–19: We make a function test
that is calling ContractB
's function test1
.
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
.
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.
RELATED TAGS
CONTRIBUTOR