• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# OpenHarmony API Design Specifications
2
3**Change History**
4
5| Version          | Prepared By               | Release Date      | Description  |
6| -------------- | ------------------- | ---------- | ---------- |
7| v0.1| OpenHarmony API SIG | November 2022| Trial version.|
8
9## Purpose
10
11An API is a definition provided by a software implementer for developers on the programming UI to reflect the capability scope of a software entity.
12
13The quality of APIs greatly affects developer experience.
14
15To deliver a sound developer experience and promote the healthy development of the OpenHarmony ecosystem, the API SIG formulates the OpenHarmony API design specifications.
16
17## Scope
18
19OpenHarmony APIs are classified into public APIs (open to third-party applications) and system APIs (available only for system applications).
20
21The design specifications are effective for both types of APIs, regardless of the programming language in use.
22
23For details about the API classification, see [OpenHarmony API Governance Charter](OpenHarmony-API-governance.md).
24
25## API Design Objectives
26
27A good API design must meet the following requirements:
28
29* Operational: An API must be able to implement the capability it claims to offer. This is the fundamental requirement.
30* Expressive: By calling an API, the caller can clearly express what they want to do.
31* Simple: An API must be easy to learn and use, and not prone to errors.
32* Predictable: An API must always complete its mission according to the definition. If the definition does not contain errors or exceptions, no error or exception should occur regardless of how many times the API is called. If an error or a failure may occur, describe the error or failure in the definition and return the corresponding error at the correct time.
33
34You must understand the following when designing APIs:
35
36* The stability and consistency of APIs take precedence over the API quantity.
37* A better API name is the one that is easy to understand, not a shorter one.
38* APIs should be encapsulated to prevent too much information from being exposed.
39
40From the perspective of developers, a well-designed API has different features in different phrases.
41
42* In the learning phase
43  * Easy to understand
44  * Easy to use
45* In the development phase
46  * Expressive
47  * Simple
48  * Predictable
49* In the maintenance phase
50  * Stable
51  * Easy to maintain
52
53## API Design Overview
54
55To make the rules as universal as possible, the specifications do not involve programming language differences or coding specifications. You need to comply with the corresponding requirements for them.
56
57This document provides pre-release review specifications and post-release evaluation specifications.
58
59* The pre-release review specifications are the basic requirements for APIs. Any API must meet these requirements before passing the release review.
60* The post-release evaluation specifications require the API providers to keep an eye on the APIs after they are published. Even though an API has met all the pre-release review specifications, it may not be perfect. On-time review after the release helps further improve the API quality.
61
62The following lists all the rules that you should comply with during API design. The list is provided for quick indexing, and the detailed description is provided in the following sections.
63
64Every OpenHarmony API provider should be familiar with these rules.
65
66### Pre-release Review Specifications
67
68* Usability
69  * Rule 1: Coding rules compliant
70  * Rule 2: Grammatically correct
71  * Rule 3: Proper use of abbreviations
72  * Rule 4: Accurate use of words in pairs
73  * Rule 5: Accurate use of design or architecture patterns
74  * Rule 6: No controversial names
75  * Rule 7: Appropriate parameter types
76  * Rule 8: Appropriate parameter quantity
77  * Rule 9: Appropriate parameter sequence
78  * Rule 10: Complete return value definition
79  * Rule 11: Appropriate exception definition
80  * Rule 12: Positive expressions
81  * Rule 13: Reducing the possibility of errors
82  * Rule 14: No sequential coupling
83  * Rule 15: Accurate logic expression
84  * Rule 16: Encapsulation welcomed
85  * Rule 17: Single responsibility
86* Availability
87  * Rule 18: Reliability
88  * Rule 19: Complete functionalities
89  * Rule 20: Permission and privacy protection
90  * Rule 21: Concurrent environment
91  * Rule 22: Resource management closure
92  * Rule 23: Retry logic
93  * Rule 24: Idempotence requirements
94  * Rule 25: Device universality
95* Consistency
96  * Rule 26: Consistent terms and concepts
97  * Rule 27: Consistent inter-device behavior
98  * Rule 28: Consistent version evolution
99  * Rule 29: Consistent naming style
100  * Rule 30: Consistent parameter sequence
101  * Rule 31: Consistent synchronous/asynchronous style
102* Compatibility
103  * Rule 32: Version compatibility
104  * Rule 33: Backward binary-code compatibility
105* API references
106  * Rule 34: Basic descriptions for modules, namespaces, classes, and functions
107  * Rule 35: Clear description of use cases
108  * Rule 36: Accurate API description
109  * Rule 37: Accurate parameter description
110  * Rule 38: Accurate return value/exception description
111  * Rule 39: Complete meta information
112  * Rule 40: Consistent style
113* Organization mode
114  * Rule 41: Reasonable layering
115  * Rule 42: Proper module division
116  * Rule 43: API reference document available (as part of the API)
117* Quality related
118  * Rule 44: Performance requirements met
119  * Rule 45: Proper power consumption
120  * Rule 46: Testable
121  * Rule 47: Environmentally adaptable
122
123### Post-release Evaluation Specifications
124
125* Stability
126  * Rule 48: Minimized rate for deprecated or changed APIs
127* Security
128  * Rule 49: No abuse of APIs
129  * Rule 50: No exploitation of APIs
130* Maintainability
131  * Rule 51: Evolution support
132  * Rule 52: Consistent behavior after feature expansion
133  * Rule 53: Documents updated accordingly
134* Irreplaceability
135  * Rule 54: Orthogonal design
136* Feedback from developers
137  * Rule 55: Developer feedback noticed
138
139## Description of Pre-release Review Specifications
140
141### Usability
142
143Usability should be considered in any design. During the design of OpenHarmony APIs, consider usability from the following aspects:
144
145#### Naming
146
147* **Rule 1: Coding rules compliant**
148
149The definition of an API must comply with the coding rules of the project to which the API belongs, for example, the rules for uppercase and lowercase letters, underscores (_), hyphens (-), and prefixes.
150
151You can refer to the following coding rules for the OpenHarmony project:
152
153* [JavaScript Coding Style Guide](../contribute/OpenHarmony-JavaScript-coding-style-guide.md)
154* [C Coding Style Guide](../contribute/OpenHarmony-c-coding-style-guide.md)
155* [C++ Coding Style Guide](../contribute/OpenHarmony-cpp-coding-style-guide.md)
156* [C&C++ Secure Coding Guide](../contribute/OpenHarmony-c-cpp-secure-coding-guide.md)
157* [HDF Driver Coding Guide](../contribute/OpenHarmony-hdf-coding-guide.md)
158* **Rule 2: Grammatically correct**
159
160API names must be in English. Generally, a class is named using a noun, for example, **exampleManager**, **exampleService**, and **exampleAnimation**. A function is named using a verb or verb-object structure, for example, **start()**, **createUser()**, and **startBoot()**.
161
162It is incorrect to name a class **Start** or a function **ball()**.
163
164In terms of verbs, use transitive verbs, transitive verbs, and verb tenses correctly. For example, you can name events **transferStarted()** and **renderDone()**.
165
166* **Rule 3: Proper use of abbreviations**
167
168Avoid abbreviations as much as possible, as abbreviations are difficult to understand or even cause misunderstanding.
169
170Use only abbreviations that are well known. Do not make your own abbreviations.
171
172* **Rule 4: Accurate use of words in pairs**
173
174Many words can be used to express the same meaning. The table below lists some examples.
175
176| Word | Synonym                                            |
177| ----- | -------------------------------------------------- |
178| send  | deliver, dispatch, announce, distribute, route     |
179| find  | search, extract, locate, recover                   |
180| start | launch, create, begin, open                        |
181| make  | create, set up, build, generate, compose, add, new |
182
183When naming APIs, try to use words in pairs, rather than any synonym.
184
185For example, if **add** is used for an API name, **remove** is a better option than **destroy** for its counterpart; if **increase** is used, **decrease** is a better option that **reduce**.
186
187The table below lists common words in pairs that can be used in API names.
188
189| Word    | Counterpart    |
190| -------- | -------- |
191| add      | remove   |
192| increase | decrease |
193| open     | close    |
194| begin    | end      |
195| insert   | delete   |
196| show     | hide     |
197| create   | destroy  |
198| lock     | unlock   |
199| source   | target   |
200| first    | last     |
201| min      | max      |
202| start    | stop     |
203| get      | set      |
204| next     | previous |
205| up       | down     |
206| new      | old      |
207
208* **Rule 5: Accurate use of design or architecture patterns**
209
210The design or architecture pattern is actually the jargon of the software industry. Use them correctly to avoid misunderstanding.
211
212If your API contains words such as **Strategy**, **Builder**, **Factory**, and **Singleton**, make sure you understand these design patterns accurately and use them correctly.
213
214When your API uses a specific pattern, use the terms defined in that pattern. Do not change the world class or sequence.
215
216* **Rule 6: No controversial names**
217
218Do not use controversial names, including but not limited to any words that violate the laws and regulations, cause religious disputes, or lead to racial discrimination, as well as dirty words.
219
220Considering that OpenHarmony is designed to empower a variety of industries, you need to pay more attention when deciding whether a name is controversial.
221
222#### Parameters
223
224* **Rule 7: Appropriate parameter types**
225
226Typically, it is better to use class type parameters than simple type parameters.
227
228For example, the following APIs seem to be fine at first glance:
229
230* `addPerson(string id, string name, int age)`
231* `removePerson(string id, string name, int age)`
232* `modifyPerson(string id, string name, int age)`
233
234However, they are not friendly for expansion. If you define the parameters using the class type **Person**, it would be easy to add new parameters. What's more, you do not need to make any changes to the APIs.
235
236Class type parameters reduce the parameter quantity in an API, thereby making the API easy to be remembered.
237
238* **Rule 8: Appropriate parameter quantity**
239
240Use 7 or less parameters in an API. In most cases, use 3 to 5 parameters in an API, for easy of use.
241
242The number of parameters in an API should not exceed 10 in any case. If an API contains more than 10 parameters, the possible cause is that the type is not well encapsulated or the API implementation logic is too complex. If this is the case, consider to use another form.
243
244* **Rule 9: Appropriate parameter sequence**
245
246In some programming languages, parameters in an API are often organized in the order of input parameters followed by output parameters.
247
248If you further sort the parameters based on their logical relationship and importance, it is easier for developers to memorize and use the parameters.
249
250You should place optional parameters after mandatory parameters, and place callback functions at the end. For example, in the **fs.readFile** API, the **path** parameter is mandatory, and **encoding** and **flag** have default values.
251
252```js
253fs.readFile(path[, options], callback)
254```
255
256```js
257fs.readFile('/etc/passwd', (err, data) => {
258  if (err) throw err;
259  console.log(data);
260});
261
262fs.readFile('/etc/passwd', {
263    encoding: 'utf-8',
264    flag: 'r+'
265}, (err, data) => {
266  if (err) throw err;
267  console.log(data);
268});
269```
270
271#### Return Values
272
273* **Rule 10: Complete return value definition**
274
275The definition of return values must be complete. This means that you need to consider exceptions in addition to normal situations so developers will be able to handle the exceptions.
276
277Example:
278
279* For a return value of the number type, define the value range and the situation in which an extreme value occurs.
280* For a return value of the Boolean type, define when **true** and **false** will be returned.
281* For a return value of the array or set type, define when **null** or an empty set will be returned.
282* For a return value of the enum type, define when each enumerated value will be returned.
283* **Rule 11: Appropriate exception definition**
284
285An exception is returned when, for example, an input parameter is invalid or the API implementation logic is incorrect.
286
287For the same module or service, there should be a unified definition for the situations in which an error value will be returned and an exception will be thrown.
288
289In addition, the same exception type should be used for the same exception.
290
291Consistency greatly reduces the difficulty in using the API and the probability of errors.
292
293#### Others
294
295You are advised to adhere to the following rules to make your APIs easy to use.
296
297* **Rule 12: Positive expressions**
298
299Positive expressions enable developers to think less.
300
301When naming APIs, use positive words instead of negative ones.
302
303The following is a counter example:
304
305```js
306if (!isNotAccessible() || !isNotWritable() || !isNotPrintable())
307```
308
309The following is recommended:
310
311```js
312if (isAccessible() && isWritable() && isPrintable())
313```
314
315* **Rule 13: Reducing the possibility of errors**
316
317Most API use errors are caused by parameter passing errors.
318
319For example, for the following function, both the second and third parameters are Boolean values. When calling the function, developers may find it difficult to remember the parameter values correctly.
320
321```js
322declare function findString(text: string, isForward: boolean, isCaseSensitive: boolean): string;
323```
324
325You can define enums to reduce the difficulty.
326
327```js
328enum SearchDirection {
329    FORWARD,
330    BACKWARD
331};
332
333enum CaseSensitivity {
334    SENSITIVE,
335    INSENSITIVE
336};
337
338declare function findString(text: string, direction: SearchDirection, sensitivity: CaseSensitivity): string;
339```
340
341The use of enums instead of Boolean values and integers helps reduce the possibility of API use errors.
342
343Combining multiple parameters into a type also reduces the possibility of parameter passing errors.
344
345* **Rule 14: No sequential coupling**
346
347Ensure high cohesion and low coupling during software design, especially for large projects.
348
349Coupling indicates the dependency between software modules. A too deep coupling often means a poor architecture design.
350
351According to the static software structure or hierarchical architecture diagram, if there are few dependencies between modules but obvious API calling directions between upper and lower layers, it is a good design. On the contrary, if there are complex inter-module dependencies or call chains with opposite directions between the upper and lower layers, the structure is poor.
352
353Among all the types of coupling, sequential coupling must be noted for APIs. Sequential coupling means that the APIs in a class must be called in a specific sequence in order to work properly.
354
355The following is an example of sequential coupling:
356
357```js
358doSomethingFirst()
359doSomethingSecond()
360doSomethingThird()
361```
362
363Sequential coupling poses high requirements on the callers and is prone to incorrect use.
364
365To avoid sequential coupling, you can use the **template method** design pattern.
366
367* **Rule 15: Accurate logic expression**
368
369Some APIs, for example, **getUserAccount()**, are used to query information, whereas others, for example, **createUserAccount()**, are used to modify data.
370
371Never use an API that seems to be used for query to carry out data modification. It will confuse developers.
372
373The name of an API should express everything it does, with no concealing. Only in this way can it be easier for developers to understand what the API does when reading the code.
374
375If an API implements too many features and cannot be named in a few words, it usually means that you should split the API into multiple APIs, to make it cohesive enough.
376
377Do not assume that developers have the same background information as you do.
378
379For example, you may name a field **language** and believe all the readers know that you are talking about the programming language. In fact, someone might wonder whether you are talking about the language of speech. Name it **programmingLanuage** will eliminate the misunderstanding.
380
381However, do not go to another extreme. If the class name or namespace name contains a prefix, do not repeat it in the function.
382
383* **Rule 16: Encapsulation welcomed**
384
385Encapsulation is a key concept in object-oriented programming.
386
387Encapsulation means that system capabilities should be encapsulated as simple APIs, with implementation details hidden as much as possible.
388
389It is like an iceberg. No matter how large the portion submerged in water is, the visible portion above water should be small enough and concise enough. This is a user-friendly interface.
390
391Encapsulation makes it easy for developers to use, while making fewer errors. For example, an electronic engineer connects all the electric wires in the room and leaves only one button to users. This is a good encapsulation. It prevents users from the need to understand the complex circuit structure and protect them from electric shocks.
392
393* **Rule 17: Single responsibility**
394
395An API should try to do only one thing (a single core responsibility) as much as possible. Example:
396
397```js
398// Not recommended
399view.fetchDataAndRender(url, templete);
400
401// Recommended
402let data = view.dataManager.fetchData(url);
403view.render(data, templete);
404```
405
406Single responsibility enables developers to use APIs in the minimum unit as required. It also enables developers to encapsulate the service logic based on their service requirements.
407
408In some cases, the rule "single responsibility" may conflict with "encapsulation welcomed". For example, if there are many APIs with a single capability, developers have to notice the calling details for each API.
409
410If this is the case, determine the level of the capability provided by your API based on the encapsulation level. To provide the capability for a high-level caller, you can encapsulate the APIs. To provide the capability for a low-level caller, you can provide separate APIs.
411
412### Availability
413
414* **Rule 18: Reliability**
415
416The APIs provided by the operating system must be fully reliable.
417
418Reliability does not mean that every call has to be successful. If resources are used up, providing a proper return value or exception is also an implementation of reliability.
419
420For every API, all the possible situations must be accurately defined, and the work should be completed according to the defined behavior in the corresponding situation.
421
422Unreliable behavior includes failure to return a value as scheduled or causing application exceptions for no reason.
423
424* **Rule 19: Complete functionalities**
425
426When planning a feature or capability, consider the completeness of functionalities. For example, a process should not be interrupted or an option should not be missing within the supported scope. This requires you to perform sufficient verification and deduction when designing the APIs.
427
428Even if the comprehensive features of an operating system are gradually provided through a series of iterations across years, every specific version should provide closed and self-consistent capabilities. To achieve this goal, you must define clear boundaries for each iteration.
429
430* **Rule 20: Permission and privacy protection**
431
432Permission control and data protection must be provided for any API that involves user data or user privacy.
433
434Comply with the following principles for permission control:
435
4361. Completeness: All behaviors across application sandboxes must be limited by permission control.
4372. Optimal granularity: One permission protects only one type of object. Developers only need to apply for the permission of the minimum granularity to access an API.
4383. Clearness: The protected object, permission scope, and sensitivity level must be clearly specified in the permission definition.
4394. Minimum scope: A permission is assigned only to applications that have service requirements.
440
441Comply with the following principles for privacy protection:
442
4431. The return value should contain only necessary information.
4442. The API calling should not obtain or collect users' personal data, unless required permissions are assigned by users.
4453. In case that an API is called by multiple applications, if personal data needs to be disclosed to the callee, the caller must specify the disclosed data type, data receiver, and data use purpose in the privacy statement.
4464. When an API needs to access sensitive user data (such as calls, contacts, and media content), the system picker mechanism must be used to prevent the API from accessing the data through sensitive permission application.
4475. Open APIs should not contain unrelated features.
448
449* **Rule 21: Concurrent environment**
450
451The OpenHarmony APIs do not require all threads to be safe, considering the extremely high cost (for example, program complexity and performance impact). You only need to select the APIs as required.
452
453APIs dedicated for concurrent environments must be properly designed and described.
454
455In the internal implementation of an API, thread safety issues should be solved as much as possible.
456
457* **Rule 22: Resource management closure**
458
459If an API requests dynamic resources, resource release should also be considered.
460
461If the requested resources are returned to the caller, an API must be provided for the caller to release the resources.
462
463If the requested resources are not directly returned to the caller, consider the resource lifecycle and release timing in the API.
464
465If there is an upper limit for resource usage, describe it clearly and provide an API to check whether the upper limit is reached.
466
467Pay special attention to the time for releasing exclusive resources.
468
469* **Rule 23: Retry logic**
470
471For APIs that may encounter calling failures, provide a retry mechanism. For example, for the scenario in which a process cannot obtain an exclusive resource (such as camera) that is already occupied by another, provide an API to query whether the resource is available.
472
473To prevent repeated attempts, you can provide a listener.
474
475Specify the maximum number of retries allowed after the API call failure.
476
477* **Rule 24: Idempotence requirements**
478
479In mathematics, the idempotent function expression is **f(x) = f(f(x))**. For example, the function for calculating the absolute value, that is, **abs(x) = abs(abs(x))**, is idempotent.
480
481In computer science, idempotence indicates that one or more requests for a resource should have the same effect.
482
483From the perspective of APIs, the effect of calling the API once to open a file should be the same as the effect of calling the API multiple times to open the file. Similarly, the effect of calling the API once to close a file should be the same as the effect of calling the API multiple times to close the file.
484
485* **Rule 25: Device universality**
486
487OpenHarmony is designed for various types of devices.
488
489The API design should meet the device universality requirements. Example:
490
491* For UI components, consider the size of different screens.
492* For data storage, consider the size of different storage devices.
493* For user input events, consider different user interaction modes, such as touches, voice, and keys.
494
495Certain APIs are available only for specific devices. Example:
496
497* Health sensor APIs are available only for wearables.
498* Vehicle control APIs are available only for telematics devices.
499
500You can calibrate the API application scenarios by referring to [SysCap](../application-dev/quick-start/syscap.md).
501
502### Consistency
503
504* **Rule 26: Consistent terms and concepts**
505
506For purposes of easy understanding, use consistent terms and concepts in API names and descriptions. Avoid jargon. Abstract scenario-specific service models to form coherent and consistent OpenHarmony concepts.
507
508In this regard, observe the following principles:
509
5101. Use a single term for each concept.
5112. Terms should be appropriate, explainable, and easy to understand.
5124. The definition of terms should be accurate and unambiguous.
5135. Common terms in the industry should not be redefined and should be used by following the industry practices.
514
515In general, use terms already defined in [OpenHarmony Glossary](../glossary.md). If necessary, you can add terms to the glossary.
516
517* **Rule 27: Consistent inter-device behavior**
518
519By default, an API should behavior the same between devices of different types.
520
521If the behavior will be different because of the device types, clearly describe the differences and provide a check mechanism.
522
523* **Rule 28: Consistent version evolution**
524
525By default, every API should provide consistent behavior in different versions. If an API change will cause behavior incompatibility, the minimum requirement is to distinguish the target version of the applications.
526
527Simply speaking, API behavior changes should not affect developed applications.
528
529* **Rule 29: Consistent naming style**
530
531Accurate API names do not always mean consistency. For example, words with similar meanings, such as **picture** and **image**, and **path** and **URL**, are often seen in the same set of APIs. You should use the same name when referring to the same object.
532
533For example, the following APIs, which are used to obtain media assets, have different naming styles:
534
535```js
536declare function getMediaAsserts(): Array<MediaAssert>;
537declare function getAudios(): Array<AudioAssert>;
538declare function getVideos(): Array<VideoAssert>;
539declare function getImages(): Array<ImageAssert>;
540```
541
542They should be named as follows:
543
544```js
545function getMediaAsserts(): Array<MediaAssert>;
546function getAudioAsserts(): Array<AudioAssert>;
547function getVideoAsserts(): Array<VideoAssert>;
548function getImageAsserts(): Array<ImageAssert>;
549```
550
551* **Rule 30: Consistent parameter sequence**
552
553The same parameter sequence should be used for APIs in the same namespace or module.
554
555For example, there is no restriction on the sequence of **deviceId** and **missionId** in a single API, but their sequence in the APIs of a module must be the same.
556
557```js
558function getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>;
559function getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnapshot>;
560
561// Correct
562function getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnapshot>;
563
564// Incorrect
565function getLowResolutionMissionSnapShot(missionId: number, deviceId: string): Promise<MissionSnapshot>;
566```
567
568* **Rule 31: Consistent synchronous/asynchronous style**
569
570Asynchronous APIs should be able to be determined based on input parameters and return values. They should use the same style. Example:
571
572```javascript
573// Callback mode
574function getDefaultDisplay(callback: AsyncCallback<Display>): void;
575// Promise mode
576function getDefaultDisplay(): Promise<Display>;
577```
578
579If both synchronous and asynchronous APIs are provided, you can add the suffix **Sync** to the synchronization API name for better distinguishing. Example:
580
581```js
582function getDefaultDisplaySync(): Display;
583```
584
585If only the synchronization API is provided and the return value is not **void**, you do not need to add the suffix. Example:
586
587```js
588function registerMissionListener(listener: MissionListener): number;
589```
590
591### Compatibility
592
593* **Rule 32: Version compatibility**
594
595Carry out full planning and all-round consideration at the very beginning, since API changes pose a high cost. However, you must notice that API changes are inevitable during system development.
596
597API changes must be backward compatible. After an API is deprecated, mark the API **deprecated** in the source code and reference document, and provide the new counterpart.
598
599Retain the deprecated APIs in at least five API versions released since the deprecation. After five versions, you can delete the deprecated APIs after providing obvious notifications to developers and leaving sufficient time for them to modify the applications.
600
601* **Rule 33: Backward binary-code compatibility**
602
603Binary-code compatibility means that an existing program can be linked to and run properly without recompilation after version evolution. It ensures that the memory layout of an instance does not change in the case of a version update.
604
605Common C++ API changes that cause binary-code incompatibility include:
606
6071. Deleting any API elements
6082. Adding a virtual function
6093. Changing the inheritance of a class
6104. Changing the declaration sequence of virtual functions
6115. Adding a non-static member variable
6126. Changing the declaration sequence of non-static member variables
613
614In terms of binary-code compatibility, C APIs have inherent advantages over C++ APIs. Therefore, you are advised to define native APIs using C.
615
616### API References
617
618API references are used to carry API information. Their quality is vital for the ecosystem development.
619
620* **Rule 34: Basic descriptions for modules, namespaces, classes, and functions**
621
622A basic description must be provided for each module, namespace, class, and function.
623
624A detailed description must be provided for key modules and complex modules.
625
626The description should be in English.
627
628* **Rule 35: Clear description of use cases**
629
630Sample code must be provided for all APIs, and common application scenarios must be covered.
631
632A detailed application scenario description should be provided for complex APIs. You can provide a link to the tutorial that exhibits how to use the API.
633
634* **Rule 36: Accurate API description**
635
636There should be no typos in the API description.
637
638All code samples must be able to run properly. If the behavior of an API varies in different versions, describe the differences.
639
640Mark deprecated APIs and provide the counterparts.
641
642* **Rule 37: Accurate parameter description**
643
644Each parameter in an API must be clearly described. Example:
645
646* For a non-simple type, specify whether the parameter can be null.
647* For an enum type, describe the use case of each enumerated value.
648* For an optional parameter, specify when the caller needs to pass the parameter and when to ignore the parameter.
649
650**Rule 38: Accurate return value/exception description**
651
652If an API has a return value or an exception, describe them in the API reference. Example:
653
654```js
655/**
656 * Sync function of rename.
657 * @param {string} path - path.
658 * @returns {void} rmdir success.
659 * @throws {BusinessError} 401 - if type of path is not string.
660 * @throws {BusinessError} 201 - if permission denied.
661 * @syscap SystemCapability.FileManagement.File.FileIO
662 * @since 7
663 */
664declare function rmdirSync(path: string): void;
665```
666
667* **Rule 39: Complete meta information**
668
669The API reference must contain basic meta information, such as **@syscap** and **@since**.
670
671The meta information describes the basic information about an API. The tool and SDK will use the information to perform corresponding processing, for example, displaying a message for a deprecated API.
672
673* **Rule 40: Consistent style**
674
675The API reference document must use consistent style, for example, bold text and image colors.
676
677### Organization Mode
678
679* **Rule 41: Reasonable layering**
680
681An operating system is usually structured in a hierarchical model, and each layer solves different levels of problems.
682
683You need to consider layering during API design.
684
685For example, in the construction industry, all buildings have walls and doors, the walls are made of bricks, and the doors are made of wood. There are abstract layers as follows:
686
687* The first layer is raw materials, including cement, sand, and wood.
688* The second layer is building elements constructed from raw materials. Examples of building elements are doors, windows, and walls.
689* The third floor is the type of room, for example, bedroom, bathroom, and living room.
690* The top floor is a variety of buildings for different purposes, such as hotels and apartments.
691
692Each layer has its own concepts to consider and problems to solve. Think carefully about the layer that your API targets.
693
694* **Rule 42: Proper module division**
695
696In addition to horizontal layering, you should pay attention to vertical layering, that is, module division. OpenHarmony APIs are organized in the form of namespaces. A namespace usually corresponds to a module.
697
698A smaller subsystem can provide only one namespace and have all the APIs in this namespace. A large subsystem can provide multiple namespaces.
699
700* **Rule 43: API reference document available (as part of the API)**
701
702When talking about the APIs provided for developers, we mean not only programming interfaces, but also anything that can be exposed.
703
704The API reference document is one that exposed. It should be managed according to the same rules as the APIs.
705
706### Quality Related
707
708* **Rule 44: Performance requirements met**
709
710The APIs provided by an operating system may be used by all upper-layer applications. They must meet performance requirements in practice.
711
712The following lists some requirements:
713
7141. Respond in a timely manner to avoid callers waiting. If an API call takes a long time, use an asynchronous API.
7152. Use the shared memory and message queue when a large amount of data needs to be transmitted.
7163. Minimize the number of new process entities.
7174. Release resources in a timely manner. A fault tolerance mechanism must be provided for abnormal scenarios to ensure timely resource release.
718
719* **Rule 45: Proper power consumption**
720
721OpenHarmony was designed for different types of devices, most of which were passive devices. Therefore, power consumption must be considered during API design.
722
723During the implementation of each function or mechanism, consider power consumption. Provide a detailed description for high power consumption APIs and offer guidance on how to use them.
724
725Provide a mechanism to prevent APIs from consuming power heavily. For example, after the device screen is locked or the application is switched to the background, stop the high power consumption behavior.
726
727Ensure that power consumption does not deteriorate during version evolution.
728
729* **Rule 46: Testable**
730
731Provide complete automatic test cases to:
732
7331. Quick detect faults during API development to improve API quality.
7342. Ensure that code modification does not affect existing functionalities during version iteration.
7353. Ensure backward compatibility of APIs.
736
737An OpenHarmony API must meet the following requirements:
738
7391. Automatic API test cases must be delivered for all new APIs.
7402. Use a test case for each single scenario. One test case covers a single functionality of an API, simplifying the code logic of each single test case.
7413. The test case execution must be efficient. The execution time of each test case must be limited to milliseconds.
7424. Automatic API test cases must be available for all APIs.
7435. Assertions with functional logic are required in addition to the capability of throwing exceptions.
744
745* **Rule 47: Environmentally adaptable**
746
747To support user personality features, an operating system usually provides environment customization capabilities, such as language, light/dark theme, and font size.
748
749For related APIs, if developers do not pass specified parameters, the results in the corresponding environment should be returned based on the environment in use.
750
751## Description of Post-Release Evaluation Specifications
752
753Even though all the pre-release rules have been satisfied, some issues might be detected during API use.
754
755It does not mean that these issues do not need to be considered during API design.
756
757On the contrary, you should carry out full considerations during the design to prevent these issues from occurring after the API release.
758
759If issues related to the following rules occur after the API release, the API quality is not good.
760
761### Stability
762
763* **Rule 48: Minimized rate for deprecated or changed APIs**
764
765For an API, stability is the most important attribute.
766
767API deprecation and behavior changes greatly reduce maintenance efficiency of developers, especially when multiple device types and system versions are involved.
768
769Designing an API with long-term stability and continuous compatibility is the goal of every API designer.
770
771The API deprecation rate and change rate are inversely proportional to the API quality to some extent.
772
773### Security
774
775* **Rule 49: No abuse of APIs**
776
777All APIs should be designed to prevent themselves from being abused. Abuse means that the use of an API exceeds the expected limit, either in quantity or scope.
778
779For example, the capability for accessing user data (such as **Gallery** and **Contacts**) or running in the background for a long time may be abused.
780
781To prevent abuse in terms of quantity, use one-time authorization.
782
783To prevent abuse in terms of scope, perform restrictions based on the caller identity.
784
785No matter what mechanism is used, describe it in the API reference. In the case of excessive abuse, notify the caller through a specific return value.
786
787* **Rule 50: No exploitation of APIs**
788
789Exploitation means that the use of an API causes negative impact, for example, system attacks.
790
791If a system problem occurs when an API or a combination of APIs is called, regardless of how they are called, there are defects in the API.
792
793It is forbidden if an API (in any case) can be called to crash the system, prevent the system from working, or steal user data. You should consider all possible calling scenarios to avoid extreme situations.
794
795### Maintainability
796
797* **Rule 51: Evolution support**
798
799A large feature of the operating system may take years to complete. This requires you to consider scalability during API design.
800
801If a group of new APIs are added to the new version and the original APIs are deprecated, the API design is poor. This situation should be avoided.
802
803* **Rule 52: Consistent behavior after feature expansion**
804
805With the system evolution, it is common that new parameters are added to APIs or new options are added to parameters.
806
807It is important to keep API behavior consistent. The original behavior should not be damaged by the introduction of new scenarios.
808
809If the behavior has to be changed, only the applications using the new version provide the new behavior. The behavior of applications using the old version remains unchanged.
810
811* **Rule 53: Documents updated accordingly**
812
813When updating the API implementation, update the API reference document accordingly. From the perspective of compatibility, the original behavior should not be changed. New functionalities should be implemented by new APIs.
814
815However, you can change the behavior of an existing API in the following cases:
816
8171. The change is made to rectify the defect.
8182. The change is made to improve performance or reduce power consumption.
8193. The change is made to provide new features or scenarios, without affecting the original feature or scenario logic.
820
821Describe the first and second cases in the Release Notes, and describe the third case in the API reference document.
822
823### Irreplaceability
824
825* **Rule 54: Orthogonal design**
826
827Orthogonality means that APIs should not overlap.
828
829For example, if an API provides the capability of creating a user account, whereas another API provides the capability of creating a user and logging in to the system, the orthogonality rule is not satisfied. You can change the logic of the second API so it provides the login capability only.
830
831If you draw API capabilities one by one, there should be no overlap between these graphs. For APIs at the same layer, it is not allowed that an API provides capabilities A, B, and C, whereas another API provides capabilities B, C, and D.
832
833To facilitate invocation, some APIs can be combined into a higher-level API. This uses different abstraction levels, not an overlap at the same layer.
834
835### Feedback from Developers
836
837* **Rule 55: Developer feedback noticed**
838
839A released API may have defects detected, even after going through the trial phase.
840
841Therefore, you should continue to notice the feedback from developers after the API release.
842
843The following types of feedback may be possible:
844
845* Requirements: Developers ask for new APIs to provide capabilities. You can plan these requirements in later versions.
846* Defects related to API behavior: The behavior of an API is inconsistent with that described in the reference document. This defect should be fixed as soon as possible. If the inconsistency is caused by incorrect description in the reference document, correct the document.
847* Inappropriate API design: The name or parameter setting of an API has defects. In this case, develop a new API to replace the defective API.
848
849In some cases, you may need to change the behavior of a published API. Note that behavior changes take effect only on new applications. The behavior can be determined based on the target API version of the application.
850
851In the worst case, you may need to deprecate an existing API and use a new one.
852