org.sonar.l10n.delphi.rules.community-delphi.PublicField.html Maven / Gradle / Ivy
Why is this an issue?
Public fields break the encapsulation principle, in which other code should not be allowed to
manipulate the internal state of an object. The class should provide an API to allow state changes
in a controlled manner.
This API could be:
- A public property that gets or sets an internal field
- A read-only public property that gets an internal field
- Methods that set the internal field to a predefined value
How to fix it
Use a property to access the internal variable in a controlled way:
type
TMyType = class(TObject)
public
FName: string;
end;
type
TMyType = class(TObject)
private
FName: string;
public
property MyName: string read FName write FName;
end;
If the state should only be observed, not modified, consider enforcing immutability on the
property:
type
TMyType = class(TObject)
private
FName: string;
public
property MyName: string read FName write FName;
end;
type
TMyType = class(TObject)
private
FName: string;
public
property MyName: string read FName;
end;
© 2015 - 2024 Weber Informatics LLC | Privacy Policy