You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
public readonly positionProperty: TReadOnlyProperty<Vector2>;
private readonly _positionProperty: Property<Vector2>;
To avoid clients or outside classes from modifying private fields. I realized this is not a pattern I really use in my sims and was wondering if it'd be worth promoting into our convention documentation, as others might be unaware of these details.
The text was updated successfully, but these errors were encountered:
This pattern concerns the situation where a field (often a Property) is read-only for the public API, but writeable internally to the class. Two common implementation patterns are shown below. @AgustinVallejo was commenting on the first pattern, which is used in MOTHA. The anti-pattern shown below is unfortunately what I see too often in code reviews.
// Pattern 1: This pattern uses 2 references to the same Property instance. The public reference // is read-only for getting the value. The private reference is for setting and resetting the instance// internal to the class.classMyClass{publicreadonlypositionProperty: TReadOnlyProperty<Vector2>;privatereadonly_positionProperty: Property<Vector2>;publicconstructor(){this._positionProperty=newVector2Property( ... );this.positionProperty=this.positionProperty;}publicreset(): void{this._positionProperty.reset();}}
// Pattern 2: This pattern uses 1 private reference to the Property instance and // a public ES5 getter.classMyClass{privatereadonlypositionProperty: Property<Vector2>;publicconstructor(){this.positionProperty=newVector2Property( ... );}publicreset(): void{this.positionProperty.reset();}getposition(): Vector2{returnthis.positionProperty.value;}}
// Anti-pattern: A single reference that is writeable in the public API, with documentation // saying "don't write to this", or an implicit hope that no one will write to it.classMyClass{publicreadonlypositionProperty: Property<Vector2>;publicconstructor(){this.positionProperty=newVector2Property( ... );}publicreset(): void{this.positionProperty.reset();}}
As part of phetsims/models-of-the-hydrogen-atom#125 I was discussing with @pixelzoom about the following conventions for exposing fields:
To avoid clients or outside classes from modifying private fields. I realized this is not a pattern I really use in my sims and was wondering if it'd be worth promoting into our convention documentation, as others might be unaware of these details.
The text was updated successfully, but these errors were encountered: