组织优秀代码的四原则

96
小熊jessie
2017.07.23 10:41* 字数 793

代码写了5年,必然会产生审丑疲劳,代码混乱不堪,无法维护,可阅读性基本没有。面对种种的问题,如何使代码更优雅,更具可读性便成了迫切需要解决的问题。下面我从实战中总结了四项基本原则,只要你灵活运用,我保证你的代码绝对漂亮的让自己不敢相信。下面我尝试以一种教学的方式教给你这四项基本原则。

一、把代码按逻辑相关性分成不同的段落,亮点是每个段落可以给个总结性的注释

我们可能都写过作文,试想一下,如果一篇文章没有任何分段,一气呵成,你阅读之后会有什么感想?会不会想杀了作者?

其实,码代码和写文章是可以类比的,如果你写得代码中没有任何分段,对于代码阅读者来说难道不是地狱吗?可能语言的描述终究是太抽象,那我就呈上两个例子让大家吐槽一下吧。
示例1:

public interface FrontendServer {
    void viewProfile(HttpRequest request);
    void openDatabase(String location,String user);
    void saveProfile(HttpRequest request);
    String extractQueryParam(HttpRequest request,String param);
    void replyOK(HttpRequest request,String html);
    void findFriends(HttpRequest request);
    void replyNotFound(HttpRequest request,String error);
    void closeDatabase(String location);
}

示例2:

# Import the user's email contracts, and match them to users in our system.
# Then display a list of those users that he/she isn't already friends with.
def suggest_new_friends(user,email_password):
    friends = user.friends()
    friend_emails = set(f.email for f in friends)
    contacts = import_contacts(user.email,email_password)
    contact_emails = set(c.email for c in contacts)
    non_friend_emails = contact_emails-friend_emails
    suggested_friends = User.objects.select(email_in=non_friend_emails)
    display['user'] = user
    display['friends'] = friends
    display['suggested_friends'] = suggested_friends
    return render("suggested_friends.html",display)

吐槽时间。。。

尝试使用一下我们的代码分段原则,闪亮的结果如下:

示例1应用原则一:

public interface FrontendServer {
    // Handlers
    void viewProfile(HttpRequest request);
    void saveProfile(HttpRequest request);
    void findFriends(HttpRequest request);

    // Request/Reply Utilities
    String extractQueryParam(HttpRequest request,String param);
    void replyOK(HttpRequest request,String html);
    void replyNotFound(HttpRequest request,String error);
    
    // Database Helpers
    void openDatabase(String location,String user);
    void closeDatabase(String location);
}

示例2应用原则一:

# Import the user's email contracts, and match them to users in our system.
# Then display a list of those users that he/she isn't already friends with.
def suggest_new_friends(user,email_password):
    # Get the user's friends' email addresses.
    friends = user.friends()
    friend_emails = set(f.email for f in friends)

    # Import all email addresses from this user's email account.
    contacts = import_contacts(user.email,email_password)
    contact_emails = set(c.email for c in contacts)

    # Find matching users that  they aren't already friends with.
    non_friend_emails = contact_emails-friend_emails
    suggested_friends = User.objects.select(email_in=non_friend_emails)

    @ Display these lists on the page.
    display['user'] = user
    display['friends'] = friends
    display['suggested_friends'] = suggested_friends
    
    return render("suggested_friends.html",display)

二、使用一致的布局,让相似的代码看起来相似

你要问我为什么让相似的代码看起来相似会使代码更清晰更容易理解,我竟然无言以对。自以为可能是人类的认知原理导致的,我无法给出更官方的解释,但是我可以给你几个例子让你好好体会一下如果不这么做带来的后果。
示例1:

public class PerformanceTester {
    public static final TcpConnectionSimulator wifi = new TcpConnectionSimulator(
            500, /* kpbs */
            80, /* millisecs latency */
            200, /* jitter */
            1 /* packet loss % */);
    public static final TcpConnectionSimulator t3_fiber =
            new TcpConnectionSimulator(
                500, /* kpbs */
                80, /* millisecs latency */
                200, /* jitter */
                1 /* packet loss % */);
    public static final TcpConnectionSimulator cell = new TcpConnectionSimulator(
            100, /* kbps */
            400, /* millisecs latency */
            250, /* jitter */
            5 /* packet loss % */);

}

我们使用原则二来变化示例1,结果如下:

