1

In the sample code below, I wanted to check the input data (non-empty) using require/assert and create the contract if it passes the two test.

The code is not working. It still creates an instance of a Contract ABC, if I provide just the _name value as input, without the _number.

How do you make the function "create" exit if the require conditions are not met. How would I tweak this code to achieve the above? Do I have to wrap the require condition with an if-then-else to return false if tests fail? Thanks.

pragma solidity ^0.4.15;
contract ABC {

    bytes32 public name;
    uint public number;
    event Log(string _myString);        

    function ABC (bytes32 _name, uint _number) public {
        Log("object created");
        name = _name;
        number = _number;

    }
}

contract XYZ {

    ABC myABC;

    event Log(string _myString);

    function create(bytes32 _name, uint _number) public returns (bool isSuccess) {

        Log("checking name");
        require(_name != 0);

        Log("name valid, now checking number");
        require(_number != 0);

        Log("name and number non-empty, creating a new contract");
        myABC = new ABC(_name,_number);

        Log("new contract created");

        return true;

    }


}
1

2 Answers 2

2

As far as I know, in Solidity there is no "null" equivalent. This means you need to get a bit clever with how you check for empty values.

bytes32 is really an array with a fixed length of 32. In order to check for an empty value here you can try the following:

require(_name[0] != 0);

This will check whether or not the string being passed in is empty.

As for the uint, I made the following change in the XYZ contract:

uint public number;
...
number = _number;

Since public variables in Solidity have "built-in" getter functions I was able to check its value (after deploying it on Remix). It appears that it is initialized as 0. This means that as long as you consider 0 to be a valid value to be passed into ABC you don't even need to check whether or not _number is non-zero.

Hope that helps!

1
  • Thanks @Hcastano. Thanks for the suggestions. It helps.
    – userDSSR
    Oct 5, 2017 at 8:38
1

I tried your code and it is working as expected. It is throwing error when not passing the _number argument to create method of contract XYZ.

You can try to compile the code on remix and check the same.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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