Incremental Development

Table of Contents

incremental development involves taking a problem (such as a lab assignment) and breaking it down into smaller, more manageable pieces, incrementally adding functionality (thus, the name, incremental development).

1. the basic idea

  • you want to find a way to break a problem down into smaller parts.
  • the example I always like to use is a user inventory for a game.
  • trying to tackle it all at once can be overwhelming.
  • instead try to break down a problem by cutting out any additional elements that can cause complications and confusion.
    • for example, lets ignore implementing the graphic user interface (GUI) for now.
      • we want to make sure our implementation works before styling it.
    • in addition, lets ignore how we’re gonna get the inventory to pop up in game.
      • we’ll connect the inventory with other elements of the game later.
  • finally, lets not even focus on the item descriptions and instead just focus on having the item name in inventory.
  • next, lets think about “what is the main function of an inventory?”
    • an inventory is meant to store items that the user collects.
    • the user should be able to quickly access an item from the inventory at any point in time.
  • lets translate these ideas back to code.
    • a variable stores an object.
      • perhaps we can have different variables that each store an object.
      • however, it would be impractical to make a ton of variables to perform this task.
  • what can we use instead?
    • we wanted to store multiple variables that each have an object.
    • what if we use a list instead? this would be more practical for a few reasons:
      • we can use one variable instead of multiple variables to hold all objects in inventory.
      • we can easily access items as needed via index or value.
      • if we need the inventory to have rows and columns, we can use a nested (two-dimensional) list to easily achieve this.
  • now that we know we can use a list, we can implement it.
  • as we’re implementing it, we might think of ways to extend our simple inventory.
    • for example, to tie descriptions to an item name, we can use a dictionary, where the key is the item name and the value is the item’s description.
      • we might also choose to create an Item namedtuple instead, where we can not only have the item name and description, but we can specify any statistics (stats) boosts or any special abilities gained from using the item.
  • at the end, we can link our inventory to the player and the rest of our game before developing the GUI.
  • this sort of thought process is applicable for any programming problem you come across, so it’s important to get used to it now.
  • let’s do another example using code.
  • let’s say that we want to create a program that matches the logic of a vending machine.
  • let’s cut out some elements for now:
    • no GUI implementation.
    • assume that there’s only one item in the vending machine.
    • assume that the vending machine only needs to take two coins for the user to get the item.
  • if you’ve taken ics 6b or eecs 31, you’ve probably heard of finite state machines (FSM) before.
    • an FSM is a model with a finite number of states that changes from one state to another based on specific inputs.
  • using this logic, we can think of a vending machine as having 3 states:
    • no coins have been inserted.
    • one coin has been inserted.
    • two coins have been inserted.
  • I want to create a function that moves to the next state given the current state.
    • lets create a next_state function that takes in the current state as a parameter.
# the function header will look something like this:
def next_state(current):
    pass

  • since the states always move in a sequential order, lets create a list that holds all the states in order.
    • it makes sense to use a list since they’re ordered and we can easily access elements via index.
    • however, other data structures can be used to achieve a similar result.
states = ["0 coins", "1 coin", "2 coins"]

# now, lets implement next_state():
def next_state(current):
    if current == state[0]:
        current = states[1]
    elif current == states[1]:
        current = states[2]
    else:
        current = states[0]
    return current

  • we should also have some way to store the current state so we can pass it in as a parameter.
    • lets create a variable called current_state that does just that.
current_state = states[0] # starts at 0 coins

  • now lets test our function out with what we have so far:
states = ["0 coins", "1 coin", "2 coins"]

def next_state(current):
    if current == states[0]:
        current = states[1]
    elif current == states[1]:
        current = states[2]
    else:
        current = states[0]
    return current

if __name__ == "__main__":
    current_state = states[0]
    for i in range(3):
        current_state = next_state(current_state)
        print(current_state)

1 coin
2 coins
0 coins
  • it looks like our function works as intended.
  • lets change our states list so that our states are a little more user-friendly and descriptive.
states = ["insert 2 coins", "insert 1 coin", "have a snack"]

