Tuesday, May 8, 2012

Why stateless utility class with static methods is bad?

- Violation of the OO design principle:
---- Theoretically, if such a static method takes in arg1, arg2, ... and change their 'state', then either:
--------1. arg1, arg2, should be members of a separate class Class1 and assigned through constructor 
--------2. the operation carried out by this static method should be part of classes of arg1, arg2 ....

- Hard to mock and Unit Test

Practically, however, most people don't ban it in entirety.

+ Could potentially save memory in multithread operation (the Utility object itself is read-only by the thread as it contains no state, hence no race or deadlock) - e.g. Stateless session bean pool in J2EE?

+ Examples of existing implementation:
JAVA 
java.lang.Math
java.util.Collection

C#
System.Collections.Specialized.CollectionsUtil 
System.Net.WebUtility
 
 
http://stackoverflow.com/questions/3339929/if-a-utilities-class-is-evil-where-do-i-put-my-generic-code
http://stackoverflow.com/questions/3340032/utility-classes-are-evil
http://stackoverflow.com/questions/1942903/java-class-with-only-static-fields-and-methods-bad-or-good-practice 
 

How To Design A Good API and Why it Matters

http://www.youtube.com/watch?v=aAb7hSCtvGw 
 

No comments:

Post a Comment