JAVA: Implementing Collection Enumeration

Traditionally, we use loops to iterate collections:

Loops Iterating List

To traverse a Collection, we need to write some kind of loops: for-each, while-loop, etc. Writing all these loops is easy, but it soon becomes tedious, slowing down our coding process; And being tedious often means being error-prone. We must develop some way to solve the problem.

Looking at these loops closely, we can easily discover that they can be divided into two parts: the code inside the loop and the loop that wraps the code inside it:


The Anatomy of A Loop

In the anatomy above, we can see that:

1) Only the code inside the loop wrapper varies; 

2) The loop, as a wrapper of the code inside it, remains the same, and thus can be factored out.

With all these observations, I employed the so called Strategy Design Pattern and devised the following code:

Enumeration v1

class StopFlag is introduced as a communication mechanism between the enumeration method of interface Enumeration and its caller so the method can tell its caller to stop when appropriate.

Working, but not so elegant, you might think. So did I. So after a second thought, I did some refinement and came up with the following code:

Enumeration v2

Here the revised version eliminates the StopFlag class, saving its job for the return value of the enumeration method.

Future Refactor

With the introduction of lambda, a new feature of JAVA SE 8, this strategy can be taken further to an extreme where the Enumeration interface and its anonymous inner class implementation can be removed. That way, the code can be even more compact.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 千岛湖(新安江水库),位于浙江省杭州市淳安县境内,小部分连接建德县西北。是为建新安江水电站拦蓄新安江下游而成的人工...
    蔚蓝色的天空c阅读 1,703评论 0 0
  • 有每天坚持的事去做 有列表里满满的歌 有永远随身携带的钥匙 没有比这更好的事了 还没有到着急发慌的年龄 还没有为一...
    阿跛阅读 5,601评论 4 29
  • 文/月宝 安妮宝贝写过的一本书叫做《素年锦时》,里面有一篇月棠记,月棠记里的女主人公,就是重光。 重光,...
    Sheryl月公子阅读 2,118评论 1 3