2

I understand that the difference is that, while neither may change the state, view may read the state and pure may not. I also understand that it's useful to distinguish possibly state-changing functions from those guaranteed not to change the state.

My question is, why is it useful to indicate that a function won't even access state? Why doesn't view suffice?

  • Probably in order to allow a higher level of compiler optimization for pure functions. And by the way, you could just as well ask the same question about view (i.e., why is it useful to indicate that a function won't change state?). – goodvibration Aug 25 '18 at 10:53
  • Oh, and another reason - it's there to protect you from doing things you didn't initially intend to. By declaring a pure function, you "remind" yourself (and others), that this function has no intention of reading state variables, nor to invoke any other function which reads state variables. It's kinda like const in C/C++. If you later decide to change functionality, you get this compilation error reminding you of your original design intentions. – goodvibration Aug 25 '18 at 11:01
  • Well the other question you propose - why is it useful to indicate a function won't change state - is both covered well elsewhere and more obvious: changing state costs money. – Joseph Aug 26 '18 at 3:46
3

If a function is pure, then no matter how many times you call it, if you pass the same parameters, it will always return the same value(s).

Example:

function pureFunction(uint a) pure returns(uint){
    return a + 5;
}

will always return 6 if you pass 1 as parameter a.

However, if the function is view, it's reading from the state, which may have changed since the last time you called it.

Example:

uint B = 5;

function viewFunction(uint a) view returns(uint){
    return a + B;
}

will also return 6 if you pass 1 as parameter a. But if another function modifies the value of B, then next time you call viewFunction(1), it will return something different.

| improve this answer | |
0

I find the answer above confusing. It really boils down to this:

Pure does (can) not access state only memory/stack

View can access state but not make changes to it, just query (+ ETL).

No state changes in a transaction call means no gas cost, we're letting the compiler know that so we can get the right behaviour (sendTx vs call) after deployment.

| improve this answer | |
  • 2
    This doesn't answer the question. The dude says he already knows the difference between pure and view. – goodvibration Aug 25 '18 at 10:55
  • And what's the common denominator? "no state modifications possible". – Nico Vergauwen Aug 25 '18 at 11:05

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.