blob: 8661ad73634998d48bfd076607fbc353a314433d [file] [log] [blame] [view]
Erik Chen598410c2024-04-11 21:05:511These design principles make it easier to write, debug, and maintain code in //chrome/browser.
2
3## Caveats:
4* These are recommendations, not requirements.
5* These are not intended to be static. If you think a
6 principle doesn't make sense, reach out to //chrome/OWNERS.
7* These are intended to apply to new code and major refactors. We do not expect
8 existing features to be refactored, except as need arises.
9
10## Structure, modularity:
11* Features should be modular with no dependency cycles.
12 * This is a provisional design principle. We are currently investigating
13 feasibility. TODO: canonical example
14 * For most features, all business logic should live in some combination of
15 //chrome/browser/<feature>, //chrome/browser/ui/<feature> or
16 //component/<feature>.
17 * WebUI resources are the only exception. They will continue to live in
18 //chrome/browser/resources/<feature> alongside standalone BUILD.gn files.
19 * This directory should have a standalone BUILD.gn and OWNERs file.
20 * This directory may have its own namespace.
21 * This directory should have a public/ subdirectory to enforce further
22 encapsulation.
23 * The main reason for this is to guard against future, unexpected usage
24 of parts of the code that were intended to be private. This makes it
25 difficult to change implementation details in the future.
26 * The BUILD.gn should use public/sources separation.
27 * Corollary: There are several global functions that facilitate dependency
28 inversion. It will not be possible to call them from modularized features
29 (no dependency cycles), and their usage in non-modularized features is
30 considered a red flag:
31 * `chrome::FindBrowserWithTab` (and everything in browser_finder.h)
32 * `GetBrowserViewForNativeWindow` (via browser_view.h)
33 * `FindBrowserWindowWithWebContents` (via browser_window.h)
34
35* Features should have a core controller with precise lifetime semantics. The
36 core controller for most desktop features should be owned and instantiated by
37 one of the following classes:
38 * `TabFeatures` (member of `TabModel`)
39 * This class should own all tab-centric features. e.g. print preview,
40 lens overlay, compose, find-in-page, etc.
41 * If the feature requires instantiation of
42 `WebContents::SupportsUserData`, it should be done in this class.
43 * For desktop chrome, `TabHelpers::AttachTabHelpers` will become a
44 remove-only method. Clank/WebView may continue to use section 2 of
45 `TabHelpers::AttachTabHelpers` (Clank/WebView only).
46 * More complex features that also target mobile platforms or other
47 supported embedders (e.g. android webview) will continue to use the
48 layered components architecture.
49 * We defer to //components/OWNERS for expertise and feedback on the
50 architecture of these features, and encourage feature-owners to
51 proactively reach out to them.
52 * Lazy instantiation of `WebContents::SupportsUserData` is an
53 anti-pattern.
54 * `BrowserWindowFeatures` (member of `Browser`)
55 * example: omnibox, security chip, bookmarks bar, side panel
56 * `BrowserContextKeyedServiceFactory` (functionally a member of `Profile`)
Erik Chend5431602024-05-23 20:20:5857 * Override `ServiceIsCreatedWithBrowserContext` to return `true`. This
58 guarantees precise lifetime semantics.
59 * Lazy instantiation is an anti-pattern.
60 * Production code is started via `content::ContentMain()`. Test
61 harnesses use a test-suite dependent start-point, e.g.
62 `base::LaunchUnitTests`. Tests typically instantiate a subset of
63 the lazily-instantiated factories instantiated by production code,
64 at a different time, with a different order. This results in
65 different, sometimes broken behavior in tests. This is typically
66 papered over by modifying the production logic to include
67 otherwise unnecessary conditionals, typically early-exits.
68 Overriding `ServiceIsCreatedWithBrowserContext` guarantees
69 identical behavior between test and production code.
70 * Use `TestingProfile::Builder::AddTestingFactory` to stub or fake
71 services.
Erik Chen598410c2024-04-11 21:05:5172 * `GlobalFeatures` (member of `BrowserProcess`)
73 * The core controller should not be a `NoDestructor` singleton.
74* Global functions should not access non-global state.
75 * Pure functions do not access global state and are allowed. e.g. `base::UTF8ToWide()`
76 * Global functions that wrap global state are allowed, e.g.
77 `IsFooFeatureEnabled()` wraps the global variable
78 `BASE_FEATURE(kFooFeature,...)`
79 * Global functions that access non-global state are disallowed. e.g.
80 static methods on `BrowserList`.
Erik Chen08053b12024-05-25 01:05:4181* No distinction between `//chrome/browser/BUILD.gn` and
82 `//chrome/browser/ui/BUILD.gn`
83 * There is plenty of UI code outside of the `ui` subdirectory, and plenty of
84 non-UI code inside of the `ui` subdirectory. Currently the two BUILD files
85 allow circular includes. We will continue to treat these directories and
86 BUILD files as interchangeable.
Erik Chen598410c2024-04-11 21:05:5187
88## UI
89* Features should use WebUI and Views toolkit, which are x-platform.
90 * Usage of underlying primitives is discouraged (aura, Cocoa, gtk, win32,
91 etc.). This is usually a sign that either the feature is misusing the UI
92 toolkits, or that the UI toolkits are missing important functionality.
93* Features should use "MVC"
94 * Clear separation between controller (control flow), view (presentation of
95 UI) and model (storage of data).
96 * For simple features that do not require data persistence, we only require
97 separation of controller from view.
98 * TODO: work with UI/toolkit team to come up with appropriate examples.
Erik Chen08053b12024-05-25 01:05:4199* Views:
100 * For simple configuration changes, prefer to use existing setter methods
101 and builder syntax.
102 * Feel free to create custom view subclasses to encapsulate logic or
103 override methods where doing so helps implement layout as the composition
104 of smaller standard layouts, or similar. Don't try to jam the kitchen sink
105 into a single giant view.
106 * However, avoid subclassing existing concrete view subclasses, e.g. to add
107 or tweak existing behavior. This risks violating the Google style guidance
108 on multiple inheritance and makes maintenance challenging. In particular
109 do not do this with core controls, as the behaviors of common controls
110 should not vary across the product.
111* Avoid subclassing Widgets.
Erik Chen598410c2024-04-11 21:05:51112* Avoid self-owned objects/classes for views or controllers.
113
114## General
115* Code unrelated to building a web-browser should not live in //chrome.
116 * See [chromeos/code.md](chromeos/code.md) for details on ChromeOS (non-browser) code.
117 * We may move some modularized x-platform code into //components. The main
118 distinction is that ChromeOS can depend on //components, but not on
119 //chrome. This will be evaluated on a case-by-case basis.
120* Avoid nested message loops.
121* Threaded code should have DCHECKs asserting correct sequence.
122 * Provides documentation and correctness checks.
123 * See base/sequence_checker.h.
124* Most features should be gated by base::Feature, API keys and/or gn build
125 configuration, not C preprocessor conditionals e.g. `#if
126 BUILDFLAG(FEATURE_FOO)`.
127 * We ship a single product (Chrome) to multiple platforms. The purpose of
128 proprocessor conditionals is:
129 * (1) to allow platform-agnostic code to reference platform-specific
130 code.
131 * e.g. `#if BUILDFLAG(OS_WIN)`
132 * (2) to glue src-internal into public //chromium/src.
133 * e.g. `#if BUILDFLAG(GOOGLE_CHROME_BRANDING)`
134 * (3) To make behavior changes to non-production binaries
135 * e.g. `#if !defined(NDEBUG)`
136 * e.g. `#if defined(ADDRESS_SANITIZER)`
137 * (1) primarily serves as glue.
138 * (2) turns Chromium into Chrome. We want the two to be as similar as
139 possible. This preprocessor conditional should be used very sparingly.
140 Almost all our tests are run against Chromium, so any logic behind this
141 conditional will be mostly untested.
142 * (3) is a last resort. The point of DEBUG/ASAN/... builds is to provide
143 insight into problems that affect the production binaries we ship. By
144 changing the production logic to do something different, we are no longer
145 accomplishing this goal.
146 * In all cases, large segments of code should not be gated behind
147 preprocessor conditionals. Instead, they should be pulled into separate
148 files via gn.
149 * In the event that a feature does have large swathes of code in separate
150 build files/translation units (e.g. extensions), using a custom feature
151 flag (e.g. `BUILDFLAG(ENABLE_EXTENSIONS)`) to glue this into the main source
152 is allowed. The glue code should be kept to a minimum.
153* Avoid run-time channel checking.
154* Avoid test only conditionals
155 * This was historically common in unit_tests, because it was not possible to
156 stub out dependencies due to lack of a clear API surface. By requiring
157 modular features with clear API surfaces, it also becomes easy to perform
158 dependency injection for tests, thereby removing the need for conditionals
159 that can be nullptr in tests.
160 * In the event that they are necessary, document and enforce via
161 `CHECK_IS_TEST()`.
162* Avoid unreachable branches.
163 * We should have a semantic understanding of each path of control flow. How
164 is this reached? If we don't know, then we should not have a conditional.
165* For a given `base::Callback`, execution should either be always synchronous, or
166always asynchronous. Mixing the two means callers have to deal with two distinct
167control flows, which often leads to incorrect handling of one.
168Avoid the following:
169```cpp
170if (result.cached) {
171 RunCallbackSync())
172} else {
173 GetResultAndRunCallbackAsync()
174}
175```
176* Avoid re-entrancy. Control flow should remain as localized as possible.
177Bad (unnecessary delegation, re-entrancy)
178```cpp
179class CarSalesPerson : public Delegate {
180 // Can return nullptr, in which case no car is shown
181 std::unique_ptr<Car> ShowCar() {
182 return car_factory_->CreateCar();
183 }
184
185 // Delegate overrides:
186 // Whether the car should be shown, even if the factory is busy.
187 bool ShouldShowCarIfFactoryIsBusy() override;
188
189 CarFactory* car_factory_;
190};
191
192class CarFactory {
193 std::unique_ptr<Car> CreateCar() {
194 if (!CanCreateCar())
195 return nullptr;
196 if (FactoryIsBusy() && !delegate->ShouldShowCarIfFactoryIsBusy())
197 return nullptr;
198 return std::make_unique<Car>();
199 }
200
201 bool CanCreateCar();
202 bool FactoryIsBusy();
203
204 Delegate* delegate_;
205};
206```
207
208Good, version 1: Remove delegation. Pass all relevant state to CarFactory so that CreateCar() does not depend on non-local state.
209```cpp
210class CarSalesPerson {
211 // Can return nullptr, in which case no car is shown
212 std::unique_ptr<Car> ShowCar() {
213 return car_factory_->CreateCar(ShouldShowCarIfFactoryIsBusy());
214 }
215
216 // Whether the car should be shown, even if the factory is busy.
217 bool ShouldShowCarIfFactoryIsBusy();
218
219 CarFactory* car_factory_;
220};
221
222class CarFactory {
223 std::unique_ptr<Car> CreateCar(bool show_even_if_factory_is_busy) {
224 if (!CanCreateCar())
225 return nullptr;
226 if (FactoryIsBusy() && !show_even_if_factory_is_busy)
227 return nullptr;
228 return std::make_unique<Car>();
229 }
230 bool CanCreateCar();
231 bool FactoryIsBusy();
232};
233```
234
235Good, version 2: Remove delegation. CreateCar always create a car (fewer conditionals). State only flows from CarFactory to CarSalesPerson (and never backwards).
236```cpp
237class CarSalesPerson {
238 // Can return nullptr, in which case no car is shown
239 std::unique_ptr<Car> ShowCar() {
240 if (!car_factory_->CanCreateCar())
241 return nullptr;
242 if (car_factory_->FactoryIsBusy() && !ShouldShowCarIfFactoryIsBusy())
243 return nullptr;
244 return car_factory_->CreateCar();
245 }
246
247 // Whether the car should be shown, even if the factory is busy.
248 bool ShouldShowCarIfFactoryIsBusy();
249 CarFactory* car_factory_;
250};
251
252class CarFactory {
253 bool CanCreateCar();
254 bool FactoryIsBusy();
255 // never returns nullptr.
256 std::unique_ptr<Car> CreateCar();
257};
258```
259
260