编码风格(Coding Style)和编程准则(Programming Guidelines)

一、编码风格

1、哑元

在类中没有定义该成员变量,但是在成员函数参数列表中出现,以区分其它重载函数的变量,称为哑元。

iterator(IntStack& is, bool)

2、继承接口

class Schematic : public vector<Shape*> {

public:

~Schematic() { cout << "~Schematic" << endl; }

};

Schematic s;

s.push_back(new Square);

3、常用风格

1)大括号写法

无论是函数,还是定义类,结构,建议采用如下风格:

int func(int a);

int func(int a) {

int b = a + 1;

return b * 2;

}

这样我们可以一目了然那个是声明,那个是定义。

int func(int a) { return (a + 1) * 2; }//单行定义

2、标识符

类的第一个字母大写;函数和变量的第一个字母小写。The rest of the

identifier consists of one or more words, run together but distinguished

by capitalizing each word。如:

class FrenchVanilla : public IceCream {

FrenchVanilla myIceCreamCone(3);

void eatIceCreamCone();

3、头文件包含顺序

从最特殊到一般。即包含局部意义的,接着再是全局意义的。这样的话,如果我们自己的头文件不被它解析,我们可以马上知道。

4、在头文件中包含警卫

通过预处理指令#define实现。

// IncludeGuard.h

#ifndef INCLUDEGUARD_H

#define INCLUDEGUARD_H

// Body of header file here...

#endif // INCLUDEGUARD_H

我们可以看出,宏名是头文件名的大写,并把"."换成了"_"。

5、使用命名空间

No using declarations of any kind are allowed outside of function

definitions, and no global using directives are allowed in header files.In

cpp files, any global using directives will only affect that file

二、编程准则

1)First make it work, then make it fast.

2)Elegance always pays off.

3)Remember the “divide and conquer” principle. If the problem you’re looking at is too

confusing, try to imagine what the basic operation of the program would be, given the

existence of a magic “piece” that handles the hard parts. That “piece”is an object–write

the code that uses the object, then look at the object and encapsulate its hard parts into

other objects, etc.

4)Don’t automatically rewrite all your existing C code in C++ unless you need to

significantly change its functionality.

5)If you do have a large body of C code that needs changing, first isolate the parts of the

code that will not be modified, possibly wrapping those functions in an“API class”as static

member functions. Then focus on the code that will be changed, refactoring it into classes

to facilitate easy modifications as your maintenance proceeds.

6)When you create a class, make your names as clear as possible.

7)Write the test code first (before you write the class), and keep it with the class. Automate

the running of your tests through a makefile or similar tool.

8)Remember a fundamental rule of software engineering:All software design problems can

be simplified by introducing an extra level of conceptual indirection. This one idea is the

basis of abstraction, the primary feature of object-oriented programming.

9)Watch for long argument lists. Function calls then become difficult to write, read and

maintain. Instead, try to move the member function to a class where it is (more) appropriate,

and/or pass objects in as arguments.

10)Don’t repeat yourself. If a piece of code is recurring in many functions in derived classes

, put that code into a single function in the base class and call it from the derived-class

functions.

Notonly do you save code space, you provide for easy propagation of changes. You can

use an inline function forefficiency. Sometimes the discovery of this common code will add

valuable functionality to your interface.

11)When deciding between inheritance and composition, ask if you need to upcast to the

base type. If not, prefer composition (member objects) to inheritance. This can eliminate the

perceived need for multiple inheritance. If you inherit, users will think they are supposed to

upcast.

12)Sometimes you need to inherit in order to access protected members of the base class.

13)Avoid multiple inheritance.

14)Don’t use private inheritance. Although it’s in the language and seems to have occasio

nal functionality, it introduces significant ambiguities when combined with run-time type

identification. Create a private member object instead of using private inheritance.

15)Normally, don’t let the compiler create the constructors, destructors, or the operator= f

or you. Class designers should always say exactly what the class should do and keep the

class entirely under control. If you don’t want a copy-constructor or operator=, declare the

m as private. Remember that if you create any constructor, it prevents the default

constructor from being synthesized.

16)If your class contains pointers, you must create the copy-constructor, operator=, and

destructor for the class to work properly.

17)When you write a copy-constructor for a derived class, remember to call the base-class

copy-constructor explicitly (also the member-object versions).If you don’t, the default constructor will be called for the base class (or

member object) and that probably isn’t what you want. To call the base-class

copy-constructor, pass it the derived object you’re copying from:

Derived(const Derived& d) : Base(d) { // ...

18)When you write an assignment operator for a derived class, remember to call the

base-class version of the assignment operator explicitly.If you don’t, then nothing will

happen (the same is true for the member objects). To call the base-class assignment

operator, use the base-class name and scope resolution:

Derived& operator=(const Derived& d) {

Base::operator=(d);

19)Avoid the preprocessor. Always use const for value substitution and inlines for macros.

