C# – Using Generic Helper Classes in Projects

cobject-oriented

I have a generic helper class (1) that can be used in other projects also. Imagine something like basic handling of file and folders, something useful and DRY that always come in handy.

I have another class (2) that is project specific, but it uses the generic class (1) to accomplish things.

The generic helper class (1) is used by creating a new object of it in specific places where is needed in the project.

GenericHelperClass ghc = new GenericHelperClass();

Same goes for the project specific class (2), is being used by creating a new object of it in specific places where is needed in the project.

ProjectSpecificClass psc = new ProjectSpecificClass();

But as I said the project specific class (2) uses the generic helper class (1) to do stuff.

So here I thought, that the project specific class (2) should have its own private generic helper class (1) to do its job.

But wait, there is going to be an instance of that generic helper class (1) in the project already, so why creating another one? Let's just pass that instance of (1) on the constructor of (2).

So (2) is now created like:

GenericHelperClass ghc = new GenericHelperClass();
// code and code and code
// .
// .
ProjectSpecificClass psc = new ProjectSpecificClass(ghc);

with this I have only one object of GenericHelpClass, and I have avoided using static.

The question is: Am I wrong here or am I just creating spaghetti-dependencies or something? Any suggestions?

(the names selection GenericHelperClass/ProjectSpecificClass is just for demonstration)

Best Answer

There are some reasons which can make this design the better alternative:

GenericHelperClass ghc = new GenericHelperClass();
// ...
// using `ghc` here for other purposes
//...
ProjectSpecificClass psc = new ProjectSpecificClass(ghc);
  • if the construction of ghc is slow or needs lots of resources, it might be better to construct the object only once

  • if after construction of ghc the object has to be initialized in a specific way before it can be used, it is better to do this initialization only once

  • you want to expect the constructor of ProjectSpecificClass an object of type IGenericHelperClass (an interface) to make it possible to "mock the object out" for unit testing purposes

If none of the reasons apply to your case, keep things as simple as possible for the user of ProjectSpecificClass and construct the object inside, where it is needed, even when this is done twice. Standard object construction in C# is very fast, as long as there is no "heavy-weight" constructor code in place.

Related Topic