From the course: Programming Foundations: Design Patterns

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Encapsulating iteration

Encapsulating iteration

From the course: Programming Foundations: Design Patterns

Start my 1-month free trial

Encapsulating iteration

- We have many ways to store collections of objects in data structures. For example, most modern programming languages provide arrays. If you're using Java, you could store menu items for a menu in an array like this. Most languages provide additional structures for storing collections of objects like lists, dictionaries and sets. For example, Java provides an ArrayList, which is a lot like an array, but has some list like capabilities too. Here we're storing our menu items in an ArrayList. Simple enough, but what if we need to write code that operates over several of these collection types? Let's say you want to write a print method to print any menu. To print a menu, we need to iterate over the collection that's storing the menu items. If you're using an array to store your menu items, you'll write code like this. Now if you decide to change the representation of menus from an array to an ArrayList, you end up rewriting all that code to print the menus because the code depends on…

Contents