Google对外发布C++编码规范
Google的C++编码规范对外发布,引起了业内开发人员的广泛关注。
其中,来自硅谷的柯化成认为,这是地球上最好的一份C++编程规范,没有之一,建议广大国内外IT人员研究使用。
盛大的资深开发者赵劼表示,“非常同意。Google在这方面下足了功夫,让所有人写出来的代码都使用同样的规范,就好像在工程师编程世界里普及普通话一样。很多资深工程师刚加入的时候被迫学习编码规范,开始不习惯,后来发现收益非浅。所谓磨刀不误砍柴功,创业公司更应该关注。”
科泰的陈榕也认为,“希望Google索性再出版一个工具,类似早先C语言的lint,按照该规范自动排版。否则谁记得住这么多条条框框?”
C++开发者杜昶旭给大家的建议是,“建议所有开发人员反复阅读此编码规范,直到可以背下来再开始写代码。当然,更好的做法是根据这个再补充出更具体的执行策略。学校里这些知识老师强调的太少,提前自学吧。”
当然,也有不同的声音,来自大连的sagasw就认为,“关于Google的C++编码规范,不知为何突然又火起来,这个规范在C++社区中应用的不多,关注度远不如Gtest,另外这个规范对于Google是有帮助的,但不是最好的,也不是一定适合每个公司的,每个决定后面都有一个tradeoff,不知这些光会用规范,那意义不大。”
“土豆”也表示,“Google的C++编码规范没有说的这么好吧,至少我看Webkit的源码中,明显苹果的代码比Google的代码漂亮些,也容易看些,受不了Google源码中的N多下划线。”
Example
They say an example is worth a thousand words so let's start off with an example that should give you a feel for the style, spacing, naming, etc.
An example header file, demonstrating the correct commenting and spacing for an @interface declaration
// GTMFoo.h
// FooProject
//
// Created by Greg Miller on 6/13/08.
// Copyright 2008 Google, Inc. All rights reserved.
//
#import
// A sample class demonstrating good Objective-C style. All interfaces,
// categories, and protocols (read: all top-level declarations in a header)
// MUST be commented. Comments must also be adjacent to the object they're
// documenting.
//
// (no blank line between this comment and the interface)
@interface GTMFoo : NSObject {
@private
NSString *foo_;
NSString *bar_;
}
// Returns an autoreleased instance of GMFoo. See -initWithString: for details
// about the argument.
+ (id)fooWithString:(NSString *)string;
// Designated initializer. |string| will be copied and assigned to |foo_|.
- (id)initWithString:(NSString *)string;
// Gets and sets the string for |foo_|.
- (NSString *)foo;
- (void)setFoo:(NSString *)newFoo;
// Does some work on |blah| and returns YES if the work was completed
// suclearcase/" target="_blank" >ccessfuly, and NO otherwise.
- (BOOL)doWorkWithString:(NSString *)blah;
@end
An example source file, demonstating the correct commenting and spacing for the @implementation of an interface. It also includes the reference implementations for important methods like getters and setters, init, and dealloc.
//
// GTMFoo.m
// FooProject
//
// Created by Greg Miller on 6/13/08.
// Copyright 2008 Google, Inc. All rights reserved.
//
#import "GTMFoo.h"
@implementation GTMFoo
+ (id)fooWithString:(NSString *)string {
return [[[self alloc] initWithString:string] autorelease];
}
// Must always override super's designated initializer.
- (id)init {
return [self initWithString:nil];
}
- (id)initWithString:(NSString *)string {
if ((self = [super init])) {
foo_ = [string copy];
bar_ = [[NSString alloc] initWithFormat:@"hi %d", 3];
}
return self;
}
- (void)dealloc {
[foo_ release];
[bar_ release];
[super dealloc];
}
- (NSString *)foo {
return foo_;
}
- (void)setFoo:(NSString *)newFoo {
[foo_ autorelease];
foo_ = [newFoo copy];
}
- (BOOL)doWorkWithString:(NSString *)blah {
// ...
return NO;
}
@end