Create a mapper easily

  2 mins read

If you are used to implement clean architecture in your project you will know that the mappers are a very boring part to write. The mappers are needed to send data across boundaries and you need to be careful while you are writing it, because if you forget to map any field the data will not be displayed.

I want to share how I create it, it´s just a trick but I think will be helpful for almost all if you create them manually.

  1. Go to the Object model that you need to map, copy and past to a sublime text editor
  2. In sublime, search for occurrences with the regex flag activated
  3. regex

  4. Look for “set\w+” and press Alt + Enter, now you can see all the matches of the setter methods selected:
  5. setters selected

  6. Press CMD + C or CTRL + C if you are in Linux/Win, return to your IDE and paste the contents
  7. With the alt key pressend drag the cursor to start the multi-selection feature, and set the caret at the start of the line
  8. Write “object.”
  9. caret at start

  10. Press CMD + -> or End key to go to the finish of the line. write “(otherObject.”
  11. Return to Sublime and repeat the previous process but for the getters, so look for: “(get|is)\w+\(\)”, press alt + enter, copy and return to the IDE and paste the contents
  12. paste geters

  13. Press CMD + -> or End key to go at the end and write “;”
  14. Go to Code -> Reformat Code to format all the code and complete the rest of the method.
  15. mapper done

Done! You completed your mapper, What you won?
– You don’t forget any of the fields
– Is less boring than write all the fields one by one

Written by:

Christian Panadero Martinez

  • Arturo

    Some questions (I have mappers implemented in my app and I’m suffering efficiency problems parsing large objects):
    – Doesn’t the mappers violate the DRY principle?
    – Each object has a cost of creation, if you have 100K objects your efficiency will decrease dramatically isn’t?
    – Do you have a solution working with ORMs and Json parsing annotations to have everything decoupled?

    Take a look to this discussion:

    • Hi Antonio, sure, it violates DRY and you may have a performance impact if you have a lot of objects.
      But in software development all is about trade-offs, a mapper is a super util object to send data between layers. It allows you to decouple your domain and data layers, for ex, in an application that uses an API to fetch new data and a database as its storage for that data, your domain layer shouldn’t know about implementation details of your api/storage. Those details are the extra fields that you need to persist on your database, foreign keys, relations, etc… and in terms of the API annotations or methods of how to transform json objects to data objects. As per the performance impact in a medium-large app I didn’t felt any dramatic slow down doing this process.