Should I Use Public or Private Variables

Should I use public or private variables?

private data members are generally considered good because they provide encapsulation.

Providing getters and setters for them breaks that encapsulation, but it's still better than public data members because there's only once access point to that data.

You'll notice this during debugging. If it's private, you know you can only modify the variable inside the class. If it's public, you'll have to search the whole code-base for where it might be modified.

As much as possible, ban getters/setters and make properties private. This follows the principle of information hiding - you shouldn't care about what properties a class has. It should be self-contained. Of course, in practice this isn't feasible, and if it is, a design that follows this will be more cluttered and harder to maintain than one that doesn't.

This is of course a rule of thumb - for example, I'd just use a struct (equivalent with a class with public access) for, say, a simple point class:

struct Point2D
{
double x;
double y;
};

The point of public/private variables and functions?

Basically, when you are developing a class that other developers will use :

  • public methods and variables are what the other developers will (need to) use -- what your class does
  • private methods and variables are what you, as the developer of that class, used to make it work -- it's how your class works internally.

Others need to be able to use your class ; but not to know how it does it.


If you want to know more, you'll have to search for Encapsulation.

public or private, does it really matter with Android variables

Private fields promote encapsulation

It's a generally accepted convention to use private unless you need to expose a field or method to other classes. Getting in this as a habit will save you a lot of pain in the long run.

However, there isn't anything inherently wrong with a public field or method. It causes no difference for garbage collection.

In some cases some types of access will affect performance, but they are probably a bit more advanced than the topic of this question.

One such case has to do with inner classes accessing outer class fields.

class MyOuterClass
{
private String h = "hello";

// because no access modifier is specified here
// the default level of "package" is used
String w = "world";

class MyInnerClass
{
MyInnerClass()
{
// this works and is legal but the compiler creates a hidden method,
// those $access200() methods you sometimes see in a stack trace
System.out.println( h );

// this needs no extra method to access the parent class "w" field
// because "w" is accessible from any class in the package
// this results in cleaner code and improved performance
// but opens the "w" field up to accidental modification
System.out.println( w );
}
}
}

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

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.

Which is better practice, using private variables or public methods within the class?

For the most part, it's all personal preference. I would use the first constructor if its value did not depend on other variables. However, setter methods allow for certain conditions to be met before modifying the value of a variable. For example:

private int x;

public TestClass(int x) {
setX(x);
}

public void setX(int x) {
// Some random condition depending on other variables.
if (System.currentTimeMillis() & 1 == 0) {
this.x = 5;
} else {
this.x = x;
}
}

It would make sense to use a setter method if there were many conditions that could not be easily represented by a ternary statement.

If the class is abstract, then a concrete class that extends it could possibly override the setter method, thus modifying the value of the variable. If you plan on using self-encapsulation and don't want any child class to override the setter method, simply add the final keyword to the method declaration.

Why do we declare Private variables in Java?

When programmers talk about accessing a variable, they mean accessing its value when the program runs. Protecting the code from changes is another matter entirely and requires human processes rather than syntax of a programming language. Making a variable private "protects" its value when the code runs. At this level, we are not concerned with protecting it from other programmers changing the code itself. The point of so-called "data hiding" is to keep internal data hidden from other classes which use the class. Those other classes should only access behavior by calling methods on the class, not by changing values of variables directly.

General programming principles such as "data hiding" are followed to help us as programmers write correct code. If any class can change a variable's value, then it is difficult to ensure that the value is valid. Say for example, you have a variable which counts the number of widgets a factory manufactures. By making the variable a private data member, you can more easily ensure that the value is never negative. On the other hand, if the variable is public, another class could change it to a negative value which can cause other parts of the code to crash.

Difference between public and private variables

Public variables are accessible from out side classes but private one just accessible for current class and inner classes:

public class VarClass
{
public int publicID = 10;
private int privateID = 100;
public VarClass()
{
Console.WriteLine(publicID);
Console.WriteLine(privateID);
}

public class InnerClass
{
public InnerClass()
{
VarClass c = new VarClass();
Console.WriteLine(c.privateID);
Console.WriteLine(c.publicID);
}
}
}

public class OuterClass
{
public OuterClass()
{
VarClass c = new VarClass();
Console.WriteLine(c.privateID); // Compile Error
Console.WriteLine(c.publicID);
}
}

What is the difference between public, private, and protected?

You use:

  • public scope to make that property/method available from anywhere, other classes and instances of the object.

  • private scope when you want your property/method to be visible in its own class only.

  • protected scope when you want to make your property/method visible in all classes that extend current class including the parent class.

If you don't use any visibility modifier, the property / method will be public.

More: (For comprehensive information)

  • PHP Manual - Visibility

Why should variable has public or private or protect but function should not in a class

When you use any of the programming languages, you should know the rules, otherwise, the behavior of the program will come strange; for example as in your case, while declaring functions in a class, omitting the visibility keywords implies the function will have the public visibility.

About the property visibility:

Class properties must be defined as public, private, or protected. If
declared using var, the property will be defined as public.

And about the method visibility:

Class methods may be defined as public, private, or protected.
Methods declared without any explicit visibility keyword are defined
as public.

And finally about the defining variables, I believe you need to read about the variable scope.


As per request, about the comment above regarding static vs private:

staticness of a class member is intended to deal with the lifetime of the matter (the matter exists regardless of existence of any instance of a class), while privateness is about the visibility of the matter (for example: the existent matter cannot be accessed when it has the private visibility.)

The two are different concepts and are not mutually exclusive (you may use them together.) Mixing these concepts, makes me believe that you're in an urgent need of reading some OOP materials.

private or protected variables?

In this case, the location of that image used to be a private, implementation-specific feature of the base class. Your new requirements meant that it needed to be able to vary from one derived class to another.

You should keep the member field private, but define a protected virtual property to expose it to derived classes:

private const string _defaultImagePath = @"C:\whatever.bmp";

protected virtual string ImagePath {
get {return _defaultImagePath;}
}

In the derived class that wants to change it:

private const string _myImagePath = @"C:\other.bmp";
protected override string ImagePath {
get {return _myImagePath;}
}

You will also want to change the base class so that it uses the property when it needs the image path, instead of using the field. This is the "Encapsulate Field" refactoring.



Related Topics



Leave a reply



Submit