Programming Practices
Class Property Access Modifiers
- Level: Recommendation
Description: ArkTS provides private, protected, and public access modifiers for class properties. The default access modifier is public. Using appropriate access modifiers can enhance code security and readability. Note that if a class contains private properties, the class cannot be initialized using object literals.
Negative Example:
class C {
count: number = 0;
getCount(): number {
return this.count;
}
}
- Positive Example:
class C {
private count: number = 0;
public getCount(): number {
return this.count;
}
}
Floating - Point Number Representation
- Level: Recommendation
Description: In ArkTS, floating - point values include a decimal point, but there is no requirement for a digit before or after the decimal point. Adding digits both before and after the decimal point can improve code readability.
Negative Example:
const num = .5;
const num = 2.;
const num = -.7;
- Positive Example:
const num = 0.5;
const num = 2.0;
const num = -0.7;
Checking for Number.NaN
- Level: Requirement
- Description: In ArkTS, Number.NaN is a special value of the Number type used to represent non - numeric values.
In ArkTS, Number.NaN is unique in that it does not equal any value, including itself. Comparisons involving Number.NaN are counterintuitive: both Number.NaN !== Number.NaN and Number.NaN != Number.NaN evaluate to true.
To check if a value is Number.NaN, always use the Number.isNaN() function.
- Negative Example:
if (foo == Number.NaN) {
// ...
}
if (foo != Number.NaN) {
// ...
}
- Positive Example:
if (Number.isNaN(foo)) {
// ...
}
if (!Number.isNaN(foo)) {
// ...
}
Top comments (0)