1

I'm new to the SOLID principles. I have this scenario:

class ErrorClass {

   constructor(name: string, description: string) {
      // 
   }

}

class Class1 {

   public someMethod() {
         try {
            // good scenario
         } catch (error) {
            throw new ErrorClass("Error Name","Error Description");
         }
   }

}

Is that wrong? Am I allowed to call ErrorClass directly from Class1 or am I supposed to inject ErrorClass into Class1 as a dependency? I'm worried that my Class1 constructor can get bloated if I have to inject different error classes along with other classes it might also depend on?

Grateful for any help or advice!

Thanks

viztastic
  • 1,815
  • 1
  • 17
  • 17
  • Does it make *sense* to inject the exception that a class would produce? That would mean that you cannot try to catch a specific exception, e.g., `UserNotSignedInException` and do a special handling. If you're injecting the exception constructor then you can inject a `NotEnoughPylonsException` instead and now your class will be throwing that. But you won't be catching it. Unless you also inject the exception at the catch location. In which case, you just made a roundabout way of throwing and catching the same exception, since you still need to run the same code when the user wasn't logged in. – VLAZ Sep 22 '21 at 08:39
  • Thanks so much @VLAZ are you saying it’s not always a violation of solid to call an error class directly from my main class? – viztastic Sep 22 '21 at 08:40
  • 3
    SOLID should not be taken as gospel. There are some cases where you can choose not to follow it. For example, there is logging. If you have some code that logs stuff in the middle of other code, that's technically a violation of the SRP. You could work around it and make it actually obey SOLID but you'd be throwing a lot of infrastructure at a very trivial problem. – VLAZ Sep 22 '21 at 08:48
  • I would argue that in this scenario your `ErrorClass` is very much defining a value object (i.e. an immutable object without an identity or any behaviour apart from a container for immutable properties), and as such you don't need to inject them. – biziclop Oct 28 '21 at 15:22

1 Answers1

1

I would suggest you read upon Cross-cutting concern. Here are a few links:

  1. https://en.wikipedia.org/wiki/Cross-cutting_concern
  2. https://www.c-sharpcorner.com/UploadFile/vendettamit/managing-cross-cutting-concerns-the-logger-and-logging/

Please note, that in most cases they give example of a Logger class as a Cross-cutting concern - a logger is something that every class needs, and according to the SOLID principles it should be injected as a ctor parameter to every class, right? Wrong. Logger class is an exception to the SOLID principles because it is a Cross-cutting concern.

And in your case, your ErrorClass is also a Cross-cutting concern. Therefore, it should be a global static and not injected as a parameter to ctor.

Refael Sheinker
  • 713
  • 7
  • 20