ros Best Practices
This guide outlines the essential practices for developing robust, performant, and maintainable ROS 2 applications. Adherence to these rules ensures consistency, leverages ROS 2's advanced features, and aligns with the project's quality standards.
1. Code Quality and Static Analysis (The ament Way)
Mandate ament_lint_auto: Always integrate ament_lint_auto and ament_lint_common into your package build process. This is non-negotiable for catching style violations and common bugs early.
- ❌ BAD: Relying on manual checks or pre-commit hooks that can be bypassed.
- ✅ GOOD: Automatic enforcement during every build.
# CMakeLists.txt
# ...
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
ament_lint_auto_find_test_dependencies()
endif()
# ...
<!-- package.xml -->
<package format="2">
<!-- ... -->
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<!-- ... -->
</package>
C++ Style Enforcement: Use ament_cpplint and ament_cppcheck. Follow Google C++ Style Guide and modern C++17/20 features. Prioritize RAII and explicit smart pointer ownership.
- ❌ BAD: Raw pointers for resource management; ignoring
cpplint warnings.
- ✅ GOOD:
std::unique_ptr, std::shared_ptr for ownership.
// ❌ BAD: Manual memory management, potential leak
MyObject* obj = new MyObject();
// ...
delete obj; // Easy to forget or double-delete
// ✅ GOOD: RAII with smart pointers
std::unique_ptr<MyObject> obj = std::make_unique<MyObject>();
// Resource automatically managed
Python Style Enforcement: Adhere strictly to REP-8, which extends PEP 8. Use black for formatting and flake8 for linting. Ensure proper naming, imports, and docstrings.
- ❌ BAD: Inconsistent formatting, missing docstrings,
camelCase for variables.
- ✅ GOOD:
snake_case for variables/functions, clear docstrings, black-formatted code.
# ❌ BAD
def calculateVelocity(pos1, pos2, time):
# ...
return vel
# ✅ GOOD
def calculate_velocity(position1: float, position2: float, time_delta: float) -> float:
"""Calculates average velocity."""
# ...
return velocity
Copyright and Licensing: Use ament_copyright to ensure all source files have correct copyright and license headers.
- Run
ament_copyright --add-missing "Your Name" apache2 to automate this.
2. Code Organization and Structure
Python Package Layout (Catkin): Adopt the recommended src/<package_name>/__init__.py structure. This ensures proper Python package discovery and avoids namespace collisions.
- ❌ BAD: Scattering Python files directly in the package root or relying on
roslib.load_manifest.
- ✅ GOOD: Centralized, importable Python code.
my_package/
├── CMakeLists.txt
├── package.xml
├── setup.py
└── src/
└── my_package/
├── __init__.py
└── my_module.py
# setup.py for the above structure
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['my_package'],
package_dir={'': 'src'},
)
setup(**d)
Node/Script Installation: Use catkin_install_python for ROS nodes and scripts. Install to ${CATKIN_PACKAGE_BIN_DESTINATION} to make them accessible via rosrun without polluting the global PATH.
- ❌ BAD: Installing scripts directly to
/usr/bin via setup.py scripts argument.
- ✅ GOOD: Package-isolated executables.
# CMakeLists.txt
# ...
catkin_install_python(PROGRAMS
nodes/my_node.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
# ...
3. Performance Considerations
Embrace Node Composition: Always use node composition for performance-critical applications, especially those with large messages (images, point clouds) or resource-constrained environments. This enables intra-process communication (IPC) for zero-copy data transfer.
- ❌ BAD: Running every node in its own process, leading to high inter-process communication overhead.
- ✅ GOOD: Grouping related nodes into a single composed process.
// Example: Composing nodes in C++ (simplified)
#include "rclcpp/rclcpp.hpp"
#include "my_package/my_camera_node.hpp" // Component
#include "my_package/my_processor_node.hpp" // Component
int main(int argc, char * argv[]) {
rclcpp::init(argc, argv);
rclcpp::executors::SingleThreadedExecutor exec; // Or MultiThreadedExecutor
auto camera_node = std::make_shared<my_package::MyCameraNode>();
auto processor_node = std::make_shared<my_package::MyProcessorNode>();
exec.add_node(camera_node);
exec.add_node(processor_node); // IPC if topics match
exec.spin();
rclcpp::shutdown();
return 0;
}
Choose the Right Executor: For complex applications with multiple nodes or long-running callbacks, use rclcpp::executors::MultiThreadedExecutor. For simple, single-purpose nodes, SingleThreadedExecutor is sufficient.
- ❌ BAD: Using
SingleThreadedExecutor for a node with many subscriptions or services that could block.
- ✅ GOOD:
MultiThreadedExecutor for concurrent callback processing.
// ✅ GOOD: MultiThreadedExecutor for responsive systems
rclcpp::executors::MultiThreadedExecutor exec(rclcpp::ExecutorOptions(), 4); // 4 threads
exec.add_node(my_complex_node);
exec.spin();
4. Common Pitfalls and Gotchas
Thread Safety Analysis (C++): Enable Clang's Thread Safety Analysis (-Wthread-safety) for multithreaded C++ code. Annotate mutex-protected data with RCPPUTILS_TSA_GUARDED_BY and functions with RCPPUTILS_TSA_REQUIRES. Use libcxx for std::mutex annotations.
- ❌ BAD: Unprotected shared data access, leading to data races and deadlocks.
- ✅ GOOD: Compiler-assisted detection of threading issues.
# CMakeLists.txt
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wthread-safety)
# add_compile_options(-Wthread-safety-negative) # For negative capability analysis
endif()
// ✅ GOOD: Thread-safe data access with annotations
#include <rcpputils/thread_safety_annotations.hpp>
#include <mutex>
class MyThreadSafeClass {
public:
void increment() RCPPUTILS_TSA_REQUIRES(mutex_) {
std::lock_guard<std::mutex> lock(mutex_);
data_ RCPPUTILS_TSA_GUARDED_BY(mutex_)++;
}
private:
mutable std::mutex mutex_;
int data_ RCPPUTILS_TSA_GUARDED_BY(mutex_) = 0;
};
5. Testing Approaches
Unit Tests: Every package must include unit tests. Use gtest for C++ and pytest for Python. Ensure high code coverage.
- Integrate tests into your
CMakeLists.txt using ament_add_gtest or ament_add_pytest.
- ❌ BAD: Untested code, relying solely on integration tests.
- ✅ GOOD: Small, focused unit tests for individual components.
# CMakeLists.txt for C++ gtest
if(BUILD_TESTING)
find_package(ament_cmake_gtest REQUIRED)
ament_add_gtest(my_cpp_test test/test_my_module.cpp)
target_link_libraries(my_cpp_test PRIVATE my_package_library)
endif()
Continuous Integration (CI): Implement CI pipelines (GitHub Actions, Azure Pipelines) to automatically build, lint, and test your code on every push/pull request. This is crucial for maintaining code quality and catching regressions.
- Ensure CI runs
colcon test --packages-select <your_package> --event-handlers console_direct+.
Documentation: Generate documentation (Doxygen for C++, Sphinx for Python) and keep it up-to-date. Clear documentation is vital for maintainability and onboarding.
- Integrate documentation generation into your build or CI process.
This comprehensive guide ensures your ROS 2 projects are built on a solid foundation of quality, performance, and maintainability. Adhere to these principles to contribute to a robust and reliable robotics ecosystem.
1---2name: ros3description: [Applies to: **/*] Definitive guidelines for writing high-quality, performant, and maintainable ROS 2 code, leveraging modern C++ and Python best practices, `ament` tooling, and efficient architectural patterns like node composition and multithreaded executors.4---56# ros Best Practices78This guide outlines the essential practices for developing robust, performant, and maintainable ROS 2 applications. Adherence to these rules ensures consistency, leverages ROS 2's advanced features, and aligns with the project's quality standards.910## 1. Code Quality and Static Analysis (The `ament` Way)1112* **Mandate `ament_lint_auto`**: Always integrate `ament_lint_auto` and `ament_lint_common` into your package build process. This is non-negotiable for catching style violations and common bugs early.13 * ❌ BAD: Relying on manual checks or pre-commit hooks that can be bypassed.14 * ✅ GOOD: Automatic enforcement during every build.1516 ```cmake17 # CMakeLists.txt18 # ...19 if(BUILD_TESTING)20 find_package(ament_lint_auto REQUIRED)21 ament_lint_auto_find_test_dependencies()22 endif()23 # ...24 ```2526 ```xml27 <!-- package.xml -->28 <package format="2">29 <!-- ... -->30 <test_depend>ament_lint_auto</test_depend>31 <test_depend>ament_lint_common</test_depend>32 <!-- ... -->33 </package>34 ```3536* **C++ Style Enforcement**: Use `ament_cpplint` and `ament_cppcheck`. Follow Google C++ Style Guide and modern C++17/20 features. Prioritize RAII and explicit smart pointer ownership.37 * ❌ BAD: Raw pointers for resource management; ignoring `cpplint` warnings.38 * ✅ GOOD: `std::unique_ptr`, `std::shared_ptr` for ownership.3940 ```cpp41 // ❌ BAD: Manual memory management, potential leak42 MyObject* obj = new MyObject();43 // ...44 delete obj; // Easy to forget or double-delete4546 // ✅ GOOD: RAII with smart pointers47 std::unique_ptr<MyObject> obj = std::make_unique<MyObject>();48 // Resource automatically managed49 ```5051* **Python Style Enforcement**: Adhere strictly to REP-8, which extends PEP 8. Use `black` for formatting and `flake8` for linting. Ensure proper naming, imports, and docstrings.52 * ❌ BAD: Inconsistent formatting, missing docstrings, `camelCase` for variables.53 * ✅ GOOD: `snake_case` for variables/functions, clear docstrings, `black`-formatted code.5455 ```python56 # ❌ BAD57 def calculateVelocity(pos1, pos2, time):58 # ...59 return vel6061 # ✅ GOOD62 def calculate_velocity(position1: float, position2: float, time_delta: float) -> float:63 """Calculates average velocity."""64 # ...65 return velocity66 ```6768* **Copyright and Licensing**: Use `ament_copyright` to ensure all source files have correct copyright and license headers.69 * Run `ament_copyright --add-missing "Your Name" apache2` to automate this.7071## 2. Code Organization and Structure7273* **Python Package Layout (Catkin)**: Adopt the recommended `src/<package_name>/__init__.py` structure. This ensures proper Python package discovery and avoids namespace collisions.74 * ❌ BAD: Scattering Python files directly in the package root or relying on `roslib.load_manifest`.75 * ✅ GOOD: Centralized, importable Python code.7677 ```78 my_package/79 ├── CMakeLists.txt80 ├── package.xml81 ├── setup.py82 └── src/83 └── my_package/84 ├── __init__.py85 └── my_module.py86 ```8788 ```python89 # setup.py for the above structure90 from distutils.core import setup91 from catkin_pkg.python_setup import generate_distutils_setup9293 d = generate_distutils_setup(94 packages=['my_package'],95 package_dir={'': 'src'},96 )97 setup(**d)98 ```99100* **Node/Script Installation**: Use `catkin_install_python` for ROS nodes and scripts. Install to `${CATKIN_PACKAGE_BIN_DESTINATION}` to make them accessible via `rosrun` without polluting the global `PATH`.101 * ❌ BAD: Installing scripts directly to `/usr/bin` via `setup.py` `scripts` argument.102 * ✅ GOOD: Package-isolated executables.103104 ```cmake105 # CMakeLists.txt106 # ...107 catkin_install_python(PROGRAMS108 nodes/my_node.py109 DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}110 )111 # ...112 ```113114## 3. Performance Considerations115116* **Embrace Node Composition**: Always use node composition for performance-critical applications, especially those with large messages (images, point clouds) or resource-constrained environments. This enables intra-process communication (IPC) for zero-copy data transfer.117 * ❌ BAD: Running every node in its own process, leading to high inter-process communication overhead.118 * ✅ GOOD: Grouping related nodes into a single composed process.119120 ```cpp121 // Example: Composing nodes in C++ (simplified)122 #include "rclcpp/rclcpp.hpp"123 #include "my_package/my_camera_node.hpp" // Component124 #include "my_package/my_processor_node.hpp" // Component125126 int main(int argc, char * argv[]) {127 rclcpp::init(argc, argv);128 rclcpp::executors::SingleThreadedExecutor exec; // Or MultiThreadedExecutor129130 auto camera_node = std::make_shared<my_package::MyCameraNode>();131 auto processor_node = std::make_shared<my_package::MyProcessorNode>();132133 exec.add_node(camera_node);134 exec.add_node(processor_node); // IPC if topics match135136 exec.spin();137 rclcpp::shutdown();138 return 0;139 }140 ```141142* **Choose the Right Executor**: For complex applications with multiple nodes or long-running callbacks, use `rclcpp::executors::MultiThreadedExecutor`. For simple, single-purpose nodes, `SingleThreadedExecutor` is sufficient.143 * ❌ BAD: Using `SingleThreadedExecutor` for a node with many subscriptions or services that could block.144 * ✅ GOOD: `MultiThreadedExecutor` for concurrent callback processing.145146 ```cpp147 // ✅ GOOD: MultiThreadedExecutor for responsive systems148 rclcpp::executors::MultiThreadedExecutor exec(rclcpp::ExecutorOptions(), 4); // 4 threads149 exec.add_node(my_complex_node);150 exec.spin();151 ```152153## 4. Common Pitfalls and Gotchas154155* **Thread Safety Analysis (C++)**: Enable Clang's Thread Safety Analysis (`-Wthread-safety`) for multithreaded C++ code. Annotate mutex-protected data with `RCPPUTILS_TSA_GUARDED_BY` and functions with `RCPPUTILS_TSA_REQUIRES`. Use `libcxx` for `std::mutex` annotations.156 * ❌ BAD: Unprotected shared data access, leading to data races and deadlocks.157 * ✅ GOOD: Compiler-assisted detection of threading issues.158159 ```cmake160 # CMakeLists.txt161 if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")162 add_compile_options(-Wthread-safety)163 # add_compile_options(-Wthread-safety-negative) # For negative capability analysis164 endif()165 ```166167 ```cpp168 // ✅ GOOD: Thread-safe data access with annotations169 #include <rcpputils/thread_safety_annotations.hpp>170 #include <mutex>171172 class MyThreadSafeClass {173 public:174 void increment() RCPPUTILS_TSA_REQUIRES(mutex_) {175 std::lock_guard<std::mutex> lock(mutex_);176 data_ RCPPUTILS_TSA_GUARDED_BY(mutex_)++;177 }178 private:179 mutable std::mutex mutex_;180 int data_ RCPPUTILS_TSA_GUARDED_BY(mutex_) = 0;181 };182 ```183184## 5. Testing Approaches185186* **Unit Tests**: Every package must include unit tests. Use `gtest` for C++ and `pytest` for Python. Ensure high code coverage.187 * Integrate tests into your `CMakeLists.txt` using `ament_add_gtest` or `ament_add_pytest`.188 * ❌ BAD: Untested code, relying solely on integration tests.189 * ✅ GOOD: Small, focused unit tests for individual components.190191 ```cmake192 # CMakeLists.txt for C++ gtest193 if(BUILD_TESTING)194 find_package(ament_cmake_gtest REQUIRED)195 ament_add_gtest(my_cpp_test test/test_my_module.cpp)196 target_link_libraries(my_cpp_test PRIVATE my_package_library)197 endif()198 ```199200* **Continuous Integration (CI)**: Implement CI pipelines (GitHub Actions, Azure Pipelines) to automatically build, lint, and test your code on every push/pull request. This is crucial for maintaining code quality and catching regressions.201 * Ensure CI runs `colcon test --packages-select <your_package> --event-handlers console_direct+`.202203* **Documentation**: Generate documentation (Doxygen for C++, Sphinx for Python) and keep it up-to-date. Clear documentation is vital for maintainability and onboarding.204 * Integrate documentation generation into your build or CI process.205206This comprehensive guide ensures your ROS 2 projects are built on a solid foundation of quality, performance, and maintainability. Adhere to these principles to contribute to a robust and reliable robotics ecosystem.