Main Content

Splitting out code into name blocks for clarity and reusability

Archive - Originally posted on "The Horse's Mouth" - 2014-11-30 16:12:47 - Graham Ellis

When you first write code - "a program" - there's a big temptation to start at the top and write on down to the bottom, putting all the code more or less sequentially in your program's source file. In the case of Java, which I was teaching last week, that would have meant within the main method (we use the name "method" for a named block of code in Java).

It's all right to start off by following that temptation to some extend, but the code soon gets long and hard to follow, and design patterns / algorithms which you employ / implement aren't easily re-used as you ed up buiding something in which all the parts run into each other, rather than comprisng a series of individual parts each of which plugs nicely into those around it through an undertandable, defined, easy to test API (Application Programmer Interface) ... which also has the bonus that it can be reused gain later on without duplicating code.

Let me show you what I mean. Here's a piece of code as I'm recommending you write it:

  public static void main(String[] args) {
    BufferedReader standard = openKeyboard();
    float first = askAndGet(standard,"Please give me first number");
    float second = askAndGet(standard,"Please give me second number");
    float total = first + second;
    System.out.println("Adding up, I got " + total);
  }


Even if you're an experienced Java programmer, you won't recognise functions such as openKeyboard and askAndGet - they're not standard Java functions. You will, however, recognise the Java syntax and you'll be able to take a pretty good guess at what those two missing methods do.

And you'll find those methods later in the code ...

• Originally, the methods were written as a part of the main method but as the separation of functionalliy became clear during development, I separated them out

• By having a separate main and helper methods, I can run the whole class as a standalone program,and without any alteration at all I can also use the functionallity of opening the keyboard connection, and of prompting and reading a floating number, from within other programs.

Source code of complete examples - [here]