Main purpose of utility classes

Asked

Viewed 2,572 times

15

What is the real function of utility classes? Would only reduce maintenance and repetition of code or would go beyond these functions?

Would have some way (convention) to use these classes correctly?

2 answers

11


The term can be widely used.

As far as I know, there’s nothing very definite about how to use it. Some people say never do this, at least not in the traditional way as they usually do. They usually get the name auxiliary, secondary or helpers (helpers).

Static class

Utility classes are usually static.

Some people think that this should never exist. Some people think that they hurt the design object-oriented, and this would be a deadly crime.

There really is a problem with this kind of class when there is global state. Even so, it does not mean that it should not actually exist. But it is preferable utility classes without a global state. In general, utilities have no state.

Another problem: it is more difficult to test code with these classes. It is difficult to replace it. It has techniques for this but it complicates a bit. On the other hand I do not think that every rule should be followed, especially if it is exclusively to facilitate the test. The main code is that it should be easy, the test is secondary.

Another reason they often complain is that it tends to join methods that have little or no relationship in a class. This, in theory, would reduce cohesion. But then the problem is not that the class is utilitarian, but that it is poorly designed. Anyway, even when this happens, if you think about it, it doesn’t usually cause any real problems. Only a purist, academic, dogmatic advocate this. Look both ways and choose which one will bring you better results. If you prefer cohesion at any cost, make utility classes of one method only. Or more if you can still maintain the cohesion (read carefully there not to exaggerate in the attempt of cohesion for no reason).

It is utopian to think that the responsibility is always clear. And if it is in "the doubt I did" ends up having a design too complex.

If static classes were not useful they would not exist in language. It is not possible to be dogmatic.

But utility classes can be instantiated as well. As far as I know the term does not require the class to be static. When this occurs they are called helper classes, but the terms are usually used interchangeably. I won’t go into details because I don’t know if the question covers this.

Why use

One of the biggest reasons to do this is to avoid code repetition. And this facilitates maintenance.

The world’s most experienced and pragmatic programmers use it in the most complex and widely used projects in the world. This doesn’t cause real problems when you know what you’re doing. In fact, you find a tiny amount of mostly unimpressive projects that avoid these classes.

Stop using just to say that met a paradigm does not solve problems. But it can bring others. If you’re not going to create a utility class, where does a naturally isolated method that needs to be used in various places go? How are you going to separate what is the fundamental of a class from what is merely an accessory? How will you extend the functionality of a class without having to inherit? How will you eliminate the dependency of this without repeating code?

Of course, those who do not know how will make mistakes. But the problem is not of the tool is of the user of it. As every tool there is no perfection in it, it does not suit everything. There is designs that become too complex when you discard the right tool for the situation.

Object-oriented design

The utility class can increase the cohesion of the classes that use it. The "main" classes do only the least it needs to do leaving for the utility class to do what is accessory to it.

On the other hand it may violate encapsulation. OOD often says that everything related to the object must be close to it. Practice shows that this hurts other principles, but anyway... And today many people admit that blindly seeking OOD is not the best option. Others still think this. Today one prefers composition over inheritance, the largest cohesion that extreme encapsulation, etc.

In general these classes need to be able to be more generic. If it will meet only one class it is probably doing something wrong anyway. But some people actually think this is interesting. There is a current of thought that says that there should only be methods in the main class that access private members. Everything else should come in auxiliary class(s). This gives more cohesion and facilitates maintenance by giving more flexibility. More modern languages encourage this - interestingly returning to what was before, was good and ideology misrepresented.

In some cases linking the methods of these classes with interfaces may be a good idea. So you can tell who should use these classes. See Programming for interface and not for implementation, why?. Facilitates the principle of interface segregation without duplicating code.

Several Patterns design They get more complicated when you choose to avoid this kind of class. In fact some of these patterns become almost automatic when you separate the responsibilities correctly. Proponents of pure OOD usually swell the classes to get the one from encapsulation. Of course it’s always done by bad programmers. The good ones know when to avoid this.

Research here or elsewhere the problems that people have in software development and you will see that they are not because there are utility classes. And it turns out that many are poorly made, yet they don’t cause the real problems in your code.

Completion

It often takes a huge amount of time to solve an unlikely future problem that will save you little time.

Use the tool at the right place and time. Learn to use it. Learn everything it can help you or harm you. And if you have specific questions, ask here.

Utility classes organize code, separate responsibilities, reduce code repetition, simplify maintenance.

Utility classes are not bad, bad programmers create and use utility classes badly.

You can facilitate or hinder your project by creating a utility class. Most projects will benefit from them even when not so well thought out. And only experience and open mind will give you the right dosage.

