0

I've been following a new journey into solidity for about a month now, so far so good, however with the Interface I'm having a hard time understanding the difference between these 2 methods of implementing Interfaces.

I can clearly notice how useful the Interface is in the 2nd method, but not in the 1st method.

Method 1:

pragma solidity ^0.8.0;

interface ICounter {

    function count() external view returns (uint256);
    function addToCount() external;
}

contract myInterface is ICounter {

    uint256 counter = 0;

    function count() external view override returns (uint256) {
        return counter;
    }

    function addToCount() override external {
        counter++ ;
    }
}

Method 2:

pragma solidity ^0.8.0;

contract myContract {
    uint256 count =0;

    function increment() external {
    count++ ;
    }
}

pragma solidity ^0.8.0;

interface ICounter {

    function count() external view returns (uint256);
    function increment() external;
}

contract myInterface {

    function incrementCount(address _counter) external {
        ICounter(_counter).increment();
    }

    function getCount(address _counter) external view returns (uint256) {
        return ICounter(_counter).count();
    }
}
2
  • This question is unclear, you are not using the interface on the second method, and whats the second screenshot for? Please add those details on the question
    – Julissa DC
    Jan 28, 2022 at 19:20
  • @JulissaDC Thank you for your time. In fact there's no screenshots, and the 2 methods are methods that I have crossed and tested so far for implementiing Interfaces. the 2nd Method is, a contract, and another contract casting from it through an Interface. Jan 28, 2022 at 22:26

1 Answer 1

0

The method 1 is used when developing contract hierarchies and the interfaces might change. In this case inheritance enforces proper definitions in the implementations. A new method added or a change to the function parameters should trigger a compiler error.

The method 2 is an important use cases for Interface in solidity. Interacting with already deployed contracts.

In order to write an exchange for NFTs a generic interface that will work with any NFT is the correct way to go. For example use IERC721 from OpenZeppelin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.