Some said that private properties can be used to change class definition without changing existing codes depending on the class before.
For example;
main() {
var p1 = new Project();
p1.name = 'Breeding';
p1.description = 'Managing the breeding of animals';
print('$p1');
// prints: Project name: Breeding - Managing the breeding of animals
}
class Project {
String name, description;
toString() => 'Project name: $name - $description';
}
Now, class Project is changed as below using private variables.
main() {
var p1 = new Project();
p1.name = 'Breeding';
p1.description = 'Managing the breeding of animals';
print('$p1');
// prints: Project name: BREEDING - Managing the breeding of animals
var p2 = new Project();
p2.name = 'Project Breeding of all kinds of animals';
print("We don't get here anymore because of the exception!");
}
class Project {
String _name; // private variable
String description;
String get name => _name == null ? "" : _name.toUpperCase();
set name(String prName) {
if (prName.length > 20)
throw 'Only 20 characters or less in project name';
_name = prName;
}
toString() => 'Project name: $name - $description';
}
What does it mean that;
(due to the private properties introduced) The code that already existed in main (or in general, the client code that uses this property) does not need to change
The author of the above codes(Learning Dart) said that, due to the newly inserted private property(_name), the existing codes like 'main()' are NOT affected by the change of properties in the Project class.
That's what I can't understand. How newly inserted private properties in existing classes can be a way to keep other codes depending on those classes untouched or safe?
I still don't know what your actual question is.
You can use private fields, classes and functions/methods to reorganize (refactor) your code and
as long as the public API is not affected and the users of the library do not depend on the internal behavior of the classes the users should not recognize the change.
Privacy is mostly a communication medium to indicate that some members (public) are intended to be accessed by API users and private members are an implementation detail the API user should not care about.
Don't confuse privacy with security. Reflection usually allows access to private members.
If this is not the answer you were looking for please add a comment or improve your question.