THINK FIRST·CODE LATER

← All labs

Code-smell detector

Problem

Write a small smell detector for Java source code.

Input: Java source code until the end of input. A method header is a line that (after trimming) starts with public , private , protected or static , contains (, ends with {, and does not contain class or =. The method body ends at the matching } (count { and } characters line by line, starting from the header line).

For each method, in order, report:

  • LONG_METHOD (N lines) if the method has more than 15 lines (header and closing line included);
  • LONG_PARAMETER_LIST (N params) if it has more than 4 parameters (count commas between the parentheses of the header + 1; 0 if the parentheses are empty);
  • DEEP_NESTING (depth D) if the maximum brace depth inside the method is more than 3 (the method's own { is depth 1);
  • MAGIC_NUMBER x for each integer literal (a whole-word number) other than 0, 1 or 2 inside the method body, in order of appearance, without repeats.

Method name = the word just before ( in the header. Print name: OK or name: followed by the smells separated by ; . Finally print Methods: n, with smells: k.

Input:

public class Demo {
    public static int score(int a, int b) {
        if (a > 100) {
            return 100;
        }
        return a + b;
    }

    private void many(int a, int b, int c, int d, int e) {
        for (int i = 0; i < a; i++) {
            if (b > 0) {
                while (c > 0) {
                    c--;
                }
            }
        }
    }
}

Output:

score: MAGIC_NUMBER 100
many: LONG_PARAMETER_LIST (5 params); DEEP_NESTING (depth 4)
Methods: 2, with smells: 2

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.