lundi 19 septembre 2016

Return statement instead of if statement - bad practice?

My teacher and me had a little argue wether it would be a bad practice to use the return statement to stop execution of a method instead of putting the whole bunch of code into an if statement. For example:

public static void test(String str)
{
    if (str == null) return;

    System.out.println(str);
    System.out.println("length=" + str.length());   
}

But my teacher strongly advised me to do the following because the upper solution would be unconventional:

public static void test(String str)
{
    if (str != null)
    {
        System.out.println(str);
        System.out.println("length=" + str.length());   
    }
}

In my opinion, the return statement keeps the level of indentation low and the code is better readable. What is more conventional? Keep in mind that the method should never do anything if str is null. Otherwise, the second method might be more suitable.

Aucun commentaire:

Enregistrer un commentaire