def next_state(current):
    if current == states[0]:
        current = states[1]
    elif current == states[1]:
        current = states[2]
    else:
        current = states[0]
    return current

# lets test our function again.
if __name__ == "__main__":
    current_state = states[0]
    for i in range(3):
        current_state = next_state(current_state)
        print(current_state)

insert 1 coin
have a snack
insert 2 coins
  • it’s kind of annoying to set current_state equal to the next state every single time, so lets find a way to automatically change currentstate to the next state without reassignment.
  • we can use a mutable object, such as a list, so that when current_state is passed into next_state, the list will be passed by reference rather than passed by assignment.
states = ["insert 2 coins", "insert 1 coin", "have a snack"]

current_state = ["0 coins"]

# changing current_state to a list requires us to modify next_state as well:
def next_state(current):
    if current[0] == states[0]:
        current[0] = states[1]
    elif current[0] == states[1]:
        current[0] = states[2]
    else:
        current[0] = states[0]
    return current[0]

# lets test our function again.
if __name__ == "__main__":
    for i in range(3):
        next_state(current_state)
        print(current_state)

['insert 2 coins']
['insert 1 coin']
['have a snack']
  • if we want to print out the current state without the square brackets, we can do something like this:
states = ["insert 2 coins", "insert 1 coin", "have a snack"]

current_state = ["0 coins"]

def next_state(current):
    if current[0] == states[0]:
        current[0] = states[1]
    elif current[0] == states[1]:
        current[0] = states[2]
    else:
        current[0] = states[0]
    return current[0]

if __name__ == "__main__":
    for i in range(3):
        # print the return value of next state, which is current[0] instead of current
        print(next_state(current_state))

insert 2 coins
insert 1 coin
have a snack
  • alternatively, we can also index into current_state.
states = ["insert 2 coins", "insert 1 coin", "have a snack"]

current_state = ["0 coins"]

def next_state(current):
    if current[0] == states[0]:
        current[0] = states[1]
    elif current[0] == states[1]:
        current[0] = states[2]
    else:
        current[0] = states[0]
    return current[0]

# testing our function again.
if __name__ == "__main__":
    for i in range(3):
        next_state(current_state)
        print(current_state[0])

insert 2 coins
insert 1 coin
have a snack
  • although we could continue making changes to our code, any significant advancements to our code would not longer be in the scope of this class, so I’ll stop here for now.
  • once we have the basic logic down, we can extend our code further.
    • for example, I could ask the user for the item number that corresponds to the item they want and print it out.
    • I can have these items stored in a list of namedtuples with their item name, number, and price.
  • so before you try to solve a problem all at once, consider breaking it into smaller parts and solving one thing at a time.

2. understand the problem you’re trying to solve

  • one important reason to start labs early is because it takes some time to even just wrap your head around a problem.
  • you’ll want to read the requirements for a program a few times.
    • as you’re reading, think about how you’d go about implementing parts of it.
      • personally, I like to write my ideas down on paper.
        • writing things down on paper allows you to easily visualize your thoughts using maps, graphs, etc.
      • maybe there’s a noun in the instructions that should have fields associated with it, so you might wanna use a namedtuple.
      • maybe there’s some collection of related items involved, so you might want to store them in some sort of data structure.
      • maybe you want to continue processing information until the user tells you otherwise, so you might wanna use a while loop with a sentinel value.
      • maybe there’s a common task that’s performed in multiple parts of your code, so you might wanna use a function.
      • maybe certain tasks are only executed under specific constraints, so you might wanna use branching.
    • use pseudocode, data structure visualization, and control flow graphs to map out your program.
      • pseudocode outline’s a program’s algorithm in a high-level, readable format.
        • don’t have to worry about syntax.
      • data structure visualization is useful when your program needs to access and modify a nested data structure.
      • control flow graphs illustrate all possible execution paths in a program.
        • useful if your program requires a lot of branches and loops with break and continue.
  • many programs involve 3 main components: input, manipulation, and output.
    • they’re all pretty self-explanatory.
    • similar to a function.
      • inputs are its parameters.
      • function body processes information.
      • output(s) is its return statement.
    • there’s this idea in programming called black box testing.
      • from the user’s perspective, they don’t know how a program works.
      • however, they do know that they expect a specific output to be produced based on what they input.
      • this can be applied when you’re programming:
        • think about different inputs and their corresponding outputs that a user might test for a program/function you’re creating.
        • think about similar patterns that occur with the input/output relationships.
        • once you think you’ve figured it out, implement it and test it with the inputs and outputs you came up with.
        • if you find that your code’s not working as expected, debug your code until it does.
    • good practice is to assert constraints on the user’s input and output.
      • for example, this can be achieved through precondition and postcondition asserts.
        • add descriptive messages to each assert so it’s easier to debug and more user-friendly.
      • this allows you to check data types and other conditions before information is processed and before the output is shown to the user.

