I have a set of single purpose functions that I need in two separate controllers. Right now I just have duplicate code and I want to get rid of it. This code is part of the controller and doesn't belong in my service layer. Where would you put it?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
You didn't say what kind of logic it is that you are sharing. In short, is this controller logic or a helper function? The two methods of dealing with this in an object oriented language are inheritance and composition. Inheritance makes sense if there is a shared action between the two controllers. Composition makes sense the rest of the time. The example of using inheritance lies in my original answer below the divider.
It's not uncommon to have a utility class or a helper class depending on your framework. For example, in Java and C# web frameworks you might have a package/namespace for utilities. In Ruby on Rails, you might be taking advantage of the
Alternatively, you can make it a class you instantiate. The key to the above static class pattern is to make your functions pure functions. In other words, you pass in any state that it needs to do it's job, and the function does not reference any other static state in the system.
In either case, you would access it in each of your controllers like this:
You didn't say what your platform was, as that can affect the answer. Assuming that it is an object oriented language, the most common approach is to create a base class that both the controllers extend. For example in Ruby on Rails you might have:
You can translate the idea into other languages as well. The same approach will work for ASP.NET MVC, Apache Wicket, Grails, or just about any other object oriented web framework. If your language is not object oriented, then it really depends on how the framework is designed as to the best approach.