Function Visibility & Modifiers in Solidity: Gatekeepers of Smart Contracts

Solidity uses visibility specifiers and modifiers to control who can interact with functions and under what conditions. These tools are essential for security and gas efficiency in blockchain development.

Quick Reference Guide

Visibility Access Gas Cost
public Any contract/external call Higher
external External calls only Medium
internal Contract & children Low
private Defining contract only Lowest

1. Function Visibility Explained

Public Functions (Open Door)

function mintToken() public {
    // Can be called by anyone
}

External Functions (Outside Access Only)

function withdraw() external {
    // Can't be called internally
}

Internal Functions (Family Access)

function _calculateFee() internal {
    // Only within contract/inherited
}

Private Functions (Vault Access)

function _generateHash() private {
    // Only this contract
}

2. Modifiers: Conditional Guards

Built-in Modifiers

// Read-only (no state change)
function getBalance() public view returns(uint256) {}

// No state read/write
function add(uint a, uint b) public pure returns(uint) {
    return a + b;
}

// Accepts ETH
function deposit() public payable {}

Custom Modifiers

address owner;

modifier onlyOwner() {
    require(msg.sender == owner, "Not owner!");
    _; // Function body executes here
}

function changeOwner(address _new) public onlyOwner {
    owner = _new;
}

⚠️ Common Mistakes

  • Using public for sensitive functions
  • Forgetting payable on ETH-receiving functions
  • Misordering modifiers: function x() public payable onlyOwner

Best Practices

  1. Use external for callbacks to save gas
  2. Make helper functions internal or private
  3. Chain modifiers logically: access control first

Real-World Use Cases

  • πŸ›‘️ onlyOwner for admin functions
  • modifier duringSale for time limits
  • πŸ’° modifier minAmount for ETH checks

Comments

Popular posts from this blog

Mastering Events & Logging in Solidity: The Blockchain’s Communication Channel

πŸ”’ Secure Your Code: Top 5 Solidity Vulnerabilities & Proven Fixes

πŸ”₯ Gas Fees Demystified: The Ultimate Guide to Efficient Smart Contracts