20)Avoid global variables. Always strive to put data inside classes. Global functions are more

likely to occur naturally than global variables,although you may later discover that a global

function may fit better as a static member of a class.

21)When choosing the return type of an overloaded operator, consider what will happen if

expressions are chained together. Return a copy or reference to the lvalue(return *this)so it

can be used in a chained expression (A = B = C). When defining operator=, remember x=x.

22)When writing a function, pass arguments by const reference as your first choice. As long

as you don’t need to modify the object being passed, this practice is best because it has

the simplicity of pass-by-value syntax but doesn’t require expensive constructions and

destructions to create a local object, which occurs when passing by value.

23)Be aware of temporaries. When tuning for performance, watch out for temporary

creation, especially with operator overloading. If your constructors and destructors are

complicated, the cost of creating and destroying temporaries can be high. When returning

a value from a function, always try to build the object “in place” with a constructor call in

the return statement:

return MyType(i, j);

rather than

MyType x(i, j);

return x;

The former return statement (the so-called return-value optimization) eliminates a

copy-constructor call and destructor call.

24)When creating constructors, consider exceptions. In the best case, the constructor won’t

do anything that throws an exception. In the next-best scenario, the class will be composed

and inherited from robust classes only, so they will automatically clean themselves up if an

exception is thrown. If you must have

naked pointers, you are responsible for catching your own exceptions and then deallocating

any resources pointed to before you throw an exception in your constructor. If a

constructor must fail, the appropriate action is to throw an exception.

25)Use exception hierarchies, preferably derived from the Standard C++ exception hierarchy

and nested as public classes within the class that throws the exceptions.

26)Throw exceptions by value and catch exceptions by reference. Let the exception-

handling mechanism handle memory management. If you throw pointers to exception

objects that have been created on the heap, the catcher must know to destroy the

exception, which is bad coupling(合). If you catch exceptions by value, you cause extra constructions and destructions; worse, the derived portions of your exception objects may be sliced during upcasting by value.

27)Don’t write your own class templates unless you must. Look first in the Standard C++

Library, then to vendors who create special-purpose tools. Become proficient with their

use and you’ll greatly increase your productivity.

28)Whenever you use built-in types as globals or automatics, don’t define them until you

can also initialize them. Define variables one per line along with their initialization. When

defining pointers, put the ‘*’ next to the type name. You can safely do this if you define

one variable per line. This style tends to be less confusing for the reader.

29)Don’t use the form MyType a = b; to define an object. This one feature is a major

source of confusion because it calls a constructor instead of the

operator=. For clarity, always be specific and use the form MyType a(b); instead. The

results are identical, but other programmers won’t be confused.

30)For a program to be robust, each component must be robust.

31)Use compiler error checking to your advantage. Perform all compiles with full warnings,

and fix your code to remove all warnings.

32)Prefer compile-time errors to runtime errors.

33)If you’re using exception specifications,install your own unexpected( ) function using

set_unexpected( ). Your unexpected( ) should log the error and rethrow the current

exception. That way, if an existing function gets overridden and starts throwing exceptions,

you will have a record of the culprit and can modify your calling code to handle the

exception.

34)Create a user-defined terminate( ) (indicating a programmer error) to log the error that

caused the exception, then release system resources, and exit the program.

35)If a destructor calls any functions, those functions might throw exceptions. A destructor

cannot throw an exception (this can result in a call to terminate( ), which indicates a

programming error),so any destructor that calls functions must catch and manage its own

exceptions.

36)Don’t create your own “decorated” private data member names (prepending

underscores, Hungarian notation, etc.), unless you have a lot

of pre-existing global values; otherwise, let classes and namespaces do the name scoping

for you.

37)Watch for overloading. A function should not conditionally execute code based on the

value of an argument, default or not. In this case, you should create two or more overloaded

functions instead.

38)Hide your pointers inside container classes. Bring them out only when you are going to

immediately perform operations on them. Pointers have always been a major source of bugs

. When you use new, try to drop the resulting pointer into a

container. Prefer that a container “own” its pointers so it’s responsible for cleanup. Even

better, wrap a pointer inside a class; if you still want it to look like a pointer, overload

operator-> and operator*. If you must have a free-standing pointer, always initialize it,

preferably to an object address, but to zero if necessary. Set it to zero when you delete it to

prevent accidental multiple deletions.

39)Don’t overload global new and delete; always do this on a class-by-class basis.

40)Prevent object slicing. It virtually never makes sense to upcast an object by value. To

prevent upcasting by value, put pure virtual functions in your base class.

41)Sometimes simple aggregation does the job. A“passenger comfort system”on an airline

consists of disconnected elements: seat, air conditioning, video, etc., and yet you need to

create many of these in a plane. Do you make private members and build a whole new

interface? No – in this case, the components are also part of the public interface, so you

