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?


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.

| improve this answer | |

Although Ethereum does treat a contract like an object oriented class, the instance of the class do not reside in the transactions. The instance lives on the blockchain where transactions can make calls to it.

There are different frameworks out there for Ethereum that you can quickly download and get a sense of this with their demo contracts complete w front end code that issues transactions to them. I like both Truffle and Embark: https://github.com/embark-framework/embark

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.