Search code examples
methodscode-organizationreturn-type

same method, multiple return types. code organization


Let´s say I a have an User class and I want to return all the users in my database. For that i have create a method called getAll();

I need to call the method in different parts of my application and return the data in different formats. I might need all users separated by commas to put in some "where in" condition, or in json format to make an api, or as array, for example.

Whats is the best solution to organize my code?

Possible solutions: 1.Pass a fetchMode variable to the getAll function so i can format the return value accordingly. 2. Create a proxy method "findAllAsArray", "findAllAsJson" etc, which calls the the original getAll method and formats the response. 3. Allways return the result in a standard format (ex: array) and then create some generic methods to convert between formats: ex: arrayToJson, arrayToCsv, etc and use them when I need the results in other format than the standard.

The method 1 might make the getAll method too complex, if i have many formats needed. The method 2,might adding too many extra methods making my class more complex. The method 3, not sure but the data should be returned in the needed format from the model i think. Converting it in the controller, it´s probably not the best solution.


Solution

  • Create a new class, e.g. "Users," which contains the raw data. Users is immutable: Once initialized, its state never changes. Now have getAll() return an instance of Users, initialized with the raw data that getAll() created. Result has, for each format, a public method which formats the raw data appropriately and returns it.

    In pseudo code:

    class User:
      method getAll:
        users = # fetch the users
        return Users.new(users)
    
    class Users
      method initialize(users)
        # Save users to a member variable
      method json:
        # Return users formatted as json
      method csv:
        # Return users formatted as csv
    

    To retrieve all users in json format:

    users.getAll.json
    

    To retrieve all users in csv format:

    users.getAll.csv