Dart: should the instance variables be private or

2019-03-02 17:04发布

问题:

For example:

class _Foo {
    String _var1;
    String var2;
}

I always use public variable var2 because I think it's no point to make private variables when the class is already private, because you can not access private class anyway.

But I found many people use private variable _var1. Is this just a personal preference? When the class is private, what is the point of private instance variable? If you can not access the private class, you can not access all of its instance variables regardless whether they are private or not. If you can access the private class in the same lib, then you can access its all instance variables regardless whether they are private or not.

回答1:

Making the class private doesn't make its members private and it doesn't make instances of that class inaccessible.

Assume

lib/private_class.dart

class Foo {
  final _PrivateClass privateClass = _PrivateClass();
}

class _PrivateClass {
  String publicFoo = 'foo';
  String _privateBar = 'bar';
}

bin/main.dart

import 'package:so_53495089_private_field_in_private_class/private_class.dart';

main(List<String> arguments) {
  final foo = Foo();
  print(foo.privateClass.publicFoo);
//  print(foo.privateClass._privateBar); // invalid because of ._privateBar
}

You can't declare variables or parameters of the type of a private class or extend or implement the class in another library or create an instance of that class, but otherwise there is not much difference.

So if the field is supposed to be hidden (internal state) to users of the API, then make the field private.



标签: dart