设为首页 加入收藏

TOP

Utility Classes Are Evil(三)
2015-07-20 17:39:33 来源: 作者: 【 】 浏览:11
Tags:Utility Classes Are Evil
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/

?

?

?

?

?

首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇codeforces #185 A Plant(矩阵快.. 下一篇hdu 5017 Ellipsoid(西安网络赛 ..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·「链表」是一种怎样 (2025-12-25 19:20:51)
·C 语言中的链表有哪 (2025-12-25 19:20:48)
·c语言中的链表怎么学 (2025-12-25 19:20:45)
·Redis 分布式锁全解 (2025-12-25 17:19:51)
·SpringBoot 整合 Red (2025-12-25 17:19:48)