Trusted answers to developer questions

What is composition in Solidity?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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:

Contract A is composed of Contract B
Contract A is composed of Contract B

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 version
contract ContractB { //contract B
//test1 function to return 0
function test1() public pure returns(uint) {
return(0);
}
}
contract ContractA {
//ContractA using object of ContractB
ContractB contractB; //composition
//constructor
constructor(address helperAddress) public {
contractB = ContractB(helperAddress);
}
// test function to call contractB's test1 function
function test() public view returns(uint) {
return contractB.test1();
}
}

Code explanation

  • 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.

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.

RELATED TAGS

solidity
blockchain
Did you find this helpful?