Page 3: Contract Structure, State Variables, and Modifiers

3. Contract Structure, State Variables, and Modifiers

Efficient and secure contracts rely on clear data management structures and strict access control. Modifiers are particularly crucial for reducing redundant code and enhancing security.

3.1. Mapping and Struct

We use Mapping and Struct to structure and manage complex data.

struct User { 
uint256 id;
address userAddress;
}

mapping(address => User) public users; // Maps addresses to the User struct

3.2. Function Modifiers

Modifiers execute code before or after a function runs, used to check specific conditions. The most common example is onlyOwner.

address public owner; 
constructor() {
owner = msg.sender;
}

modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can call this function.");
_; // The original function code is inserted at this point.
}

function withdrawFunds() public onlyOwner {
// Withdrawal logic
}

3.3. View and Pure Functions

Functions that only read state variables but do not modify them should be declared view. Functions that neither read nor write state variables should be declared pure, saving gas costs.