# Solidity: which method should I use to call a function from an external Contract?

When using solidity, I have a doubt when I need to call a function which was created in a different contract. I know 2 ways of doing it, and I don't understand what is more recommendable and why. These are the ways I know:

Method 1:

contract A {
function foo() external {
return true;
}
}

contract B is A {
foo();
}


Method 2:

contract A {
function foo() external {
return true;
}
}

contract B {
function callFoo() external {
return a.foo();
}
}


Could anyone tell me the differences, and when it is more convenient to use either Method 1 or Method 2?

Thank you!!

In example 1 at compile time A and B will be merged together, since B inherits from A, the resulting bytecode can be deployed to generate one address. The call between A and B is internal to the contract and is very cheap.

In example 2 A and B have to be compiled separately and it will result in two bytecodes generating two address when deployed. The call between them is external and it will cost more gas.

Usually example 1 situation is recommended when A and B are closely related, and the example 2 situation when they are independent of each other.

Aside from the practical fact that method 2 will cost more gas than method 1 because method 1 encapsulates the function call to remain internal, I would suggest that your decision should be made from the engineering perspective–logic, readability, and simplicity.

In method 1, you have established a parent contract A and created a child B. B will inherit everything from its parent A, including all of its other functions and properties, not just this one. If this makes sense in this use case, if A should be the base contract that B inherits from, then method 1 is what I would suggest.

In method 2, you have not established any parent-child relationship between A and B. Contract A is merely there and so is B; they are independent objects. But B wishes to access a function in A and so it does. If this relationship between the two contracts makes sense in this use case then method 2 is what I would suggest.

The above is the logical evaluation. Now suppose method 2 makes the most logical sense–the two contracts should not be related as parent and child–but you want to save on gas so you opt for method 1 anyway. This code implementation would not read well at all. It would be deliberately confusing and unnecessarily complex and would violate the basic tenets of OOP. But if you really are on a shoestring budget then engineering will always take a backseat to business, unfortunately.