Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

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.

like image 828
sgon00 Avatar asked Nov 27 '18 07:11

sgon00


People also ask

Do instance variables have to be private or public?

Instance variables are declared with the keyword “private” by default. However, it is possible to make an instance variable public or protected. The value of an instance variable can be changed only within the method in which it is declared.

When should instance variables be private?

Instance variables are made private to force the users of those class to use methods to access them. In most cases there are plain getters and setters but other methods might be used as well.

Can a private class have public variables?

Yes it is possible.

Does Dart have private variables?

Instance variables are sometimes known as fields or properties. Unlike Java, Dart doesn't have the keywords public , protected , and private .


1 Answers

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.

like image 126
Günter Zöchbauer Avatar answered Oct 10 '22 12:10

Günter Zöchbauer