Smart Contracts vs OOP Class – Understanding Their Similarities

contract-development

Can I think of a smart contract as being analogous to a Class in an object-oriented programming language (e.g., Java)?

Each transaction that uses the contract essentially instantiates an object of the contract (or class), and then that object (i.e., transaction) maintains its own properties like private and public variables, as well as inherits properties from other locations.

Is this analogy correct?

Best Answer

I think people are probably going to say yes, but I would argue strongly that it is not.

In a C++ class, for example, the data that comprises the class is per-instantiation. In other words classInstance1 and classInstance2 each have their own state.

In Solidity there is only one contract in the program. In this sense the state of the contract is a singleton -- all the state is program-wide level. It's as if the entire class were global. Another way of saying this is that all the data fields of the contract are like C++ static members.

This is exactly why the DAO got hacked. The single DAO contract's state was global, and upon re-entry the same data was being accessed in both the caller and the called into function.

As far as every transaction instantiating an object, that's not quite right. The contract is instantiated on creation and the state persists across transactions.

Related Topic