DEV Community

Cover image for A pattern a day keeps the reviewers away - [Day 2] - View Object Pattern
Antonio Djigo
Antonio Djigo

Posted on

A pattern a day keeps the reviewers away - [Day 2] - View Object Pattern

Hey 👀✨

During the past few months, I've been working on a back-end project made with Ruby on Rails. Last year I was working as a Front-End developer, I've never had the opportunity to apply design patterns almost anywhere, until now.

It's a pretty useful thing, that probably every developer that works with objects should at least know and practice, and this is why I'm here, to give you (and me!) a daily short post about the different design patterns that exist (or at least, those that are used the most), with an example, and an explanation.

Because doing good code will help you, your workmates, and those who will be in the future.

Teamwork!


Do teamwork!

This day, I'll tell you about another interesting pattern that has been around for a long time. It is called View Object Pattern (aka. Presenter)

Having logic in our views is a reaaally bad idea. This would make views testing a real pain in the (add your favorite word here), and it's extra work that no one likes. Also, your views should always have as little embedded dynamic code as possible.

You'll be able to get rid of these two problems by applying the View Object pattern (You may also have heard about MVP pattern, which is pretty similar).

You are the real MVP

To generate a view object, you have to create a new class. Inside this new class, you will get anything you need from your model or controller, and you will do all the logic you had in your views, for example, retrieving all the users with that specific name you want.

Let me explain the example before you read it. We are creating a class to manage the logic for a discussion view, and we want to generate the user name and a timestamp of when the user wrote something. To do that, we will move the logic into our new View Object, and we'll call this method, just as it's shown below.

Things you need to have in mind when working with views:

  1. Use Law of Demeter, only one dot functions.
  2. Don’t hit database in views, please!
  3. Views are not for the logic, do not assign variables here.

Now, in our controller, we can initialize the object and call it, making both the order logic and the dashboard initialization easier to read, just like this:

Now, your view now looks ✨ shiny and clean ✨

And this is my second article about design patterns for the series "A pattern a day keeps the reviewers away".

Bye!

I'll try to keep posting every day one of the different patterns that are around. I can't promise I'll fulfill this task every day though!

You can read more about this pattern at:

  1. JTWay View Object tutorial
  2. Nopio View Object tutorial

Also, you can follow me so you are tuned to whenever I post something through my Twitter account!

Top comments (0)