Skip to content

良好的编程风格

乱七八糟的代码会带来混乱的人生的:)

这一个开源项目已经总结得很好: 编码规范

在学习源码的同时记录一些比较清晰的片段巩固记忆,例如rospy的topic部分格式就很清晰,让我觉得我过去写的东西真是剪不断理还乱【】

规则的一致性对于一个项目十分重要。

C++

命名规则

https://google-styleguide.readthedocs.io/zh-cn/latest/google-cpp-styleguide/naming.html

注释规则

https://google-styleguide.readthedocs.io/zh-cn/latest/google-cpp-styleguide/comments.html

Python

命名规则

  1. 模块名和包名:尽量使用简短的小写字母,并可以使用下划线分隔单词,如rosgraph.names
  2. 类名:采用驼峰命名法(CamelCase),如TopicPoller
  3. 函数名和方法名:采用小写字母加下划线分隔单词的方式,如get_num_connectionsadd_epoll
  4. 常量名:全部采用大写字母加下划线分隔单词的方式,如DEFAULT_BUFF_SIZE
  5. 变量名:采用小写字母加下划线分隔单词的方式,如data_classresolved_name

注释习惯

  1. 文件头部注释:包括版权声明、许可协议等信息,以明确代码的法律归属和使用许可。
  2. 文档字符串(Docstring)
  3. 模块级别:简要说明模块的用途和功能。
  4. 类级别:说明类的功能、重要属性和方法。
  5. 函数和方法级别:描述参数、返回值、可能抛出的异常等。使用标准格式,如reStructuredText格式。
  6. 内联注释:用于解释复杂或关键的代码逻辑,简洁明了,并与代码保持适当间距。

具体示例

文件头部注释

# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# ...

模块和类的文档字符串

"""
rospy implementation of topics.

Client API
==========

L{Publisher} and L{Subscriber} are the client API for topics.
...
"""

函数和方法的文档字符串

有这个注释,在查看函数的时候就能看到对函数功能的注释,真的很重要QUQ

class Topic(object):
    """Base class of L{Publisher} and L{Subscriber}"""

    def __init__(self, name, data_class, reg_type):
        """
        Initialize a Topic instance.

        @param name: graph resource name of topic, e.g. 'laser'.
        @type  name: str
        @param data_class: message class for serialization
        @type  data_class: L{Message}
        @param reg_type: Registration.PUB or Registration.SUB
        @type  reg_type: str
        @raise ValueError: if parameters are invalid
        """
        ...

内联注释

if not rospy.core.is_initialized():
    self.resolved_name = rospy.names.resolve_name_without_node_name(name)
else:
    # init_node() has been called, so we can do normal resolution
    self.resolved_name = resolve_name(name)