Daily Archives: December 12, 2013

Good Practice (Part 1)

Today I am only posting a quick note. Many beginners do not think in opposite conditions and get lost in nested code. Let’s list some short examples to make code more legible. There is definitely an advantage of avoiding curly brackets the longer your code gets.

static void BadPractice1() {
    bool a = true;
    bool b = true;
    bool c = true;

    if (a) {
        // some code here
        if (b) {
            // some code here
            if (c) {
                // some code here
                Console.WriteLine("hello");
            } 
        }
    }
} //

static void GoodPractice1() {
    bool a = true;
    bool b = true;
    bool c = true;

    if (!a) return;
    // some code here
    if (!b) return;
    // some code here
    if (!c) return;
    // some code here
    Console.WriteLine("hello");
} //
static void BadPractice2() {
    int i = 5;

    if (i <= 4) {
        Console.WriteLine("hello");
        Console.WriteLine("hello");
        Console.WriteLine("hello");
        // some code here
    }
    else {
        Console.WriteLine("omg");
    }
} //

static void GoodPractice2() {
    int i = 5;

    if (i > 4) {
        Console.WriteLine("omg");
        return;        
    }

    Console.WriteLine("hello");
    Console.WriteLine("hello");
    Console.WriteLine("hello");
    // some code here
} //
static int BadPractice3() {
    bool b = true;
    int i;

    if (b == true) {
        i = 5;
    }
    else {
        i = 6;
    }
    return i;    
} //

static int GoodPractice3() {
    bool b = true;

    return b ? 5 : 6;    
} //
static void BadPractice4() {
    int i;
    double d;

    i = 3 * 2 + 7;
    if (i == 10) {
        // some code here
        d = 5.0;
    }
    else {
        // some code here
        d = 4.0;
    }

    // do something with d
} //

static double AMethod() {
    int i;

    i = 3 * 2 + 7;
    if (i == 10) {
        // some code here
        return 5.0;
    }
        
    // some code here
    return 4.0;
} //

static void GoodPractice4() {
    double d = AMethod();
            
    // do something with d
} //