At the start of the function “require” is used to check if it makes sense to run the function at all. If the owner already has a dog, the function will do nothing. Using “require” has the advantage of not wasting any gas for the execution of this function.
At the end of the function “assert” is used in order to ensure, that the dog has its correct age assigned. If the age is not as it is supposed to be, something has gone wrong! So a rollback will be performed using up all the gas.
pragma solidity 0.5.1;
contract DogContract{
struct Dog {
string name;
uint age;
}
mapping(address => Dog) ownerToDog;
function addDog(string memory _name, uint _age) public {
/* Make sure that the owner doesn't have a dog already! */
require(ownerToDog[msg.sender].age == 0, "The owner already has a dog!");
ownerToDog[msg.sender] = Dog(_name, _age);
/* Check if dog age is correct and do a rollback otherwise! */
assert(ownerToDog[msg.sender].age == _age);
}
function getDog() public view returns (string memory) {
address owner = msg.sender;
return ownerToDog[owner].name;
}
}