(Coursenotes for CSC 305 Individual Software Design and Development)

Introduction + Clean code

Course overview

What’s this course about?

“Production-quality” means that, in addition to functional correctness (your program does what we expect it to do), you will be expected to attend to the following aspects:

Syllabus overview

Grading and assessments

Notes about all programming assignments

Academic honesty

Code style, programming practices

Effective Java, Sonarlint

Code critique

public static String delimit(String delimiter, String[] str) {
    String result = "";
    int i;
    for (i = 0; i < str.length; i++) {
        if (i != 0) {
            result += delimiter;
        }

        result += str[i];
    }

    return result;
}

What do you think of this code? Is its purpose clear? Is the function maintainable?

EJ57: Minimise the scope of local variables.

The variable i is now only available inside the for loop.

public static String delimit(String delimiter, String[] str) {
    String result = "";
    if (str.length > 0) {
        result += str[0];
    }
    
    for (int i = 1; i < str.length; i++) {
        result += delimiter;
        result += str[i];
    }

    return result;
}

In the example below, the iterator i is not needed after the first while loop. But its scope is not limited to that area. This can subtle mistakes like the one below. Can you spot it?

public static void example(List<Object> c, List<Object> c2) {
    Iterator<Object> i = c.iterator();
    while (i.hasNext()) {
        System.out.println(i.next());
    }

    // ... Some other code.
    Iterator<Object> i2 = c2.iterator();
    while (i.hasNext()) {
        System.out.println(i2.next());
    }
}

EJ63: Beware performance of String concatenation

public static String delimit(String delimiter, String[] str) {
    StringBuilder result = new StringBuilder();
    if (str.length > 0) {
        result.append(str[0]);
    }
    
    for (int i = 1; i < str.length; i++) {
        result.append(delimiter);
        result.append(str[i]);
    }

    return result.toString();
}

EJ58: Prefer for-each loops to traditional for loops where possible.

EJ59 Know and use the standard libraries.

public static String delimit(String delimiter, List<String> str) {
    return String.join(delimiter, str);
}

public static String delimit(String delimiter, String[] str) {
    return String.join(delimiter, str);
}