I haven't found any opinions about this online so far, so I'm soliciting opinions here.

What are the pros/cons of setting variables in the constructor of a Solidity contract versus having no constructor and setting those variables later via a setter method?

Are there significant gas tradeoffs? Is it just a matter of style/opinion?

Appreciate any thoughts :)


I think the question is too general in nature so the only possible answer is "it depends."

The right way to structure the contract depends on what the contract is supposed to do. Deployment is a specific step in the lifecycle of the contract. What needs to happen at that stage?

For example, it might be unacceptable to have an instance of the contract in an unconfigured state. If so, then do it in the constructor so everyone can be sure that such a situation isn't possible.

Upgradeable contracts using the Proxy system cannot be initialized in the constructor. In that case, the choice is clear.

In practice, I would say every parameter needs to be looked at separately. Should it be set by the constructor? Should it be modifiable? Should it be immutable?

In the case that something should not be modifiable, it will actually be easier to codify that with a constructor - otherwise you have to work out logic to make sure it doesn't happen twice. You can also use immutable to save on gas.

Hope it helps.

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.