Do you prefer repeating code instead of utility classes?

user2684198 :

We have a service in Java that deals with a lot of user-uploaded files, and tasks that prepare these files for different models to execute with.

One such phase of preparation included overriding values in json files. 4 out of 10 tasks were supposed to do this.

I created a static utility class that contained a function to override a value in a json file, something like

public static class ParameterUtils {
   public static String overrideParameter(String originalContent, String key, String newValue) {
     //4 lines of code that overrides this value and return modified content.
   }
}

However, my senior developers said that this utility class hardly offers any value, while I was trying to preserve the DRY principle. At the end I did get rid of this utility class, and now the 4 lines of code to override a value in a json file reside in 4 different files.

Do you think that this class and method are not good from OOP's view? Why and why not?

vikarjramun :

No, it is definitely bad practice to duplicate (slightly-complex) code in multiple places.

The DRY principle says "Don't Repeat Yourself". This is something to keep in mind, you don't want to repeat yourself by instructing the computer to override this parameter multiple times.

However, there may be better places to put this than in a static utility class which has only a single method.

If the 4 files you use it in all extend a certain class, maybe make it a protected static method there. Or perhaps place it in the class which returns JSON strings.

However, passing around JSON as a string seems like a code smell, especially if you are manipulating it through string manipulations. It might be a good idea to use a JSON library such as Jackson or org.json. If you use Jackson's databind feature (the most popular way to use Jackson), you create a POJO with actual getters and setters, and Jackson takes care of converting it to JSON. In the case of org.json, you work with a JSONObject class, which is very similar to a Map<String, Object>, and you mutate it like you would a map, and can convert it to and from a String with a single method.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327352&siteId=1