Search code examples
javascriptsolid-principlessingle-responsibility-principle

Does function violate SRP if it log errors on top of primary purpose?


Does this code violate SRP principle?

function sendError(error) {
    log(error);
    response.status(500).send(error.message);
}

Solution

  • The short answer would be yes, to an extend.

    SRP states that behavior that changes together should live together.

    Logging is as cross-cutting concern (System wide concern), meaning that it is functionality applicable throughout your entire application.

    In your function, logging might be applicable and not break SRP as it changes together, but how we handle this cross-cutting concern could be improved.

    The way in which you handle your logging will depend heavily on the framework which you are using. The principles still stay the same though. The basic rules are as follows:

    1 - You want to do logging in one central place, not all over the application.

    2 - You want to throw as early as possible and catch as late as possible. (This leaves you with a big stack trace, helping you to figure out what went wrong.)

    To achieve this, the most common solution is to use middleware. Libraries such as Express allows this. Your custom middleware can catch exceptions at the last possible moment and log all unhandled exceptions.

    Cross cutting concerns should be carefully managed, as they can very easily bloat and break code.

    For some extra reading on the subject, you can read up on cross cutting concerns and aspect oriented programming.

    Let me know if there is anything that I can clarify further. :)