Why is onlyOwner and _checkOwner divided into two places?

I'm just curious, why is onlyOwner and _checkOwner divided into two places? I was looking into '@openzeppelin/contracts/access/Ownable.sol' to better understand how this contract works. I also saw similar pattern in another @openzeppelin contracts so I like to know what is reason behind this structure.

:1234: Code to reproduce

     * @dev Throws if called by any account other than the owner.
    modifier onlyOwner() {

     * @dev Returns the address of the current owner.
    function owner() public view virtual returns (address) {
        return _owner;

     * @dev Throws if the sender is not the owner.
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");

Hey @Jan_Miksik
I made a quick test on remix, incrementing a uint256 and looks like it is cheaper;

Without _checkOwner():

With _checkOwner():

Of course I deployed the same contract 2 times;


As @FreezyEx said, this saves deployment cost when the modifier is used multiple times in the same contract.

The corresponding PR: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3347

1 Like