▫️Lesson 2.3: Functions in Solidity
Module 2: Developing Smart Contracts with Solidity
Objective
This lesson aims to provide a comprehensive understanding of functions in Solidity, including their declaration, types, visibility, and modifiers. Functions are the primary way to execute logic and manipulate contract data in Solidity, making them a crucial aspect of smart contract development.
Function Declaration
A function in Solidity is declared using the function
keyword, followed by its name, parameters, visibility, modifiers, and return types.
Syntax:
Example:
Function Types
View Functions: Promise not to modify the state.
Pure Functions: Promise not to read from or modify the state.
Payable Functions: Can receive Ether.
Example:
Visibility
Public: Accessible from within the contract, by derived contracts, and externally.
External: Only accessible from external calls.
Internal: Accessible within the contract and in derived contracts.
Private: Only accessible within the contract.
Example:
Modifiers
Modifiers are used to change the behavior of functions in Solidity. They can be used to restrict access, validate inputs, or guard against reentrancy attacks.
Example:
Activity: Creating and Testing Functions
Implement a Contract: Using Remix IDE, create a contract that includes functions of various types, visibilities, and modifiers.
Test Each Function: Deploy your contract and test each function to understand how different types, visibilities, and modifiers affect function behavior and access.
Exercise
Hands-On Practice:
Extend the
FunctionExample
contract by adding a modifier that checks if the input value is greater than a certain threshold before setting the value. Implement this modifier in thesetValue
function.
This lesson has covered the fundamentals of functions in Solidity, including their declaration, types, visibility, and modifiers. Understanding these concepts is essential for developing sophisticated and secure smart contracts on the Ethereum blockchain.
Last updated