Contract Structure
What is a Contract?
Last updated
What is a Contract?
Last updated
Having now understood the layout of a Solidity file and values, we will tackle the concept of the smart contract itself. While there are many different ways to approach learning about the structure of a smart contract, we will approach it from the perspective of object-oriented programming; as it will become evident later on, Solidity itself is an object-oriented programming language (perhaps one can call it contract-oriented programming)
Object-oriented programming is defined by... well, objects. In particular, developers of object-oriented programming lanugages are able to leverage classes - blueprints that one can instantitate to create objects.
A great example of understanding object-oriented programming is by looking at dog breeds. Consider the Poodle; if we consider poodles to be a class, then any living poodle can be consider an instance of the Poodle class.
Approaching object-oriented programming from a technical perspective, classes are defined by the following two characteristics:
Fields: the state of objects
Methods: the behavior of objects
Contracts, like classes in object-oriented programming, consist of both fields and methods. In practice, the fields of smart contracts come first and is followed by the contract methods.
Above, we have a contract called Rectangle which represents... a rectangle. All contracts start off with a contract header, which, in the case of Rectangle, is defined by contract Rectangle
. Following the contract header, we have the definition of Rectangle enclosed in curly brackets; this is where we will find the contract fields and methods.
Contract fields are stateful; as an example, if we deployed an instance of the Rectangle contract, its associated length
and width
fields would forever persist on the blockchain, and any changes to said fields would be peristed as well.
Contract methods are the specified behavior of smart contracts; in the case of Rectangle, the function compute()
calculates the area of the rectangle contract.
Contract fields are more commonly known as state variables (i.e. they are persistent variables associated with a contract's state). Variables that are marked as memory
or are allocated via the new
keyword are known as memory variables (and are found within function bodies).