Solidity exposes state variables and functions to internal
and external worlds using the visibility modifiers. There are four types of
visibility modifiers public, internal, private and external.
Functions can have all the four visibility modifiers, the default
visibility modifier for functions is public. State variables cannot have
external visibility modifier and the default modifier is internal.
Below is the brief description and usage of these visibility
modifiers for state variables and functions:
public
Public functions are part of the contract interface and can
be either accessible within the contract or via messages. Public state
variables are accessible similar to the functions.
contract Service {
address public arbiter; // 0x is the default
arbiter for every contract
address contractor;
///
@notice Once the service is completed, client pays to the contractor
function
pay()
public {
contractor.transfer(amountPaid);
amountPaid = 0;
}
}
For public State variables Solidity automatically generates
a getter function. In the above contract, arbiter is defined as public,
Solidity generates a function called arbiter which returns the arbiter address.
internal
The internal functions and state variables can only be
accessed within the contract or derived contracts. This is similar to protected
variables in C# and other object oriented programming.
In the above code, contractor state variable does not have
any visibility modifier. As per default configuration, the contract state
variable will be on internal scope.
private
Private functions and state variables, like the name
indicates, are accessible within the contract they defined. They are not
available in the derived contracts.
external
An external function is similar to public function. In
addition from being called internally and via transactions, external functions
can be called from other contracts. To call an external function internally it
needs to be prefixed with this (this.fund()). External functions can access other functions
and state variable directly (without the prefix of this)
/// @notice based on
the agreement, client will fund the contract
/// this amount will
be payed to contractor at the end
function fund() external onlyClient payable {
amountPaid += msg.value;
}
As mentioned earlier State variables cannot have external
visibility modifier. Only functions can have external visibility modifier.
No comments:
Post a Comment