encapsulates all file reading and writing operations. An instance of FileLines behaves exactly as a collection of strings and hides all I/O operations. When we iterate it — a file is being read. When we addAll() to it — a file is being written.
Trimmed also implements Collection
and encapsulates a collection of strings (Decorator pattern). Every time the next line is retrieved, it gets trimmed.
All classes taking participation in the snippet are rather small: Trimmed, FileLines, and UnicodeFile. Each of them is responsible for its own single feature, thus following perfectly the single responsibility principle.
On our side, as users of the library, this may be not so important, but for their developers it is an imperative. It is much easier to develop, maintain and unit-test class FileLines rather than using a readLines() method in a 80+ methods and 3000 lines utility class FileUtils. Seriously, look at its source code.
Lazy Execution
An object-oriented approach enables lazy execution. The in file is not read until its data is required. If we fail to open out due to some I/O error, the first file won’t even be touched. The whole show starts only after we call addAll().
All lines in the second snippet, except the last one, instantiate and compose smaller objects into bigger ones. This object composition is rather cheap for the CPU since it doesn’t cause any data transformations.
Besides that, it is obvious that the second script runs in O(1) space, while the first one executes in O(n). This is the consequence of our procedural approach to data in the first script.
In an object-oriented world, there is no data; there are only objects and their behavior!
Reference
http://www.javacodegeeks.com/2014/09/oop-alternative-to-utility-classes.html
http://blogs.msdn.com/b/nickmalik/archive/2005/09/06/461404.aspx
http://www.marshallward.org/avoiding-utility-classes.html
?
原文地址:http://alphawang.com/blog/2014/09/utility-classes-are-evil/
?
?
?
?
?