DEV Community

Nick Mudge
Nick Mudge

Posted on

4

Solidity: AppStorage for distinguishing state variables and preventing name clashes

Solidity state variables, immutable variables, constants, local variables and function names can look the same and it is possible to have name clashes, where for example a local variable or function name is named the same thing as a state variable, which can reduce code clarity and cause frustration.

AppStorage is a variable naming technique which makes state variables clear in your code and prevents name clashes with other kinds of variables and function names.

This is how it is done: Define a struct in a file and name the struct AppStorage. Define all the state variables in your application within the AppStorage struct.

Then in your smart contracts import the AppStorage struct. Then define this state variable: AppStorage internal s;.

That's it. Now you can access all your state variables by prepending an "s." to them.

Here is a simple example:

  1. Define AppStorage that contains all your state variables:
// AppStorage.sol
struct AppStorage {
  uint256 secondVar;
  uint256 firstVar;
  uint256 lastVar;
  ...
}
Enter fullscreen mode Exit fullscreen mode
  1. Import it and use it in contracts:
import "./AppStorage.sol"

contract Staking {
  AppStorage internal s;

  function myFacetFunction() external {
    s.lastVar = s.firstVar + s.secondVar;
  }
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay