You can introduce the idea of best practices. Show them examples of right vs wrong for each of the practices you want to teach them:
public void method(){
System.out.println("this is incorrect indentation");
String example="It makes the code difficult to read.\n";
example+="If you can't read the code, you'll see how difficult it is to work on it";
int x=5;
if("this is completely bad: 5".contains((""+x)))
System.out.println("because there's no indentation.");
}
and then show the best practice code:
public void betterMethod(){
System.out.println("this is the correct way to do indentation");
String example="It makes the code very easy to read.\n";
example+="If you can read the code, you'll see how easy it is to work on it";
int x=5;
if("this is the best practice: 5".contains((": "+x)))
System.out.println("because the indentation is good");
}
And this idea works for other best practices: show the bad and emphasize just how bad it is (you might want to exaggerate the "badness" of the worst-practice code).
Then, show them the correct way to do it. It's better if both examples give the same output. that way students see how much easier it becomes when applying best practices:
An example for comments and meaningful naming:
the bad example:
int[] b = {1,3,4,6,7,9,11,2,5,8};
int a = 0;
Arrays.sort(b);
double s=0;
for(int i=0;i<b.length;i++) {
System.out.print(b[i]+",");
s+=b[i];
if(a<b[i] && i<=b.length/2) {
a=b[i];
}
}
System.out.println();
System.out.println(a);
System.out.println(s/b.length);
the better way:
//create array of numbers
int[] numberArray = {1,3,4,6,7,9,11,2,5,8};
//create variable for median
int median = 0;
//sort array
Arrays.sort(numberArray);
//create variable for average
double average=0;
//iterate over array
for(int i=0;i<numberArray.length;i++) {
//print sorted array, each number in a different iteration of the loop.
System.out.print(numberArray[i]+",");
//sum numbers in array, one by one.
average+=numberArray[i];
//if the current value of the median variable is smaller than the current
//value in the array, and the loop hasn't passed the middle yet, set the median variable
//to be the current value in the array
if(median<numberArray[i] && i<=numberArray.length/2) {
median=numberArray[i];
}
}
System.out.println();
//print results
System.out.println(median);
//calculate and print calculation
System.out.println(average/numberArray.length);
Before showing the correct way, ask if anyone can see what this program does. It would be difficult for most. Then show the best-practice version, and they'll see just how better it is.