the art of readable code - dongpv

29
The Art of Readable Code GMO VNLAB – PHAM VAN DONG

Upload: dong-do

Post on 18-Jul-2015

147 views

Category:

Technology


7 download

TRANSCRIPT

Page 1: The Art of Readable Code - DongPV

The Art of Readable CodeGMO VNLAB – PHAM VAN DONG

Page 2: The Art of Readable Code - DongPV

Nội dungI. Hiểu sai ý nghĩa đặt tên

II. Thẩm mỹ code

Page 3: The Art of Readable Code - DongPV

Hiểu sai ý nghĩa đặt tên

results = Database.all_objects. filter("year <= 2015")

Chọn ra các bản ghi year <= 2015

=> select()

Chọn ra các bản ghi !(year <= 2015)

=> exclude()

Page 4: The Art of Readable Code - DongPV

Hiểu sai ý nghĩa đặt tênGiới hạn Min, Max bao gồm cả giới hạn của nó

CART_TOO_BIG_LIMIT = 10if shopping_cart.num_items() >= CART_TOO_BIG_LIMIT:

Error("Too many items in cart.")

CART_TOO_BIG_LIMIT = 10if shopping_cart.num_items() > CART_TOO_BIG_LIMIT:

Error("Too many items in cart.")

MAX_ITEMS_IN_CART = 10if shopping_cart.num_items() > MAX_ITEMS_IN_CART:

Error("Too many items in cart.")

Page 5: The Art of Readable Code - DongPV

Hiểu sai ý nghĩa đặt tênBiểu thị một khoảng từ phần tử đầu đến phẩn tử cuối cùng

◦ print integer_range(start=2, stop=4)

◦ print integer_range(first=2, last=4)

Min, Max

◦ set.PrintKeys(first="Bart", last="Maggie")

a b c

first last

Page 6: The Art of Readable Code - DongPV

Hiểu sai ý nghĩa đặt tênBiểu thị kết thúc và bắt đầu

In ra tất cả các sự kiên trong ngày 16

First/Last◦ PrintEventsInRange("OCT 16 12:00am", "OCT 16 11:59:59.9999pm")

Begin/End◦ PrintEventsInRange("OCT 16 12:00am", "OCT 17 12:00am")

a b c

Begin end

Page 7: The Art of Readable Code - DongPV

Hiểu sai ý nghĩa đặt tênget*()

public class StatisticsCollector {public void addSample(double x) { ... }public double getMean() {

// Iterate through all samples and return total / num_samples

}...

}

=> get*() trả về giá trị là thuộc tính

-> computeMean()

Page 8: The Art of Readable Code - DongPV

Hiểu sai ý nghĩa đặt tênCác giá trị kiểu Boolean

bool read_password = true;

◦ Chúng ta cần đọc password◦ need_password

◦ Password đã được đọc rồi◦ user_is_authenticated

Tránh nhưng hạng tử phủ định:◦ bool disable_ssl = false;

◦ bool use_ssl = true;

Page 9: The Art of Readable Code - DongPV

Hiểu sai ý nghĩa đặt tênTóm tắt• Tên tốt: Không thể hiểu sai ý nghĩa, người khá sẽ hiểu ý nghĩa

duy nhất

• Trước khi đặt tên hãy hình dung cái tên đó sẽ có thể hiểu sai như thế nào

• Định nghĩa giới hạn cao thấp cho các biến với tiền tố min_ và max_, bao gồm đầu mút với first và last

• Nhưng biến boolean tránh đạt phủ định

• Cẩn thận với nhưng mong muôn của người gọi hàm mà quên đi công việc của hàm

Page 10: The Art of Readable Code - DongPV

Thẩm mỹ codeclass StatsKeeper {public:// A class for keeping track of a series of doubles

void Add(double d); // and methods for quick statistics about them

private: int count; /* how many so far*/ public:

double Average();private: double minimum;list<double>

past_items;double maximum;

};

Page 11: The Art of Readable Code - DongPV

Thẩm mỹ code// A class for keeping track of a series of doubles// and methods for quick statistics about them.class StatsKeeper {

public:void Add(double d);double Average();

private:list<double> past_items;int count; // how many so far

double minimum;double maximum;

};

Page 12: The Art of Readable Code - DongPV

Thẩm mỹ codeBố trí cách dòng

Sủ dụng hàm để đưa vào khuôn khổ

Phân cách nhau thẳng theo cột

Sử dụng thứ tự có ý nghĩa

Gộp khai báo vào một khối

Page 13: The Art of Readable Code - DongPV

Bố trí cách dòngGiả sử một chương trình cần ước lược tốc độ kết nối mạng• Tốc độ kết nối (Kbps)

• Độ chễ trung bình (ms)

• Độ chễ jitter (ms)

• Tỉ lệ số gói tin thất bại (%)

Page 14: The Art of Readable Code - DongPV

public class PerformanceTester {public static final TcpConnectionSimulator wifi = new

TcpConnectionSimulator(500, /* Kbps */80, /* millisecs latency */200, /* jitter */1 /* packet loss % */);

public static final TcpConnectionSimulator t3_fiber =new TcpConnectionSimulator(

45000, /* Kbps */10, /* millisecs latency */0, /* jitter */0 /* packet loss % */);

public static final TcpConnectionSimulator cell = new TcpConnectionSimulator(

100, /* Kbps */400, /* millisecs latency */250, /* jitter */5 /* packet loss % */);

}

