File: blink-c%2B%2B.md

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (319 lines) | stat: -rw-r--r-- 7,814 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# Blink C++ Style Guide

This document is a list of differences from the overall
[Chromium Style Guide](c++.md), which is in turn a set of differences from the
[Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html). The
long-term goal is to make both Chromium and Blink style more similar to Google
style over time, so this document aims to highlight areas where Blink style
differs from Chromium style.

[TOC]

## Prefer WTF types over STL and base types

See [Blink readme](../../third_party/blink/renderer/README.md#Type-dependencies)
for more details on Blink directories and their type usage.

**Good:**
```c++
  String title;
  Vector<KURL> urls;
  HashMap<int, Deque<RefPtr<SecurityOrigin>>> origins;
```

**Bad:**
```c++
  std::string title;
  std::vector<GURL> urls;
  std::unordered_map<int, std::deque<url::Origin>> origins;
```

When interacting with WTF types, use `wtf_size_t` instead of `size_t`.

## Do not use `new` and `delete`

Chromium [recommends avoiding bare new/delete](c++-dos-and-donts.md#use-and-instead-of-bare);
Blink bans them.  In addition to the options there, Blink objects may be
allocated using `blink::MakeGarbageCollected` and manage their lifetimes using
strong Blink GC references, depending on the type. See
[How Blink Works](https://docs.google.com/document/d/1aitSOucL0VHZa9Z2vbRJSyAIsAz24kX8LFByQ5xQnUg/edit#heading=h.ekwf97my4bgf)
for more information.

## Don't mix Create() factory methods and public constructors in one class.

A class only can have either Create() factory functions or public constructors.
In case you want to call MakeGarbageCollected<> from a Create() method, a
PassKey pattern can be used. Note that the auto-generated binding classes keep
using Create() methods consistently.

**Good:**
```c++
class HistoryItem {
 public:
  HistoryItem();
  ~HistoryItem();
  ...
}

void DocumentLoader::SetHistoryItemStateForCommit() {
  history_item_ = MakeGarbageCollected<HistoryItem>();
  ...
}
```

**Good:**
```c++
class BodyStreamBuffer {
 public:
  using PassKey = base::PassKey<BodyStreamBuffer>;
  static BodyStreamBuffer* Create();

  BodyStreamBuffer(PassKey);
  ...
}

BodyStreamBuffer* BodyStreamBuffer::Create() {
  auto* buffer = MakeGarbageCollected<BodyStreamBuffer>(PassKey());
  buffer->Init();
  return buffer;
}

BodyStreamBuffer::BodyStreamBuffer(PassKey) {}
```

**Bad:**
```c++
class HistoryItem {
 public:
  // Create() and a public constructor should not be mixed.
  static HistoryItem* Create() { return MakeGarbageCollected<HistoryItem>(); }

  HistoryItem();
  ~HistoryItem();
  ...
}
```

## Naming

### Use `CamelCase` for all function names

All function names should use `CamelCase()`-style names, beginning with an
uppercase letter.

As an exception, method names for web-exposed bindings begin with a lowercase
letter to match JavaScript.

**Good:**
```c++
class Document {
 public:
  // Function names should begin with an uppercase letter.
  virtual void Shutdown();

  // However, web-exposed function names should begin with a lowercase letter.
  LocalDOMWindow* defaultView();

  // ...
};
```

**Bad:**
```c++
class Document {
 public:
  // Though this is a getter, all Blink function names must use camel case.
  LocalFrame* frame() const { return frame_; }

  // ...
};
```

### Precede boolean values with words like “is” and “did”

**Good:**
```c++
bool is_valid;
bool did_send_data;
```

**Bad:**
```c++
bool valid;
bool sent_data;
```

### Precede setters with the word “Set”; use bare words for getters
Precede setters with the word “set”. Prefer bare words for getters. Setter and
getter names should match the names of the variable being accessed/mutated.

If a getter’s name collides with a type name, prefix it with “Get”.

**Good:**
```c++
class FrameTree {
 public:
  // Prefer to use the bare word for getters.
  Frame* FirstChild() const { return first_child_; }
  Frame* LastChild() const { return last_child_; }

  // However, if the type name and function name would conflict, prefix the
  // function name with “Get”.
  Frame* GetFrame() const { return frame_; }

  // ...
};
```

**Bad:**
```c++
class FrameTree {
 public:
  // Should not be prefixed with “Get” since there's no naming conflict.
  Frame* GetFirstChild() const { return first_child_; }
  Frame* GetLastChild() const { return last_child_; }

  // ...
};
```

### Precede getters that return values via out-arguments with the word “Get”
**Good:**
```c++
class RootInlineBox {
 public:
  Node* GetLogicalStartBoxWithNode(InlineBox*&) const;
  // ...
}
```

**Bad:**
```c++
class RootInlineBox {
 public:
  Node* LogicalStartBoxWithNode(InlineBox*&) const;
  // ...
}
```

### May leave obvious parameter names out of function declarations
The
[Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html#Function_Declarations_and_Definitions)
allows omitting parameter names out when they are unused. In Blink, you may
leave obvious parameter names out of function declarations for historical
reasons. A good rule of thumb is if the parameter type name contains the
parameter name (without trailing numbers or pluralization), then the parameter
name isn’t needed.

**Good:**
```c++
class Node {
 public:
  Node(TreeScope* tree_scope, ConstructionType construction_type);
  // You may leave them out like:
  // Node(TreeScope*, ConstructionType);

  // The function name makes the meaning of the parameters clear.
  void SetActive(bool);
  void SetDragged(bool);
  void SetHovered(bool);

  // Parameters are not obvious.
  DispatchEventResult DispatchDOMActivateEvent(int detail,
                                               Event& underlying_event);
};
```

**Bad:**
```c++
class Node {
 public:
  // ...

  // Parameters are not obvious.
  DispatchEventResult DispatchDOMActivateEvent(int, Event&);
};
```

## Prefer enums or StrongAliases to bare bools for function parameters
Prefer enums to bools for function parameters if callers are likely to be
passing constants, since named constants are easier to read at the call site.
Alternatively, you can use `base::StrongAlias<Tag, bool>`. An exception to this
rule is a setter function, where the name of the function already makes clear
what the boolean is.

**Good:**
```c++
class FrameLoader {
public:
  enum class CloseType {
    kNotForReload,
    kForReload,
  };

  bool ShouldClose(CloseType) {
    if (type == CloseType::kForReload) {
      ...
    } else {
      DCHECK_EQ(type, CloseType::kNotForReload);
      ...
    }
  }
};

// An named enum value makes it clear what the parameter is for.
if (frame_->Loader().ShouldClose(FrameLoader::CloseType::kNotForReload)) {
  // No need to use enums for boolean setters, since the meaning is clear.
  frame_->SetIsClosing(true);

  // ...
```

**Good:**
```c++
class FrameLoader {
public:
  using ForReload = base::StrongAlias<class ForReloadTag, bool>;

  bool ShouldClose(ForReload) {
    // A StrongAlias<_, bool> can be tested like a bool.
    if (for_reload) {
      ...
    } else {
      ...
    }
  }
};

// Using a StrongAlias makes it clear what the parameter is for.
if (frame_->Loader().ShouldClose(FrameLoader::ForReload(false))) {
  // No need to use enums for boolean setters, since the meaning is clear.
  frame_->SetIsClosing(true);

  // ...
```

**Bad:**
```c++
class FrameLoader {
public:
  bool ShouldClose(bool for_reload) {
    if (for_reload) {
      ...
    } else {
      ...
    }
  }
};

// Not obvious what false means here.
if (frame_->Loader().ShouldClose(false)) {
  frame_->SetIsClosing(ClosingState::kTrue);

  // ...
```

### Use `README.md` to document high-level components

Documentation for a related-set of classes and how they interact should be done
with a `README.md` file in the root directory of a component.