Monday, February 2, 2026

Keep Code Clean 3

Take a look at this snippet of the code

void func(num)
{
    if num = 'do1' then
        doSomethingA;
        doSomethingElse1;
        doSomethingElse2;
        doSomethingElse3;
        ...
        ...
        doSomethingElse100;

    if num = 'do2' then
        doSomethingB;
        doSomethingElse1;
        doSomethingElse2;
        doSomethingElse3;
        ...
        ...
        doSomethingElse100;
}

so when you call the functions, you will normally call this way

func('do1');
func('do2');

Another way to improve and more flexible ways and cleaner code without much repetitive in codes.

void func(num)
{
    switch(num)
    {
        case 'do1':
            doSomethingA;
            break;
        case 'do2'
            doSomethingB;
            break;
        case 'doAll'
            func(do1);
            func(do2);
            return;
    }

    doSomethingElse1;
    doSomethingElse2;
    doSomethingElse3;
    ...
    ...
    doSomethingElse100;
}

You may notice at first the codes are not easily read to understand but if further notice that there is no repetitive in the code. 

You can call it 2 ways instead.

func('do1');
func('do2');

func('doAll'); // or you can do this way to call do1 and do2

You just need to call func('doAll') it will also act upon do1 and do2.

This is useful if you need to call custom function if you want to code it to run selective case (eg. funcA to run func1 and func2 then another funcB to run func1 and func3)  so you reduce the number of lines and no repetitions of codes.


No comments: