Show students what code looks like with and without methods to motivate the reasons for using them.

  • Comparing code, like the examples listed below, can help:

    • students understand methods by mapping the code back to code without them.

    • motivate methods by helping students see how it makes the code easier to understand.

  • Code Comparison Examples:

    • Example code with methods:


public class ExampleCode {     public static int sumOfSquares(int val1, int val2){         return square(val1) + square(val2);     }     public static int square(int z){         return z * z;     }     public static void main(String[] args){         // calculate the sum of the squares         int x = 10;         int y = 8;         int answer1 = sumOfSquares(x, y);         System.out.println(answer1);         int a = 10;         int b = 8;         int answer2 = sumOfSquares(a, b);         System.out.println(answer2);         int f = 10;         int g = 8;         int answer3 = sumOfSquares(f, g);         System.out.println(answer3);     } }


  • Example code without methods:



public class ExampleCode {     public static void main(String[] args){         // calculate the sum of the squares         int x = 10;         int y = 8;         int answer1 = ((x * x) + (y * y));         System.out.println(answer1);         int a = 11;         int b = 7;         int answer2 = ((a * a) + (b * b));         System.out.println(answer2);         int f = 12;         int g = 6;         int answer3 = ((f * f) + (g * g));         System.out.println(answer3);     } }

More about this tip

External Source

Interview with Samar Swaid.