design-patternsstructsolidityfactory-patternseparation-of-concerns

Struct Factories in Solidity


So I am working on a DApp in Solidity and would like to make use of Separation of Concerns. I have a Contract that adds and removes Users. My Users are of type Struct. So I thought I would write another contract, a UserFactory Contract utilising the Factory Design Pattern and separating the concerns since a UserManager should not be responsible for creating Users. Unfortunately I am unable to return Structs from my Factory Contract unless I enable ABIEncoderV2, but since this is an experimental feature it won't work in production. It seems that for Solidity I need to find a different approach to solve this design problem. Is there a go to approach for Solidity? Any help would be gladly appreciated. Thank you in advance!


Solution

  • You can return a tuple of user properties instead:

    mapping(uint -> User)
    type User struct {
       string name;
       string address;
       uint age;
    }
    function getUser(uint key) public constant returns(string,address, uint) {
         return (users[key].name, users[key].address, users[key].age;
    }
    

    But I believe that it's safe to use ABIEncoderV2 . Here is reference to official documentation

    ABIEncoderV2 The new ABI encoder is able to encode and decode arbitrarily nested arrays and structs. It might produce less optimal code and has not received as much testing as the old encoder, but is considered non-experimental as of Solidity 0.6.0. You still have to explicitly activate it using pragma experimental ABIEncoderV2; - we kept the same pragma, even though it is not considered experimental anymore