0
pragma solidity ^0.4.16;

contract FunctionTest {
    bool public foo = true;
    string public name;
    uint256 public counter = 0;

    function setName() public {
        //
    }

    function writeToStorage() {
        foo = !foo;
    }

    function readFromStorageConstant() public constant returns (bool) {
        return foo;
    }

    function readFromStorageView() public view returns (bool) {
        return foo;
    }
}

I need to accomplish this: Modify the function setName in a way that would allow setting the value of name

How do I go about this? I have no clue as to how to proceed, any hints?

  • 1
    Sounds like homework you need to do? – Lauri Peltonen Apr 27 '18 at 13:06
  • Can you elaborate more on what you mean by "setting the value of name"? – Achala Dissanayake Apr 27 '18 at 13:06
  • The key words are function arguments and change state. Don't give the answer, you need to go through by yourself – Greg Jeanmart Apr 27 '18 at 13:08
  • no @LauriPeltonen, not homework, I wish they gave solidity homework. – rattle99 Apr 27 '18 at 13:13
1
  1. Use bytes32 instead of string; it uses less gas because it fits in one 32 bytes storage slot (a.k.a word) while string is dynamically allocated, most "strings" that you're going to pass/use can fit in 32 bytes; so stick to that.
  2. Initialize the value of your state variables inside of a constructor; constructors used to be a function that has the same name as the contract name, now (since Solidity 0.4.22 I think) you need to define them with the new keyword constructor.
  3. Always declare visibility (public, private, internal, etc...); it's better for readability

Below is the modified contract (I also updated setName to your requirement):

pragma solidity ^0.4.16;

contract FunctionTest {

    bool public foo; 
    //bytes32 instead of string
    bytes32 public name; 
    uint256 public counter;

    //Back in the day, constructors would have the same name as the contract (e.g. FunctionTest(){})
    constructor() public{
        //Initialize state variables here
        foo = true;
        counter = 0;
    }

    function setName(bytes32 _name) public {
        //Always validate input data
        require(_name > 0);
        name = _name;
    }

    function writeToStorage() public {
        foo = !foo;
    }

    function readFromStorageConstant() public constant returns (bool) {
        return foo;
    }

    function readFromStorageView() public view returns (bool) {
        return foo;
    }

}
  • Thanks! I was curious to know what advantage does the constructor give? – rattle99 Apr 27 '18 at 13:29

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.