Page 15: The Art of Readable Code - DongPV

public class PerformanceTester {public static final TcpConnectionSimulator wifi =

new TcpConnectionSimulator(500, /* Kbps */80, /* millisecs latency */200, /* jitter */1 /* packet loss % */);

public static final TcpConnectionSimulator t3_fiber =new TcpConnectionSimulator(

45000, /* Kbps */10, /* millisecs latency */0, /* jitter */0 /* packet loss % */);

public static final TcpConnectionSimulator cell =new TcpConnectionSimulator(

100, /* Kbps */400, /* millisecs latency */250, /* jitter */5 /* packet loss % */);

}

Page 16: The Art of Readable Code - DongPV

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(45000, 10, 0, 0);

public static final TcpConnectionSimulator cell =new TcpConnectionSimulator(100, 400, 250, 5);

}

Page 17: The Art of Readable Code - DongPV

Sử dụng hàm để đưa vào khuôn khổThực hiện một hàm có chức năng như sau

// Turn a partial_name like "Doug Adams" into "Mr. Douglas Adams".

// If not possible, 'error' is filled with an explanation.

string ExpandFullName(DatabaseConnection dc, string partial_name, string* error);

Page 18: The Art of Readable Code - DongPV

Sử dụng hàm để đưa vào khuôn khổDatabaseConnection database_connection;string error;assert(ExpandFullName(database_connection, "Doug Adams", &error)

== "Mr. Douglas Adams");assert(error == "");assert(ExpandFullName(database_connection, " Jake Brown", &error)

== "Mr. Jacob Brown III");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");

Page 19: The Art of Readable Code - DongPV

Sử dụng hàm để đưa vào khuôn khổ

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");

Page 20: The Art of Readable Code - DongPV

Sử dụng hàm để đưa vào khuôn khổ

void CheckFullName(string partial_name,string expected_full_name,string expected_error) {

// database_connection is now a class memberstring error;string full_name = ExpandFullName(database_connection, partial_name, &error);assert(error == expected_error);assert(full_name == expected_full_name);

}

Page 21: The Art of Readable Code - DongPV

Phân cách nhau thẳng theo cột

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");

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

Page 22: The Art of Readable Code - DongPV

Phân cách nhau thẳng theo cột

(+) Cực kỳ dễ nhìn, dễ hiểu

(−) Tạo thêm việc căn chỉnh nó, một dòng phải sửa -> sửa toàn bộ

(=) Rất đáng để thử

commands[] = {...

{ "timeout" , NULL , cmd_spec_timeout },{ "timestamping" , &opt.timestamping , cmd_boolean },{ "tries" , &opt.ntry , cmd_number_inf },{ "useproxy" , &opt.use_proxy , cmd_boolean },{ "useragent“ , NULL , cmd_spec_useragent },...

};

Page 23: The Art of Readable Code - DongPV

Sử dụng thứ tự có ý nghĩadetails = request.POST.get('details')location = request.POST.get('location')phone = request.POST.get('phone')email = request.POST.get('email')url = request.POST.get('url')

•Tạo thứ tự thẻ <input> thứ tự tương ứng

•Sắp sếp theo thứ tự quan trọng trước

•Sắp sếp theo a,b,c

Page 24: The Art of Readable Code - DongPV

Gộp khai báo vào một khốiclass FrontendServer {

public: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);~FrontendServer();

};

Page 25: The Art of Readable Code - DongPV

Gộp khai báo vào một khốiclass FrontendServer {

public:FrontendServer();~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);

};

Page 26: The Art of Readable Code - DongPV

Gộp khai báo vào một khốiclass FrontendServer {

public:FrontendServer();~FrontendServer();

void ViewProfile(HttpRequest* request);void SaveProfile(HttpRequest* request);void FindFriends(HttpRequest* request);

void OpenDatabase(string location, string user);string ExtractQueryParam(HttpRequest* request, string param);void ReplyOK(HttpRequest* request, string html);void ReplyNotFound(HttpRequest* request, string error);void CloseDatabase(string location);

};

Page 27: The Art of Readable Code - DongPV

Gộp khai báo vào một khốiclass FrontendServer {

public:FrontendServer();~FrontendServer();

// Handlersvoid ViewProfile(HttpRequest* request);void SaveProfile(HttpRequest* request);void FindFriends(HttpRequest* request);

// Request/Reply Utilitiesstring ExtractQueryParam(HttpRequest* request, string param);void ReplyOK(HttpRequest* request, string html);void ReplyNotFound(HttpRequest* request, string error);

// Database Helpersvoid OpenDatabase(string location, string user);void CloseDatabase(string location);

};

Page 28: The Art of Readable Code - DongPV

Thẩm mỹ codeTóm tắt• Nếu có nhiều đoạn giống nhau, hãy cố gắng gộp lại

• Điểu chỉnh các phần theo cột

• Đặt theo thứ tự có ý nghĩa

• Sử dụng những dòng trắng để cách các phần có cùng luồng sửlý

Page 29: The Art of Readable Code - DongPV

Thank you!