爲什麼要遵守代碼規範

幾乎所有的軟件開發公司,都有相應的代碼規範,有些大公司,特別是大的外包公司(尤其是對日外包公司),其代碼規範已經到了事無鉅細的地步。但相信很多開發人員(包括我剛開始軟件開發時),都會產生一些疑問:功能,性能無疑是最重要的,設計也很重要,爲什麼卻要把這麼多的精力放在代碼規範上呢,僅僅是爲了方便別人閱讀代碼,便於維護嗎?這樣一套套的代碼規範真的可以加快開發速度嗎?

在回答這些問題以前,先來看一下Wicket,Tapestry兩個功能相類似的基類其中的代碼節選。

來自Wicket1.3.3中org.apache.wicket.component的代碼

/**

 * Called on very component after the page is rendered. It will call onAfterRender for it self

 * and its children.

 */

public final void afterRender()

{

// if the component has been previously attached via attach()

// detach it now

try

{

setFlag(FLAG_AFTER_RENDERINGtrue);

onAfterRender();

getApplication().notifyComponentOnAfterRenderListeners(this);

if (getFlag(FLAG_AFTER_RENDERING))

{

throw new IllegalStateException(Component.class.getName() +

" has not been properly detached. Something in the hierarchy of " +

getClass().getName() +

" has not called super.onAfterRender() in the override of onAfterRender() method");

}

// always detach children because components can be attached

// independently of their parents

onAfterRenderChildren();

}

finally

{

// this flag must always be set to false.

setFlag(FLAG_RENDERINGfalse);

}

}

來自Tapestry3.04基類org.apache.tapestry.AbstractComponent的代碼

/** 

     *

     *  Returns a {@link Map} of all bindings for this component.  This implementation

     *  is expensive, since it has to merge the disassociated bindings (informal parameters,

     *  and parameters without a JavaBeans property) with the associated bindings (formal

     *  parameters with a JavaBeans property).

     *

     * @since 1.0.5

     *

     **/

    public Map getBindings()

    {

        Map result = new HashMap();

        // Add any informal parameters.

        if (_bindings != null)

            result.putAll(_bindings);

        // Now work on the formal parameters

        Iterator i = _specification.getParameterNames().iterator();

        while (i.hasNext())

        {

            String name = (String) i.next();

            if (result.containsKey(name))

                continue;

            IBinding binding = getBinding(name);

            if (binding != null)

                result.put(name, binding);

        }

        return result;

    }

很容易看出,以上的這幾段代碼,與公司的開發規範相比,也有很高的吻合度,事實上,Wicket和Tapestry的作者都是長期編寫架構的開發和設計人員,是非常頂尖的開發人員,遠非一般的高級工程師可比,但看這些代碼,卻沒有多少技巧在其中,可以算的上代碼規範很好的遵守者。很多國內很程序員經常會覺得,這些高手寫的代碼應該很難,很複雜。但事實告訴我們,大道至簡,這麼多的資深程序員甚至是架構師經過多年的編寫代碼,卻都達到了同樣的規範,可謂殊途同歸。爲什麼呢?這說明,只有這些來自經驗的規範才真正的體現了水平,纔是多代程序員的精華所在。當開發人員很好的遵守代碼規範來編寫代碼時,纔可以慢慢的體會到規則,纔會體會到設計。可以想像一下,如果遵守代碼規範,一個方法不得超出50行代碼,那麼大量的if else就不可能出現,而要代之以各種設計(如工廠,策略等設計模式)來解決問題。

大家如果有興趣看一下他們的源代碼,可以去Apache網站下載,他們的代碼中只有很少的一部分,估計不足5%的代碼纔會超出50行/每方法,違反常規的代碼規範的內容也會非常的少。

開發規範不僅不是一種可有可無的東西,反而是歷代程序員經過多年的開發所磨鍊出來的經驗總結。對於程序員來講,想寫好代碼,從遵守規範開始。

最後以小說裏的一句話來結束本文:技巧的本質就是規則,而規則使人成長

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章