The single line responsibility principle is very clear with its intention: one line must do one and only one thing. The intention of coding with this in mind is to get a more readable code and an optimized one.

Experience and knowledge could help you writing readable, mantainable and clean code but, following the Single Line Responsibility principle will help you to be sure you’re doing it.

Miguel Ángel Durán1Miguel Ángel Durán. 2018. Single Line Responsibility, one line does one thing.

It doesn’t matter if is Javascript, PHP, C#, Java, React, Laravel, Python or any other technology, this is for writing code in general.

📍Single Line Responsibility in action

var word = wordList[wordPosition].toString().substring(0, characterPosition);

The above line is from a project I have on codepen, as it is notable, the same line does several tasks to get the required value. That behavior should be avoided as much as possible. Instead of grouping everything on a single line, this could be a viable alternative.

var word = wordList[wordPosition]
           .toString()
           .substring(0, characterPosition);

Why the second way is cleaner or “easy to read“? Because it is noticeable that one line takes the original value, the next line does a conversion and the last one another operation. In other words, one line does one thing.

$books = t_book::orderBy('author','asc')->where('year', $year)->where('category', $category)->get();

On that example are several clauses on a single line, the whole query is long and hard to track. But using the Single Line Responsibility makes it clear regardless of the number of clauses our query could need.

$books = t_book::orderBy('author','asc')
                ->where('year', $year)
                ->where('category', $category)
                ->get();

As Ángel Durán says in his article, this is not an unbreakable rule but is a guide to write in a clear way. Every case is different, and sometimes the context makes us do several tasks on a single line. Analyze your options but keep this principle in mind.

References   [ + ]