Traditionally, we use loops to iterate collections:
Loops Iterating ListTo 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 LoopIn 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 v1class 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 v2Here 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.
网友评论