开发者

Best Utility Class Implementation [closed]

开发者 https://www.devze.com 2023-04-09 05:55 出处:网络
Closed. This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing th
Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 8 years ago.

Improve this question

I have read several questions regarding when to use a utility class or any class that doesn't have a state associated with it.

My question is what is the best implementation once you have decided to use a utility class? A static class, a normal class with private constructor and only static methods (similar to java's math class), or an alternative?

I understand that this will probably depend on my specific si开发者_开发知识库tuation but I do not have one and was looking for more general guidelines or advantages and disadvantages to each implementation method.


What is the best implementation once you have decided to use a utility class?

Exactly what you proposed. Create a private constructor, make the class final and implement static utility methods. In such cases, there's no need to make things more complex.

Of course, you must be careful to not falling back into imperative/procedural programming style... just one opinion.


IMHO:

For Utilty Classes for little everyday Problems like Converting Stuff etc is a static class with no constructor the best implementation. Very Handy to access:

Utils.ConvertDateToCake();

My Utility Classes which need an Constructor are implemented as Singletons. So you can access them like this:

DatabaseUtils.getInstance().DoSomething();


Utility classes are pure evil in OOP. Check this blog post for better explanation: http://www.yegor256.com/2014/05/05/oop-alternative-to-utility-classes.html

In a nutshell, utility classes bring procedural programming into OOP, making your code less testable, less maintainable/readable, and slower (!).

0

精彩评论

暂无评论...
验证码 换一张
取 消