3. program implementation

  • once you’ve familiarized yourself with the task at hand, start programming.
    • implement solutions to parts of the problem that you’ve already wrapped your head around.
    • you might find that as you’re writing code, you’re able to come up with solutions that match other requirements.
      • write/type out these solutions while you still remember them. (ex: creating TODO comments in your code)
    • if you find yourself stuck on a code block’s implementation, create FIXME comments in your code or take a break before coming back to them.

4. incremental testing

  • as you’re implementing different functions, you’ll want to test them one at a time before moving on to the next step.
    • for now, you can test them by passing in different inputs (arguments) and seeing if the corresponding output is returned.
    • think about edge cases that might break your code and test them out.
      • continue debugging your code until it works as intended.
    • in later classes, you’ll use unit testing to develop test cases that can easily be rerun over and over again.
      • these unit tests are often placed in a separate test file/folder.
  • good practice is to use git for version control, committing after you’ve successfully implemented a new function/method and writing a brief but descriptive comment to go along with it.
    • you’ll use git more often in future classes.

5. debugging

  • if your code is producing an error, read the error message.
    • the console will tell you what type of error is occurring and roughly around what line(s) caused the error.
    • figure out whether one or multiple test cases are causing this error.
      • usually, if it’s just one, it may indicate that some additional constraint needs to be added for the test case to pass (ex: dividing by 0)
      • if it’s multiple, there’s likely some sort of common attribute that your test inputs have that hasn’t been accounted for.
      • if it’s all, there’s likely something wrong with your code syntactically.
  • print statements are your best friend when debugging code. (primarily for logical errors)
    • use them to make sure variables and functions (including helper functions) have correct expected values.
    • continue testing with different inputs to figure out where/when the pattern’s amiss.
  • ask others for help.
    • there’s a reason lab assignments are meant to be completed in pairs rather than individually.
    • many programs in this world were developed in large groups/teams rather than alone.
    • feel free to ask your peers or mentors around you if you need any assistance.
      • that’s what they’re here for.
  • as you’re debugging, you might find that you need to make more significant changes to your original model/implementation.
    • feel free to make as many changes as you need.
    • as tedious as it sounds to restructure your code, doing this might make your code more robust, making it less prone to errors and improving long-term performance.
    • the process of programming oftentimes goes through many iterations before reaching a “finalized” product (even then, it still needs to be consistently maintained and updated).
      • therefore, you should allow your code to be open/flexible to change.
      • making significant improvements for better readability, clarity, and structure will assist others (and yourself) who look at your code many years later.

6. the S in SOLID principles

  • SOLID principles are primarily used in object-oriented programming, but these principles are applicable almost anywhere.
  • most of these principles apply to classes, which you guys will learn in later courses, so for now, I’ll just describe S:
  • S = Single Responsibility Principle
    • think about a grocery list. what sort of ways would you want to manipulate it?
    • you may want to add, remove, and reorder items.
    • you could create one function based on the user’s input that supports adding, removing, and reordering items.
      • however, programming this may make your code harder to read since you generally don’t want your functions/methods to be too long.
      • in addition, you may have a (somewhat) harder time debugging your code since it’s more difficult to identify/trace where errors occurred.
      • doesn’t allow for proper modularity and organization.
  • grocery list example (everything in one function):
