West
West

Reputation: 2570

What is the use of private instance variables?

Im studying dart and have this example code here that uses private instance variables:

class User {
String _first;
String _last;
  
String getFullName() {
return "$_first $_last";
}
}

main() {
User user = User();
user._first = "Bob";
user._last = "Smith";
var fullName = user.getFullName();
print(fullName);
}

The code seems to work just the same with or without underscores for the variables, so I'm really struggling to understand the true purpose of this and cant think of a real world example of when a protected variable could come in handy. Protected against what exactly since everyone is free to go into your code and tweak its implementation. Same goes for private methods. Hope someone can help me understand

Upvotes: 0

Views: 209

Answers (2)

dev-aentgs
dev-aentgs

Reputation: 1288

It prevents creation of unwanted and unintentional dependencies.

class FooUtils{
  
  //Foo variables
  int _fooId;
  
  //Foo methods
  void _updateFooState(){
    
  }
  
  //Foo util methods for users
  void getUserDOB(int userId){
    //some logic
    _updateFooState();
  }
  
}

class UserClass{
  // User specific code 
  
}

When you write Utils or Libraries or Packages that others will use, you wouldn't want to create a dependency on your class's internal state.

By default class members are public if they are not marked with _. If these members are visible and modifiable, then your Application's state cannot be guaranteed to be consistent. In the above example _fooId is an internal implementation detail of FooUtils and it shouldn't be visible to anyone using FooUtils class. If modified externally it might result in erroneous output.

Upvotes: 1

Tushar
Tushar

Reputation: 675

You are correct that anybody could go into your code and tweak its implementation. But we declare variables as protected or private to make our code better. These are called as access modifiers which allow you to restrict the variable access or control the access scope ofyour properties or methods.

When you declare a variable as public, it can be accessed from anywhere, within the class, outside of it and from any class that may extend it.

If you declare it as proctected then you cannot access it from outside the class but just from within it and any classes that my extend your parent class.

And when you declare it as private then you cannot access it from outside or from any extended classes but just from within the class that it is declared in.

Hope it will help you! :)

Upvotes: 0

Related Questions