Dart: should the instance variables be private or public in a private class?

前端 未结 1 450
盖世英雄少女心
盖世英雄少女心 2021-01-17 18:43

For example:

class _Foo {
    String _var1;
    String var2;
}

I always use public variable var2 because I think it\'s no poin

相关标签:
1条回答
  • 2021-01-17 18:58

    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.

    0 讨论(0)
提交回复
热议问题