แนวปฎิบัติในการเขียนโค้ด C++ จาก Google

21. April 2009

ไปแอบอ่านมานิดหน่อยครับ เค้าว่าเป็นแนวปฎิบัติที่ใช้กันใน Google คนเขียน C++ ลองไปอ่านดู

Google C++ Style Guide

เรื่องที่น่าสังเกตหลังอ่านเรื่องหนึ่งคือ “Do not use Hungarian notation” ตอนสมัยผมสนใจ C++ ใหม่ๆ เมื่อนานมากแล้วสมัย VB6 กำลัง Boom จำได้ว่าเค้า Encourage นักหนา ให้เอา prefix แปลกๆมานำหน้าชื่อตัวแปล ไม่ว่าจะเป็น lpstrXxxx, szXxxx, hWndXxxx, … blah blah อ่านทีนึงแทบจะเป็นลม ประกอบกับตอนนั้นอ่าน Code C++ ที่ใช้สร้างหน้าต่างโง่ๆมาอันนึง ไม่มีอะไรเลย ใช้ Code ประมาณ 60 บรรทัด (มารู้ตอนแก่ว่ามันคือการใช้ Win32 API ล้วนๆ) แต่ VB6 แค่ New Project ก็เสร็จแล้ว ทำให้ตอนนั้นผมเลิกสนใจ C++ ไปเลย

กลับมาเรื่อง Hungarian Notation ชื่อตัวแปรที่ Google แนะนำให้ตั้งจะเป็นแบบ lower case หมด แล้วใช้ underscore คั่นระหว่างคำแทน ก็ดูอ่านง่ายดี เหมือนภาษา C

How to Name

Give as descriptive a name as possible, within reason. Do not worry about saving horizontal space as it is far more important to make your code immediately understandable by a new reader. Examples of well-chosen names:

int num_errors;                  // Good.
int num_completed_connections;   // Good.

Poorly-chosen names use ambiguous abbreviations or arbitrary characters that do not convey meaning:

int n;                           // Bad - meaningless.
int nerr;                        // Bad - ambiguous abbreviation.
int n_comp_conns;                // Bad - ambiguous abbreviation.

Type and variable names should typically be nouns: e.g., FileOpener, num_errors.

Function names should typically be imperative (that is they should be commands): e.g., OpenFile(), set_num_errors(). There is an exception for accessors, which, described more completely in Function Names, should be named the same as the variable they access.

จริงๆแล้วภาษา C++ มันเปิดมาก เปิดจนมีวิธีการหลายอย่างในการทำเรื่องๆเดียว ตัวเลือกก็เลยมีมากมาย เอาโค้ดคนอื่นมาทำต่อก็เลยต้องใช้เวลาหน่อย มีเรื่องน่าสนใจอีกหลายอย่างเกี่ยวกับการเลือกแนวปฎิบัติของ Google ลองไปอ่านกันดู :)

Native , ,