blob: cf6d73a85555d3740b1be0f2d20be0caef33af00 [file] [log] [blame] [view]
Artem Titova6178672023-01-30 10:51:011<!-- go/cmark -->
2<!--* freshness: {owner: 'hta' reviewed: '2021-01-01'} *-->
3
Karl Wibergab566702019-01-31 01:34:394# How to write code in the `api/` directory
5
Artem Titova6178672023-01-30 10:51:016Mostly, just follow the regular [style guide](/g3doc/style-guide.md), but:
Karl Wibergab566702019-01-31 01:34:397
8* Note that `api/` code is not exempt from the “`.h` and `.cc` files come in
9 pairs” rule, so if you declare something in `api/path/to/foo.h`, it should be
10 defined in `api/path/to/foo.cc`.
11* Headers in `api/` should, if possible, not `#include` headers outside `api/`.
12 It’s not always possible to avoid this, but be aware that it adds to a small
13 mountain of technical debt that we’re trying to shrink.
14* `.cc` files in `api/`, on the other hand, are free to `#include` headers
15 outside `api/`.
Danil Chapovalov541756f2023-09-07 10:29:4316* Avoid structs in api, prefer classes.
Karl Wibergab566702019-01-31 01:34:3917
Danil Chapovalov541756f2023-09-07 10:29:4318The preferred way for `api/` code to access non-`api/` code is to call
Karl Wibergab566702019-01-31 01:34:3919it from a `.cc` file, so that users of our API headers won’t transitively
20`#include` non-public headers.
21
22For headers in `api/` that need to refer to non-public types, forward
23declarations are often a lesser evil than including non-public header files. The
Artem Titova6178672023-01-30 10:51:0124usual [rules](/g3doc/style-guide.md#forward-declarations) still apply, though.
Karl Wibergab566702019-01-31 01:34:3925
26`.cc` files in `api/` should preferably be kept reasonably small. If a
27substantial implementation is needed, consider putting it with our non-public
28code, and just call it from the `api/` `.cc` file.
Danil Chapovalov541756f2023-09-07 10:29:4329
30Avoid defining api with structs as it makes harder for the api to evolve.
31Your struct may gain invariant, or change how it represents data.
32Evolving struct from the api is particular challenging as it is designed to be
33used in other code bases and thus needs to be updated independetly from its usage.
34Class with accessors and setters makes such migration safer.
35See [Google C++ style guide](https://google.github.io/styleguide/cppguide.html#Structs_vs._Classes) for more.
36
37If you need to evolve existent struct in api, prefer first to convert it into a class.