I’m building a perl application which does the following operations:
- Copy a bunch of files (class fileFetcher )
- Parse each file (class fileParser)
- Store some data from each file in a database (class dbHelper)
Now, should I, in my main.pl (entry point of the script), construct an instance of each of these and call the appropriate methods?
or is it better practice to have a separate “Application” class that does all the instantiations and method calls, and let the main script just have a call like Application.run(args)
?
The class, would exist just to instantiate and call methods on things, and doesn’t seem right.
7
Apply the YAGNI principle – as long as you have only 3 objects, and only one entry point into your script, you most probably don’t need that additional Application
class, so don’t create it. This would not make your code more readable or better maintainable – so why bother (for now).
However, when your script becomes bigger in the future, and your main.pl
gets additional responsibilities, it may be a good idea to refactor the instantiation code of those combined operations into a separate function. Giving that function a meaningful name describing the operation as a whole would be very good idea. Furthermore, when your program grows to a state where this operation is just one of many other operations, that would be an even better reason to refactor things out of main.
When it shows up later that this operation needs additional “global” state or environment information, then this new function may be refactored into a class to make that global state a member variable of that class. That class typically won’t get the name Application
, since this name is not very descriptive for what the operation does. But refactor when this happens, not beforehand.
AFAIK the notion of having a separate Application
class comes from some (mostly C++) GUI frameworks where this is standard way of definining a kind of entry point and globally available object. See, for example, this SO post, about the QApplication
class in the Qt framework. I don’t know if there are Perl frameworks out there with a similar approach, but as long as you are not using or creating such a framework, I don’t see a point to add an Application
class to your Perl script.
Keep It Simple
Don’t create a separate Application class it’s not necessary. Nothing bothers me more than having to turn over rock after rock after rock to understand what’s going.
I don’t think it’s necessary in this case, but I also don’t think it’s necessarily a bad decision — but if you do, your name is. It’s not Application, that is effectively what your main is. What it is, is a workflow or a process. Application doesn’t need to be an object and doesn’t benefit from being an object. Your process might.
If you think it possible or likely that your process may be incorporated into a larger process, then go ahead and make it a class, until then, I’d leave it as it is.