I Know What You Did Last Faculty : C++ Coding Standard ISL Lab Seminar Hansol Kang
Contents Introduction Summary Rule of thumb Naming Header file Conditional Statement Comment
Introduction (Coding Standard) if (a > a_1 && b < b_1 && c < c_1 d>d_1) Readability int abc(int a, int b) { Do something Do you really need to make it a function? Coding Convention Optimization Maintenance 2
Rule of Thumb by 포프 Readability first (your code should be your documentation most of the time) Crash/Assert early. Don't wait until the worst case happens to make the crash condition. Follow IDE's auto formatted style unless you have really good reasons not to do so. (Ctrl + K + D in VC++) Learn from existing code 3
Naming Camel case : 각단어의첫문자를대문자로표기하며, 맨처음문자는소문자로표기.( 대문자로단어를구분 ) kurtcobain Pascal case : 첫단어를대문자로표기. KurtCobain Snake case : 단어사이를 underscore 로구분하여표기. kurt_cobain Hungarian notation : 데이터타입을의미하는접두어를사용하여표기. strkurtcobain 지양하는추세. Why? 1. IDE의발달로데이터타입을표기할필요 x 2. 변수의의미를파악하는것이더욱중요 4
Google C++ Naming(General Naming Rules) 함수이름, 변수이름, 파일이름은약어를피하고서술적으로작성. int price_count_reader; int num_errors; int num_dns_connections; int lstm_size; // No abbreviation. // "num" is a widespread convention. // Most people know what "DNS" stands for. // "LSTM" is a common machine learning abbreviation. int n; int nerr; int n_comp_conns; int wgc_connections; int pc_reader; int cstmr_id; // Meaningless. // Ambiguous abbreviation. // Ambiguous abbreviation. // Only your group knows what this stands for. // Lots of things can be abbreviated "pc". // Deletes internal letters. 가능하다면상세한이름을사용할것. 글자길이를줄이는것보다새로읽는사람이즉시이해하는것이더중요. 5
Google C++ Naming(File Names) 파일이름은모두소문자이어야하고, underscore 나 dash 로단어사이를연결함. 반드시 underscore 일필요는없으며, 프로젝트에서사용하던관례를따름. my_useful_class.cc my-useful-class.cc myusefulclass.cc url_table.h url_table.cc url_table-ini.h 클래스선언클래스정의많은코드를포함한인라인함수 Cf. Inline function 인라인함수는대부분헤더에선언하는것을기본으로그길이가너무긴경우 inl.h 로따로작성할것. 인라인함수는함수가작을때만 (10 라인이나그이하 ) 사용할것. 인라인함수의무분별한사용은지양. inline int max_limit(double x){ return x>255? 255 : (int)x; 6
Google C++ Naming(Type Names) 타입이름은대문자로시작하며 underscore 없이단어마다첫글자로대문자를사용. 클래스, 구조체, typedef, 열거형을포함한모든타입에대해같은규칙이적용. // Class and structure class UrlTable { struct UrlTableProperties { // Enumerated type enum UrlTableErrors { 7
Google C++ Naming(Variable Names) 변수이름은모두소문자로작성하며단어사이에 underscore 를사용. 클래스멤버변수는이름끝에 underscore 를사용. string table_name; // OK - uses underscore. string tablename; // OK - all lowercase. string tablename; // Bad - mixed case. 구조체는보통변수처럼사용. struct UrlTableProperties { string name; int num_entries; Cf. structs vs. classes class TableInfo { private: string table_name_; // OK - underscore at end. string tablename_; // OK. ; C++ 에서 struct 와 class 키워드는거의똑같이동작. 데이터를나르는수동적인객체의경우에만 struct 를사용하며, 그외의모든경우에는 class 를사용. structs 는멤버의값을읽고쓰는것이외의어떤기능도허용하지않음. 필드의접근 / 변경은메서드호출이아닌직접필드에접근하는방식으로작성할것. 더많은기능이필요하다면 class 가적당하며불확실한경우 class 로만들것. 8
Google C++ Naming(Constant Names) k 로시작하는대소문자가섞인이름을사용. const int kdaysinaweek = 7; 지역변수인지, 전역변수인지, 클래스의일부인지와상관없이모든컴파일시점상수들은다른변수들과조금다른이름규칙을사용. k 로시작하여매단어의첫글자를대문자로사용. 9
Google C++ Naming(Function Names) 일반함수들은대소문자가섞인방식을사용. accessors 와 mutators 는해당하는변수의이름과같은것을사용. AddTableEntry() DeleteUrl() OpenFileOrDie() crash 가발생할수있는함수 함수이름은대문자로시작하여각단어의첫글자를대문자로쓰고, underscore 는사용하지않음. 함수의실행중 crash 가발생할수있다면함수의이름뒤에 OrDie 를붙인다. 10
Google C++ Naming(Function Names cont.) accessors 와 mutators (get 과 set 함수 ) 는접근또는변경을하려는변수의이름과일치하는이름을사용. class MyClass { public:... int num_entries() const { return num_entries_; void set_num_entries(int num_entries) { num_entries_ = num_entries; private: ; int num_entries_; 11
Google C++ naming(macro names) 일반적으로매크로는사용하지않는것이좋으며, 절대적으로필요하다면대문자와 underscore 로작성. #define ROUND(x)... #define PI_ROUNDED 3.0 12
Google C++ Header Files(The #defile Guard) 모든헤더파일은여러번포함되지않기위해 #define 가드를사용. 유일성을보장하기위해 #define 가드는프로젝트의소스트리의절대경로에기반함. <PROJECT>_<PATH>_<FILE>_H_ 으로작성 예를들어프로젝트에 foo/src/bar/baz.h 파일이있다면 foo 는아래와같은가드를가져야함. #ifndef FOO_BAR_BAZ_H_ #define FOO_BAR_BAZ_H_... #endif // FOO_BAR_BAZ_H_ 13
Google C++ Header Files(Names and Order of Includes) 가독성을높이고숨겨진종속성을피하기위해서일관된순서를사용. 모든프로젝트의헤더파일은디렉터리단축표시인. ( 현재디렉터리 ) 이나.. ( 부모디렉터리 ) 을사용하지않고프로젝트의소스디렉터리의하위요소로나열. 예를들어 google-awesome-project/src/base/logging.h 는아래와같이 #include 되어야함. #include "base/logging.h" 예를들어 dir2/foo2.h 에있는것들을구현하거나테스트하기위한 dir/foo.cc 나 dir/foo_test.cc 를작성시아래의순서대로작성할것. 1. dir2 / foo2.h 2. C 시스템파일 3. C++ 시스템파일 4. 다른라이브러리의.h 파일 5. 현재프로젝트의.h 파일 14
Google C++ Header Files(Names and Order of Includes cont.) 예를들면 google-awesome-project/src/foo/internal/fooserver.cc 의 include 들은아래와같이작성할수있음. #include "foo/public/fooserver.h" // Appropriate location #include <sys/types.h> #include <unistd.h> #include <hash_map> #include <vector> #include "base/basictypes.h" #include "base/commandlineflags.h" #include "foo/public/bar.h" 15
Conditional Statement 조건문에서인수는비교하고자하는대상을왼쪽에배치할것. 당신의나이 가 10 보다큰가? 10 이 당신의나이 보다작은가? If (received < expected) if (received > expected) //good //bad 부정이아닌긍정을, 간단한것을, 흥미로운것을먼저처리할것. if (a == b) { else { if (a!= b) { else { 16
Conditional Statement 조건이길어질때리팩토링해서사용할것. if ( 복잡하고길고어렵고아무튼그런조건문 1 && 복잡하고길고어렵고아무튼그런조건문 2 복잡하고길고어렵고아무튼그런조건문 3) bool disconnected = 복잡하고길고어렵고아무튼그런조건문 1 && 복잡하고길고어렵고아무튼그런조건문 2 복잡하고길고어렵고아무튼그런조건문 3; if (disconnected) 17
Conditional Statement 삼항연산자를적절히사용할것. time_str += (hour >= 12)? "pm" : "am"; return exponent >= 0? mantissa*(1 << exponent) : mantissa / (1 << -exponent); if (hour >= 12) { time_str += "pm"; if (exponent >= 0) { return mantissa*(1 << exponent); else { time_str += "am"; else { retun mantissa / (1 << -exponent); 18
Comment 생각을기록하고나올것같은질문을예측할것. 또한코드의결함을설명하는것을두려워하지말것. TODO FIXME HACK XXX : 아직하지않은일 : 오작동을일으킨다고알려진코드 : 아름답지않은해결책 : 위험한것. 큰문제가있는경우 //TODO: 에디트박스숫자이외에입력방지 ( 完 ) //TODO: 에디트박스숫자길이제한. //TODO: 사이즈줄인것과원본을따로관리하여, 나중에비디오저장이가능하도록함. //HACK: 현재 1 번영상최적화. 19
Comment 모호한네이밍에는주석을달지말고네이밍을수정할것. // 반환하는항목의수나전체바이트수와같다. //Request 가정하는대로 Reply 에일정한한계를적용한다. void CleanReply(Request request, Reply reply); //'reply 이 cont/byte/ 등과같이 'request' 가정하는한계조건을만족시키도록한다. void EnforceLimitsFromRequest(Request request, Reply reply); 20
Summary 모든네이밍은약어사용을피하고서술적으로작성할것. 가독성좋게조건문을작성할것. 코드를수정하는것을최우선으로하고, 주석은반드시필요한경우에만작성할것. 21
Future Work Paper Review Proposed Model Tools Mathematical Study Others Vanilla GAN SpyGAN(about depth) Document Linear algebra Level Processor DCGAN Programming Probability and statistics Coding Standard LS GAN PyTorch Information theory Ice Propagation BEGAN Python executable & UI Pix2Pix Cycle GAN 22
Reference [1] 포프 C++ Coding Standards (https://docs.google.com/document/d/1ct8epgmxe0eopehvwufmbhg4tjr5kumcovkr5irqzmo/edit#heading=h.r2n9mhxbh2gg) [2] Google C++ Style Guide (Original) (https://google.github.io/styleguide/cppguide.html) [3] Google C++ Style Guide (Translated) (http://jongwook.kim/google-styleguide/trunk/cppguide.xml) [4] 읽기좋은코드가좋은코드다 (https://www.slideshare.net/e2goon/ss-33769330) [5] [ 코딩원칙?] if문. 그외가독성을올리자. (https://blog.naver.com/soguns/120139779253) [6] 무조건 if for 문에 { 를써야하는가... (http://www.gamecodi.com/board/zboard.php?id=gamecodi_talkdev&no=3727) [7] [ 읽기좋은자바스크립트코딩기법 ] 문장과표현식 ( 조건문과반복문 ) (https://jojoldu.tistory.com/6) 23
& 24
Appendix { 써야하는가? 붙여야하는가? if (condition) { dosomething(); else { dosomethingelse(); if (condition) { dosomething(); else { dosomethingelse(); 경험상으로 { 가엉켜서컴파일에러나런타임에러가발생해시간을낭비. IDE가자동으로들여쓰기해주는간단한 if for에서에러를낸적은없음. 안정성이라면세계제일이라는 NASA의표준코드 Style ASI 25