Programming Practices
Array Traversal
- Level: Requirement
Description: For array traversal, prioritize using Array object methods such as forEach(), map(), every(), filter(), find(), findIndex(), reduce(), and some().
Negative Example:
const numbers = [1, 2, 3, 4, 5];
const increasedByOne: number[] = [];
for (let i = 0; i < numbers.length; i++) {
increasedByOne.push(numbers[i] + 1);
}
- Positive Example:
const numbers = [1, 2, 3, 4, 5];
const increasedByOne: number[] = numbers.map(num => num + 1);
Assignment in Control - Flow Expressions
- Level: Requirement
Description: Avoid performing assignments in control - flow expressions used in if, while, for, or ?: statements, as this can lead to unexpected behavior and poor code readability.
Negative Example:
if (isFoo = false) {
// ...
}
- Positive Example:
const isFoo = someBoolean;
if (isFoo) {
// ...
}
Finally Blocks
- Level: Requirement
Description: Avoid using return, break, continue, or throw statements in finally blocks. Unhandled exceptions in called methods can also cause premature termination of the finally block. Premature termination can affect exception propagation in try or catch blocks and method return values.
Negative Example:
function foo() {
try {
// ...
return 1;
} catch (err) {
// ...
return 2;
} finally {
return 3;
}
}
- Positive Example:
function foo() {
try {
// ...
return 1;
} catch (err) {
// ...
return 2;
} finally {
console.log('XXX!');
}
}
ESObject Usage
- Level: Suggestion
Description: ESObject is mainly used for type annotations in cross - language calls between ArkTS and TS/JS. Using ESObject in non - cross - language scenarios introduces unnecessary overhead.
Negative Example:
// lib.ets
export interface I {
sum: number
}
export function getObject(value: number): I {
let obj: I = { sum: value };
return obj
}
// app.ets
import { getObject } from 'lib'
let obj: ESObject = getObject(123);
- Positive Example:
// lib.ets
export interface I {
sum: number
}
export function getObject(value: number): I {
let obj: I = { sum: value };
return obj
}
// app.ets
import { getObject, I } from 'lib'
let obj: I = getObject(123);
Array Type Notation
- Level: Suggestion
Description: ArkTS supports two array type notations: T[] and Array. For better readability, it is recommended to use T[].
Negative Example:
let x: Array<number> = [1, 2, 3];
let y: Array<string> = ['a', 'b', 'c'];
- Positive Example:
let x: number[] = [1, 2, 3];
let y: string[] = ['a', 'b', 'c'];
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.