def main():
    grocery_list = []
    option_dict = {"a": "add item", "r": "remove item", "o": "reorder items",
                   "p": "print grocery list", "q": "quit"}
    print("MENU")
    for letter, option in option_dict.items():
        print(f"{letter} - {option}")
    print()
    choice = input("Choose an option:\n")
    while True:
        if choice == "q":
            break
        elif choice == "a":
            new_item = input("Enter the name of the item you'd like to add:\n")
            grocery_list.append(new_item)
        elif choice == "r":
            item_to_remove = input("Enter the name of the item you'd like to remove:\n")
            grocery_list.remove(item_to_remove)
        elif choice == "o":
            index1 = int(input("Enter the index of the first element that
            you'd like to swap with the second:\n"))
            index2 = int(input("Enter the index of the second element that
            you'd like to swap with the first:\n"))
            grocery_list[index1], grocery_list[index2] =
            grocery_list[index2], grocery_list[index1]
        elif choice == "p":
            print("GROCERY LIST")
            if len(grocery_list) == 0:
                print("nothing in grocery list right now.")
            else:
                for item in grocery_list:
                    print(item)
            print()

        print("MENU")
        for letter, option in option_dict.items():
            print(f"{letter} - {option}")
        print()
        choice = input("Choose an option:\n")

  • instead, you could create three separate functions that deal with adding, removing, and reordering items with a fourth function that processes the user’s input and executes the correct function.
    • easier to read and will likely have more descriptive function names.
    • can reuse these functions in multiple parts of your code (or in other source files).
    • if something goes wrong in your processing function, it’s easier to pinpoint the source of your problem.
  • grocery list example (multiple functions):
def add_item(a_grocery_list):
    new_item = input("Enter the name ofo the item you'd like to add:\n")
    a_grocery_list.append(new_item)

def remove_item(a_grocery_list):
    item_to_remove = input("Enter the name of the item you'd like to remove:\n")
    a_grocery_list.remove(item_to_remove)

def swap_items(a_grocery_list):
    index1 = int(input("Enter the index of the first element that
    you'd like to swap with the second:\n"))
    index2 = int(input("Enter the index of the second element that
    you'd like to swap with the first:\n"))
    a_grocery_list[index1], a_grocery_list[index2] =
    a_grocery_list[index2], a_grocery_list[index1]

def print_items(a_grocery_list):
    print("GROCERY LIST")
    if len(a_grocery_list) == 0:
        print("nothing in grocery list right now.")
    else:
        for item in a_grocery_list:
            print(item)
    print()

def print_menu():
    option_dict = {"a", "add item", "r": "remove item", "o": "reorder items",
                   "p": "print grocery list", "q": "quit"}
    print("MENU")
    for letter, option in option_dict.items():
        print(f"{letter} - {option}")
    print()

def main():
    grocery_list = []
    print_menu()
    choice = input("Choose an option:\n")
    while True:
        if choice == "q":
            break
        elif choice == "a":
            add_item(grocery_list)
        elif choice == "r":
            remove_item(grocery_list)
        elif choice == "o":
            swap_items(grocery_list)
        elif choice == "p":
            print_items(grocery_list)

    print_menu()
    choice = input("Choose an option:\n")

  • the Single Responsibility Principle states that a function (or a class) should only have one responsibility.
    • closely aligns with separation of concerns, which states that you should split your program into multiple sections that each address a different concern.

7. other good practices

  • write brief but descriptive comments for your code.
    • useful when you or someone else has to look at your code again.
  • create meaningful variable and function names.
    • helps with readability and contextualization.
  • write out type annotations for your functions.
    • this includes types for your parameters and return values.
    • you’ll learn more about this in future classes.
  • don’t write out long functions.
    • as mentioned earlier, it makes it harder to debug your code and is less modular.
    • instead, find ways to refactor your code into multiple, small functions.
  • statements should not be too long.
    • generally no more than 80 characters per line.
    • long statements can be harder to read (and requires you to scroll back and forth).
    • instead, find ways to truncate the line and specify where line breaks occur.

Author: Ashley Pock

Created: 11/17/2025 Mon