should create public member objects. Those objects have their own private implementations,

which are still safe. Be aware that simple aggregation is not a solution to be used often, but

it does happen.

编码风格(Coding Style)和编程准则(Programming Guidelines)相关推荐

  1. 面试技巧篇 -- 编码风格 (Coding Style)

    面试技巧篇 – 编码风格 (Coding Style) Coding Style 在面试中有什么影响? 算法面试已经是绝大多数high-tech公司的敲门砖,这也导致了求职者花费大量时间准备算法刷题, ...

  2. python coding style guide 的快速落地实践——业内python 编码风格就pep8和谷歌可以认作标准...

    python coding style guide 的快速落地实践 机器和人各有所长,如coding style检查这种可自动化的工作理应交给机器去完成,故发此文帮助你在几分钟内实现coding st ...

  3. python coding style why_python coding style guide 的快速落地实践——业内python 编码风格就pep8和谷歌可以认作标准...

    python coding style guide 的快速落地实践 机器和人各有所长,如coding style检查这种可自动化的工作理应交给机器去完成,故发此文帮助你在几分钟内实现coding st ...

  4. 《Python编程从入门到实践》记录之类编码风格

    遵守一定的编写规则,能够使得程序更容易阅读理解和使用 类编码风格: 类名使用驼峰命名法,即类名中的每个单词的首字母都大写,且不用下划线.实例名和模块名都采用小写格式,且在单词之间加上下划线 每个类,都 ...

  5. c++编码风格指南_带回家的编码挑战的基本指南

    c++编码风格指南 by Jane Philipps 简·菲利普斯 带回家的编码挑战的基本指南 (The Essential Guide to Take-home Coding Challenges) ...

  6. Linux 内核编码风格【转】

    原文:http://www.cnblogs.com/baochuan/archive/2013/04/08/3006615.html Linux 内核编码风格 序 像其他大型软件一样,Linux制订了 ...

  7. 良好的JavaScript编码风格(语法规则)

    编码风格 1.概述 "编程风格"(programming style)指的是编写代码的样式规则.不同的程序员,往往有不同的编程风格. 有人说,编译器的规范叫做"语法规则& ...

  8. c++编码风格指南_100%正确的编码样式指南

    c++编码风格指南 Here are three links worth your time: 这是三个值得您花费时间的链接: The 100% correct coding style guide ...

  9. 来自 Google 的 R 语言编码风格指南

    来自 Google 的 R 语言编码风格指南 R 语言是一门主要用于统计计算和绘图的高级编程语言. 这份 R 语言编码风格指南旨在让我们的 R 代码更容易阅读.分享和检查. 以下规则系与 Google ...

最新文章

  1. Java类加载器详解
  2. Delphi 调用C#编写的WebService 参数为Null解决方法
  3. Python程序设计题解【蓝桥杯官网题库】 DAY10-算法训练
  4. Robot Framework-Ride界面介绍及库的添加
  5. eclipse从svn导入maven项目变成普通项目解决办法
  6. 【Java】java jmx 入门案例
  7. asp.net signalR 专题—— 第一篇 你需要好好掌握的实时通讯利器
  8. vue-cropper 自定义旋转任意角度
  9. ApolloStudio高手之路(4):用Python以最轻便的方式进行金橙子激光打标板卡二次开发(以EzCad2为载体二次开发)
  10. 智能硬件(1)--- 智能硬件开发流程
  11. 解决input输入中文时,拼音在输入框内会触发input事件的问题
  12. 为什么压缩图片和压缩
  13. 高德地图怎么测量面积_高德地图如何测量海拔
  14. 离婚时,住房公积金分割吗?
  15. DLL输出类使用研究手记(ZZ)
  16. ssm毕设项目客房订餐系统s2whx(java+VUE+Mybatis+Maven+Mysql+sprnig)
  17. 计算机科学导论参考文献,物联网毕业论文参考文献精选
  18. 中年黑客高考“回忆杀” :如果你想从事安全。。。
  19. Android中直播视频技术探究之---基础知识大纲介绍
  20. SolidWorks toolbox齿轮再修改方法

热门文章

  1. C# 通过百度地图API,获取访问IP详细地址(上网IP的大致位置信息,一般为城市级别)
  2. 针对在线游戏玩家的 DDoS 攻击和破坏性的涟漪效应
  3. python罗马数字转换_Python练习【3】【罗马数字转换/查找公共前缀】
  4. 《互联网时代》第一集·时代
  5. 仿苹果AppStore 环形下载进度条
  6. 企业信使运营管理平台官网_注册_开自助充值
  7. .NET忠实粉丝们,请进
  8. Spring官网学习(一)概述
  9. 【CTF WriteUp】2020中央企业”新基建“网络安全技术大赛初赛Crypto题解
  10. 埋点设计思路 - 基础知识和设计流程