Beginner

Solidity Basics: Your First Lines of Code — Good practice

Know how a Solidity file is structured.

Developer Beginner
7/9 — Solidity Basics: Your First Lines of Code — Good practice

Make intent loudWrite SPDX and pragma first, then declare contract, state, and functions with explicit visibility and mutability. Do not rely on defaults.

Keep ABI slimExpose only what you need; prefer internal helpers; add purposeful getters instead of public state when you need custom formatting or checks.

DocumentUse NatSpec for public/external functions. Note expected units, revert reasons, and side effects. Keep compiler ranges consistent across repos.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Counter {
    uint256 private _count;

    event Incremented(uint256 newValue);

    function getCount() external view returns (uint256) {
        return _count;
    }

    function increment() external {
        _count += 1;
        emit Incremented(_count);
    }
}
Key points
  • Explicit visibility and mutability:Everywhere; avoid defaults.
  • Tight pragma range matching:Your toolchain and audits.
  • Prefer internal/private helpers; expose:Minimal public surface.
  • Use NatSpec on external/public:Functions to guide integrators.
  • Choose data locations deliberately:And benchmark if unsure.
  • Emit events for state:Changes users care about; keep storage for truth.
  • Lint/style check Solidity (solhint/solhint-plugin-prettier):To catch slips.
Steps
  1. Start every file with SPDX + pragma, then a minimal contract skeleton.
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.24;
    
    contract Counter {
        uint256 private _count;
    
        event Incremented(uint256 newValue);
    
        function getCount() external view returns (uint256) {
            return _count;
        }
    
        function increment() external {
            _count += 1;
            emit Incremented(_count);
        }
    }
    
  2. Header only: quick copy for SPDX + pragma lines.
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.24;
  3. Add explicit visibility/mutability to:Every function and state variable.
  4. Prefer internal helpers; expose:Only the functions external callers need.
  5. Add NatSpec comments for:Public/external functions to guide integrators.
← Previous section
Next section →