Session 7

More on Growing Programs


CS 2530
Intermediate Computing


Opening Exercise: Find a Home

Suppose I have a class of ordered integers. It contains an array and a count:

    public class OrderedIntegers
    {
      private int[] value;
      private int   count;
      ...
    }

In this object, the integers are stored in the value array in ascending order, for example [1 2 6 8 9].

Write a method called int slotFor( int newValue ) that returns the position in the array where newValue would go. In our example, slotFor(7) would be 3.

That's not so bad. We just need a quick loop:

    private int slotFor( int newValue )
    {
      int i;
      for (i=0; i < count; i++)
        if ( value[i] >= newValue )
          break;
      return i;
    }

Why did I declare i outside the loop?
Why did I have the loop break on >=?



Factoring Common Behavior in the ArrayMemoDatabase

Last time, we build a solution to Homework 1 from the ground up. We created a class that satisfies all of the project requirements.

But we could do better. [There is a common loop in several methods]. Repeated code is a sign of a repeated idea. What is the repeated idea? Finding the slot for a key.

The script walks through the process of factoring this commonality out of those methods into a helper. My final version of the class uses a new helper method, int slotFor(String), to implement the behavior of the class's four public methods. These four methods are all a bit simpler now, and each makes explicit the act of finding the slot for the key to be inserted, found, removed, or verified.

Code that says what it means and does is good code.



Exercise Interlude: Make Room

Back in our world of ordered integers, suppose I'd like to put a new integer into the value array. Our slotFor() method can tell us where we want to put it.

Write a method void makeRoomAt( int slotForNewItem ) moves all the remaining items forward one slot.

Draw a picture. Think about steps. Think, think, think.

Another quick loop, trickier but doable after thinking ahead:

    private void makeRoomAt( int slotForNewItem )
    {
      for (int i = count; i > slotForNewItem; i--)
        value[i] = value[i-1];
    }

Notice the shape of the inverted for loop. We start at count rather than count-1. We continue until the position before slotForNewItem. We decrement the counter. You'll see this pattern occasionally when dealing with ordered lists of things.



Java Style

Java programming has a style shared by the community of Java programmers. Some conventions came from the creators of Java, and others came as programmers wrote a lot of Java code and wanted to share ideas and code.

... naming things:

... format and white space (similar to the C world)

... some of the programming style you see is my style.
... some for class and some for me.

Consistency is important. It can make unfamiliar style bearable.



Exercise: Assembly Required

Back to our world of ordered integers one last time. We have written two methods:

    private int  slotFor   ( int newValue )       {...}
    private void makeRoomAt( int slotForNewItem ) {...}

Now we want to make it possible for users of our objects to add items to the collection. Fill in the blank:

    public void insert( int newValue )
    {
      if arrayIsFull() return;

      // THE BLANK
    }

The post-condition for this method is to satisfy the invariant on the class: the array is in ascending order.

I recommend using helper methods.

No problem!

    public void insert( int newValue )
    {
      if arrayIsFull() return;

      int position = slotFor( newValue );
      makeRoomAt( position );
      value[position] = newValue;
      count++;
    }

Code that says what it means and does is good code, at least as a first step.

By breaking the task down into small steps, I get to a working solution quickly. Now that I have a solution, I can look for ways to make it faster or smaller. Can you see a way to fold slotFor and makeRoomAt down into a single loop? If so, you could drop it right into insert. The resulting code might not be as clear, but it would be smaller, and a bit faster.



Making a Faster ArrayMemoDatabase

The extra credit...

The best sort is no sort.

Idea: insert in order!

Our in-class exercise guides the way...

We need some new Java for comparing strings.



A Style of Programming

Last time, I built my solution to Homework 1 in what may seem an unusual way: I took small steps. Lots of them.

This really is how I approach writing code, especially when the problem is new to me. A lot of other programmers do something similar:

  1. Identify the requirements of the task.
  2. Choose one requirement, a small bit of functionality.
  3. Specify how the program will work when meeting this requirement.
  4. Write the simplest code I can to meet it.
  5. Clean up my program.
  6. If more requirements remain to be done, go to Step 2.

The keys to this approach are small steps, simple code, and cleaning up.

[ Write the code. Run the test. It works! Repeat. ]

Notice in this process that we are either writing new code or improving the appearance or design of the code while preserving the current functionality.

... But couldn't we just have planned ahead and done it "right" in the first place? Maybe. But writing code can help us learn what we are doing... How far ahead should we think? Can we plan *too* far ahead? What's the danger in that?



New App: A Simple Calculator

... for Homework 2. Run the calculator app:

... no new Java needed to implement the model.

.. due Friday. Then we can get back on cycle with a Friday → Thursday assignment.



Follow Up on Homework 1

Remember to follow the homework submission requirements!

I have added a link to the coding standards page on the Course Resources page.



Wrap Up



Eugene Wallingford ..... wallingf@cs.uni.edu ..... September 11, 2012