Rule of thumb
You can look at this problem from two perspectives:
- Overall
*Util
methods are often a suggestion of bad code design or lazy naming convention.
- It is legitimate design solution for reusable cross-domain stateless functionalities. Please note that for almost all common problems there are existing solutions.
Example 1. Correct usage of util
classes/modules. External library example
Let's assume you are writing application which manages loans and credit cards. Data from these modules is exposed through web services in json
format.
In theory you can manually convert objects to strings which will be in json
, but that would reinvent the wheel. Correct solution would be to include in both modules external library used to convert java objects to desired format. (in example image I have shown gson)
Example 2. Correct usage of util
classes/modules. Writing your own util
without excuses to other team members
As a use case assume that we need to perform some calculations in two modules of application, but both of them need to know when there are public holidays in Poland. In theory you can make these calculations inside modules, but it would be better to extract this functionality to separate module.
Here is small, but important detail. Class/module you have written is not called HolidayUtil
, but PolishHolidayCalculator
. Functionally it is a util
class, but we have managed to avoid generic word.