Do one of the basic things for all classes: document them well, learn from the ones they made for you to use and teach others about the ones you created.

  • Thanks for the answer, it would be simpler if I create a utility class for each function, for example: Conversaodatautil, in this class I put only methods that parse the dates received?

  • 2

    To say that utility classes do not cause real problems is an anti-information. Java has had and has many problems because of Apis that ignored principles of OOP that it proposes to support (read the article indicated by rray). For example, in Java we need external libraries to do things that are already available in Java itself because they are poorly available (log and date are classic examples). The file API was also a shame and had to be revolutionized in the latest versions.

  • 2

    @Techies It is not a matter of getting simpler, it is a matter of getting more organized. No doubt you should not create utility classes that do much. So a class like this that handles coais beyond the date is almost certain to do a lot of things. It may be that even this class does too many things. But in general this does not happen. Here it goes from experience. As I said, if you are in doubt in a specific case ask a specific and detailed question.

  • 1

    @Caffé that article was discussed and rejected in several places. What is there is grounded? It is. But there is an exaggeration in the consequences. You just said that the problem is that it was poorly done. This is another problem. It’s not because you used utility class that it’s a shame.

8

What is a utilitarian class

It would be nice if the question offered a definition of "utility class" to ensure that we’re talking about the same thing.

I will assume that utility class is one that publishes generic resources used everywhere in the application.

For example, it returns the current user, the host name, system metadata, has business information formatting functions, eventually connecting data to the database...

Why shouldn’t you use utility classes

Utility classes are not cohesive.

It is called "utilitarian" precisely so that your goal does not need to be well defined, so that you can put anything in there. " This will be used in various places and I don’t know where to post" - play in utility class.

If you’re talking about class, you must be talking about object orientation. If you are interested in object orientation, there is no space for utility classes.

Hurting well-established principles of a paradigm is not simply lack of etiquette - the principle exists to solve a problem and when you break the principle you open the doors to the problem it aims to solve.

In OOP, each object must have a single responsibility. The utility class is named after "useful" just so you can have infinite responsibilities.

Stopping to think, we can raise the question: if this is the useful class, the other classes of the system are what? Useless?

You end up with your entire system coupled with a gigantic class, often costly to create when it publishes the state of many things, so you end up using singletons as well, including accidental complexity in the system.

Since a lot depends on the class, it is difficult to assess the impact of a change in it, so you avoid changing it and, instead, "just for safety", write new methods doing almost the same thing as other existing methods, leading to code duplication instead of avoiding it.

If "utility class" is what I described at the beginning, there are N problems using it (I can list other problems if it’s of interest) and no real benefit.

Would have some way (convention) to use these classes correctly?

The right thing is not to use them but to elaborate a little better the design, finding the right place to publish each resource. There will always be the right name and the right place for a feature, and if you’re hard to find it is because the design can be improved.

Now, in the field of opinion:

In another answer is written "the test is secondary". Please take this as an expression of opinion, and it is an idea already quite outdated including.

My portion of opinion in this answer is, if it’s not tested, it’s broken.

In case of opportunity in the project, no code should be discovered from automated tests.

Automated testing on modern platforms does not require a specific design to allow testing, it requires only good design, and good design is always desirable even if you didn’t want to automate testing.

  • 2

    Some of these utility classes are function statements. The problem of utils just change the name of the package/namespace to Commons, what is outside it is specialized :P hehe. Already looked that

  • 1

    Yes, it is my opinion and that of many people. It is not the opinion of many others. The test is secondary does not mean that it should not exist but rather that one should not complicate the application just to facilitate the test. The design correct is always critical and if this is done, the test will not be complicated. But if I have to choose between complicating the application or what is required to do the test, I prefer to complicate the second. That doesn’t mean the verification itself is complicated. I agree that if the person does wrong, ends up creating a situation that makes it very difficult and there is really wrong.

  • @rray I did not know the article and I found it very cool, including my answer and the article are completely in agreement. I think it would be relevant if you suggested the article in the other answer, which advocates the use of utility classes. bigown, I just complicated the application to ensure the test when I knew even less than I know today. Nowadays it’s the other way around: the tests help me to uncomplicate the application.

  • 1

    I was just reading your answer, and I saw that the two answers are excellent and very enlightening, in my view one complements what is missing in the other. Thank you for the reply.

  • 3

    To say that the "right is not to use" I think is kind of complicated. It would fit better if you passed to the field of "opinion" of yours, just below, because for who knows what you are doing, is a hand on the wheel, and no problem. As personal opinion may even be. As absolute truth, I understand as a missing point in the answer.

  • @Bacchus I explained in the first part of the answer, based on widely accepted principles of object orientation and describing real problems, why it is right not to use. And I also described what kind of utility class I’m talking about. That is, I delimited a context and presented evidence. The conclusion that it is right not to use, therefore, is not merely opinionated. And of course it is not an absolute truth (is there such a thing?). Nothing I write is to be read as an attempt to present an absolute truth.

  • @Caffé I understand your point of view, but without reading your comment, the impression you give is to be an absolute statement, so I commented.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.