DEV Community

Cover image for ArkTS programming specification(4)
liu yang
liu yang

Posted on

ArkTS programming specification(4)

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;
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Positive Example:
class C {
  private count: number = 0;

  public getCount(): number {
    return this.count;
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode
  • Positive Example:
const num = 0.5;
const num = 2.0;
const num = -0.7;
Enter fullscreen mode Exit fullscreen mode

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) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode
  • Positive Example:
if (Number.isNaN(foo)) {
  // ...
}

if (!Number.isNaN(foo)) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)