Kenan
Assistant Engineer
Assistant Engineer
  • UID621
  • Fans0
  • Follows0
  • Posts55
Reads:832Replies:0

Details in code structure optimization

Created#
More Posted time:Nov 7, 2016 14:27 PM
What would jump to your mind when we speak of program optimization? Generally we may think of
• Execution speed of the program
• Page loading time
• Memory usage
• Network traffic consumption
• Sacrifice space in exchange for improvement in execution speed
• Execute repeated operations in exchange for optimized memory consumption
• and a variety of measures to reduce queries to the database
Today we’ll talk about another kind of optimization - code structure optimization, which is usually more important.
Optimize readability and extendibility
• In an age with sufficient hardware and complicated systems, it is more important to make the code easier to read, debug, maintain and extend. Only in this way can we achieve better team work and adapt ourselves to the changing demands.
• Our code is usually written once, debugged five times, modified 10 times and read 50 times.
• The never-ending changes will undermine the conceptual integrity of the original design, and ultimately causes the software to die.
• By reading code, we are compiling and executing the code with our eyes and in our brains.
• Do not make your code unintelligible to “others”, because you might be one of the “others” after one week.
• Optimization cannot make the best of both worlds. Optimization in performance may increase the memory consumption of the application, while impairing the code readability.
The unity of opposites of optimization
Optimization cannot make the best of both worlds. Optimization in performance may increase the memory consumption of the application, while impairing the code readability.
Code structure optimization cases
One function attends to only one thing
/**
 * One function or one method attends to only one thing
 * The function below serves to send messages, but it also completes query of user telephone numbers.
 * The logic for getting user telephone numbers should be removed
 */
function sendSMS($uid, $msg)
{
    $sql = "select phone from user where uid =".intval($uid);
    $re = M('user')->query($sql);
    $param['OperID'] = 'xxx';
    $param['OperPass'] = 'xxx';
    $param['msg'] = $msg;
    $param['DesMobile'] = $re[0]['phone'];
    $api = 'http://xxxx/QxtSms/QxtFirewall?'.urldecode(http_build_query($param));
    //....Call the interface to send messages
}

//To be improved: do we also often neglect such issues in our work?

function getPhoneByUid($uid)
{
    $sql = "select phone from user where uid =".intval($uid);
    $re = M('user')->query($sql);
    return $re[0]['phone'];
}

function sendSMS($uid, $msg)
{

    $param['OperID'] = 'xxx';
    $param['OperPass'] = 'xxx';
    $param['msg'] = $msg;
    $param['DesMobile'] = getPhoneByUid($uid);
    $api = 'http://xxxx/QxtSms/QxtFirewall?'.urldecode(http_build_query($param));
    //....Call the interface to send messages
}


Delete dead code
//1: Eliminate dead code
function deadcode()
{
    setRunLog();
    ;//We have no idea whether the code below is alive or dead...
}

function setRunLog()
{
    $tree = array_reverse(debug_backtrace());
    $log = '';
    foreach ($tree as $k => $t)
    {
        $log .= $k.": File ".$t['file']."  , function ".$t['function']." , line ".$t['line']."
";
    }
    echo date('Y-m-d H:i:s').':I am running by:  
'.$log;
}


Define a period yourself. If the code is not run all the time, you can delete it (might still be risky).
Do not store two types of data in one variable
function addCart($item_id , $count)  
{  
    if(!is_array($item_id))  
    {  
        $_SESSION['cart']['item_id'] = $count;  
    }  
    else  
    {  
        foreach($item_id as $i_id => $count)  
        {  
            $_SESSION['cart']['i_id'] = $count;  
        }  
    }  
}  
addCart( 'IPHONE3' , 2 );  
addCart( array('IPHONE3' => 2 , 'IPAD' => 5) );

//We recommend you write it like this more
function addCartSingle($item_id , $count)
{

}

function addCartArr($arr )
{

}


Remove repeated code
Such code is frequently seen in projects. Because of the iteration of multiple versions and multiple contributors, repetition is unavoidable. So when you need to modify the business logic, you may find some code was omitted for modification.
//Solve repeated code
function reg_user()
{
    //insert into user...
    ;//Register a user...
}


function user_reg()
{
    //insert into user...
    ;//User registers...
}

//Every modification requires edits in two places, otherwise a bug will occur.
//You cannot delete it rashly because it is called in many places.
//Modify it like this. Although it is not perfect, it is better.

function user_reg()
{
    return reg_user();
}


Do not make code a showpiece of your skills
//Do not write over-masterly code
//The programmer of silly version
function swap1()
{
    $a = 2;
    $b = 8;
    list($a, $b) = array($b, $a);
    echo "$a , $b
";
}
swap1();

//The programmer of normal version
function swap2($a, $b)
{
    list($a, $b) = array($b, $a);
    echo "$a , $b
";
}
swap2(2, 8);

//The programmer of showy version
function swap3($a,$b)
{
    $a=$a^$b;
    $b=$a^$b;
    $a=$a^$b;
    echo "$a , $b
";
}
swap3(2, 8);


Extract the obscure code to be annotated
//Extract the obscure code to be annotated
function loadHostConfig()
{
    //Here we extract the second-level domain of the current URL
    $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
    $arr = explode('.', $host);
    $subdomain = strtolower($arr[0]);

    $client_arr = array(
        'edu' => 5,
    );
    if (isset($client_arr[$subdomain]))
    {
        define('UCAI_CLIENT_ID', $client_arr[$subdomain]);
        include_once SITE_PATH.'/config/'.$subdomain.'.class.php';
    }
    else
    {
        include_once SITE_PATH.'/config/www.class.php';
    }
}

//Extract it directly
//Name the function according to its role: give it a name indicating “what it does”, instead of “how it does it”.
function getSubdomain()
{
    $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
    $arr = explode('.', $host);
    $subdomain = strtolower($arr[0]);
    return $subdomain;
}

function loadHostConfig()
{
    //Here we extract the second-level domain of the current URL

    $subdomain = getSubdomain();

    $client_arr = array(
        'edu' => 5,
    );
    if (isset($client_arr[$subdomain]))
    {
        define('UCAI_CLIENT_ID', $client_arr[$subdomain]);
        include_once SITE_PATH.'/config/'.$subdomain.'.class.php';
    }
    else
    {
        include_once SITE_PATH.'/config/www.class.php';
    }
}


Consistent returned values, returned from a single point, with a uniform type
class OneReturn
{

    public function bad($condition)
    {

        if ($condition == 1) {
            return 'one';
        }

        if ($condition == 2) {
            return 2;
        }

        return array(
            'value' => 3,
        );

    }

    public function good($condition)
    {

        $return = array('value' => 0);

        if ($condition == 1) {
            $return['value'] = 1;
        }

        if ($condition == 2) {
            $return['value'] = 1;
        }

        return $return;

    }

}


We'll call it an end to today's experience sharing session.
Guest