public class PerformanceTester {
    public static final TcpConnectionSimulator wifi = 
            new TcpConnectionSimulator(
            500, /* kpbs */
            80,  /* millisecs latency */
            200, /* jitter */
            1    /* packet loss % */);
    public static final TcpConnectionSimulator t3_fiber =
            new TcpConnectionSimulator(
            500, /* kpbs */
            80,  /* millisecs latency */
            200, /* jitter */
            1    /* packet loss % */);
    public static final TcpConnectionSimulator cell = 
            new TcpConnectionSimulator(
            100, /* kbps */
            400, /* millisecs latency */
            250, /* jitter */
            5    /* packet loss % */);

}

变换的结果很让人眼前一亮,但还不是很完美,通过原则三,会将完美进行到极致。我们首先介绍一下原则三。

三、使用方法或者其他技术消除重复的代码

消除代码块中重复的代码,会使得代码逻辑更加简洁清晰,更具表达性,重点更加突出。
示例1:

public class PerformanceTester {
    public static final TcpConnectionSimulator wifi = 
            new TcpConnectionSimulator(
            500, /* kpbs */
            80,  /* millisecs latency */
            200, /* jitter */
            1    /* packet loss % */);
    public static final TcpConnectionSimulator t3_fiber =
            new TcpConnectionSimulator(
            500, /* kpbs */
            80,  /* millisecs latency */
            200, /* jitter */
            1    /* packet loss % */);
    public static final TcpConnectionSimulator cell = 
            new TcpConnectionSimulator(
            100, /* kbps */
            400, /* millisecs latency */
            250, /* jitter */
            5    /* packet loss % */);

示例1应用原则三:

public class PerformanceTester {
    // TcpConnectionSimulator(throughput, latency, jitter, packet_loss)
    //                            [Kbps]   [ms]    [ms]    [percent]   
    
    public static final TcpConnectionSimulator wifi =
            new TcpConnectionSimulator(500, 80, 200, 1);
    public static final TcpConnectionSimulator t3_fiber =
            new TcpConnectionSimulator(500, 80, 200, 1);
    public static final TcpConnectionSimulator cell =
            new TcpConnectionSimulator(100, 400, 250, 5);
}

示例2:

 DatabaseConnectio database_connection;
    string error;
    assert(expandFullName(database_connection,"Doug Adams",&error)=="Mr. Douglas Adams");
    assert(error == "");   
    assert(expandFullName(database_connection,"No Such Guy",&error)=="");
    assert(error =="no match found");   
    assert(expandFullName(database_connection,"John",&error)=="");
    assert(error =="more than one result");

示例2应用原则三:

    checkFullName("Doug Adams","Mr. Douglas Adams","");
    checkFullName("Jake Brown","Mr. Jake Brown III","");
    checkFullName("No Such Guy","","no match found");
    checkFullName("John","","more than one result");

    void checkFullName(String partial_name,
                       String expeted_full_name,
                       String expected_error){
        // database_connection is now a class member
        String error;
        String full_name = expandFullName(database_connection,partial_name,&error);
        assert(error == expected_error);
        assert(full_name == expeted_full_name);
    }

四、使用列对齐来使代码更加易读

使用列对齐的方式组织代码,可以让语句之间的对应关系清晰明显,阅读者从中很容易获取方法的调用规则等信息,这对于理解代码和发现代码中的错误有极大帮助。

示例1:

    checkFullName("Doug Adams","Mr. Douglas Adams","");
    checkFullName("Jake Brown","Mr. Jake Brown III","");
    checkFullName("No Such Guy","","no match found");
    checkFullName("John","","more than one result");

示例1应用原则四:

    checkFullName("Doug Adams"  , "Mr. Douglas Adams"  , "");
    checkFullName("Jake Brown"  , "Mr. Jake Brown III" , "");
    checkFullName("No Such Guy" , ""                   , "no match found");
    checkFullName("John"        , ""                   , "more than one result");

示例2:

# Extract POST parameters to local variables
details = request.POST.get('details')
location = request.POST.get('location')
phone = request.POST.get('phone')
email = request.POST.get('email')
url = request.POST.get('url')

示例2应用原则四:

# Extract POST parameters to local variables
details  = request.POST.get('details')
location = request.POST.get('location')
phone    = request.POST.get('phone')
email    = request.POST.get('email')
url      = request.POST.get('url')

如果想了解更多信息或者对开源项目感兴,请加我的微信公众号,我在那里等你

小熊的开源社区.jpg
小熊的开源社区.jpg