SN

April 11, 2018

The benefits of stripping logic out of your controllers

Something I’ve been trying to do lately is take the logic out of my controllers, and put it into service classes.

It may feel like you’re fighting against the framework, but I think the benefits outweigh the cost.

It allows you to write more unit tests

Generally, you want your test suite to be comprised of mainly unit tests; some people have suggested a 9-1 ratio, which having written a test suite that is more feature tests than unit tests, I tend to agree.

Unit tests are fast.

They are fast because you don’t have traverse through the entire framework to test that class/function is doing its job.

Unit tests allow you to test in isolation.

I had a scenario where I needed to upload a video to S3, create a video in my database, and capture the first frame of the video as an image.

This functionality was split into 3 different service classes.

Taking the logic out of the controller allowed me to write 3 unit tests that ran in isolation, and one feature test that confirmed all 3 classes were working together.

If I had left the logic in the controller, it would put me in a situation where I would only be able to write the one feature test, which would be harder to debug when it failed.

I mean, I guess you could test your controller in isolation, but that feels gross to me for some reason.

Reusability

Taking logic out of your controllers makes your code more modular.

Continuing with the s3 upload scenario from above:

I had to export existing members, and their videos, from the old system into the new.

Because I had created those service classes I was able to reuse the existing functionality to complete the import.

If I had left the logic in a controller, things would have been more difficult and time consuming.

Nuance

I’m not suggesting you do this for every single controller method. If it’s a simple crud operation, I leave it in my controller and write a feature test for it.

You need to decide for yourself when it might be a good time to move controller logic into it’s own class.

There’s no wrong answer, which is one of the reasons programming is so difficult at times.

Are you new to Test Driven Development?

Join the mailing list! :)