1 2 3 4 5 6 7 8 9 10 11 12 13 14
This is a wholly readable bit of code – there’s almost no question what’s going on here. On the other hand, it’s pretty easy to see the rampant repetition; this code isn’t interested in “don’t repeat yourself” (DRY). We’re calling the same method on every selection we make, and our selections are repeated in both the if and else block. When I saw this code, I had an immediate inclination to rewrite it. Here’s what I came up with first:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
1 2 3 4 5 6 7 8 9
This felt repetitive when I first wrote it, but I couldn’t quickly come up with a single function that would work. A little thinking about it, though, led me to this single function which gets a second argument: direction. That argument is used to decide whether to run the item’s next or previous method, and then whether to run the item’s first or last method. Besides combining two functions into one, it also eliminates calling next or prev twice inside each function.
1 2 3 4 5 6
Learning about patterns and then discovering opportunities to use them is one of the more pleasing parts of my job. I hope this helps you identify some of those opportunities for yourself :)