I'm writing a equals(Object obj) function for a class. I see that it is possible to access the private fields of obj from the caller. So instead of using a getter:
Odp other = (Odp) obj;
if (! other.getCollection().contains(ftw)) {
}
I can just access the field directly:
Odp other = (Odp) obj;
if (! other.collection.contains(ftw)) {
}
Is this bad practice?
I tend to always use getters, because sometimes a getter isn't just "return(foo)". Sometimes they initialize things if they're null, or have some debug logging in them, or validate the current state in some way. It's more consistent.
No, it's not. The reason that private variables and methods are not accessable from other classes is to allow you to change the internals of your class without having to change all the code that uses the class (that and to prevent the user of your class from e.g. setting a variable to a value that it's never supposed to have).
If you use private variables of other objects that doesn't hurt anything, because if you'd restructure your class's internals, you'd have to change the code inside the class anyway.
I dont think this is bad practice, but a feature of the language. It not only allows you to test equals the way you do, but it is also useful in a Prototype pattern for object creation.
That is fine and completely normal. It is a little bit odd to think that this can fiddle with the private fields of other, but it's okay because there's no way anything bad can happen as far as some third party being able to muck with an Odp object's internals. Any method of the Odp class can modify any private members of any Odp object, even non-this ones, but that's fine since any such methods can obviously be trusted!
This is a duplication of
Why can I access my private variables of the "other" object directly, in my equals(Object o) method
Private data is accessible by any instance of that class, even if one instance of class A is accessing the private members of another instance of A. It's important to remember that that access modifiers (private, protected, public) are controlling class access, not instance access
Using private member for entity class may caused proxy class work incorrectly.
Imagine hibernate create class by lazy query. If you check member variable , it return null.
But if you call get() , it will fetch data from database and initialise the field.
Related
In Java in the equals(Object o) method I can access the private variables of the passed in object without going through its public getters.
public boolean equals(Object o){
...
MyObject other = (MyObject)o;
return getProp() == other.prop;
}
How's that?
Private data is accessible by any instance of that class, even if one instance of class A is accessing the private members of another instance of A. It's important to remember that that access modifiers (private, protected, public) are controlling class access, not instance access.
The probable answer is that the designer of the visibility model considers that any developer working in a class has to master the implementation of the whole class.
But this is a bad idea. This encourages bad practice. A developer accessing a field of Person, in the class Person, does not have to know the implementation of the whole class. The good practice is to use the accessor, without having to know what operations the accessor does.
What is the benefit of making fields private while creating an immutable class?
I have seen why while creating immutable class, fields are declared as private? but I didn't get understand anything from this post.
Can anybody please explain me the same?
The best way to explain is with an example:
public class Immutable {
private final char[] state = "Hi Mom".getChars();
public char[] getState() {
return state.clone();
}
}
Here we have a properly encapsulated, immutable class. Nothing can change the state (modulo nasty reflective tricks).
Now lets JUST change the access on the field:
public class Immutable {
public final char[] state = "Hi Mom".getChars();
public char[] getState() {
return state.clone();
}
}
Note we are still making the defensive copy in getState ... as before ... but now someone can do this:
Immutable mu = new Immutable();
mu.state[1] = 'o';
... and our supposedly immutable object's state has changed.
That is ONE reason why it is a good idea to keep the fields private. (Obviously, this only applies to field whose types are mutable reference types.)
A SECOND reason is encapsulation. Declaring fields as private hides implementation details, which reduces the risk of unwanted cross-coupling. If I don't do this, then I (or some other programmer) might be tempted to write code that depends on the internals of Immutable. That is going to lead to problems if I need to change them; e.g. changing the type of state to String. Problems as in "lots more code to check / change".
A THIRD reason is that non-private (and particularly public) fields can be an impediment to subclassing. If I declare a field as public then, the I can't undeclare it in a subclass. If I want to hide the field or modify the behavior of the field in a subclass (by overriding) ... I can't. By contrast, if the field is private and access is via instance methods, I can override those methods in subclasses. Or I can choose to not use the field at all.
The only reason for making final fields private is binary compatibility, and this actually holds true irrespective of whether the containing class is immutable or not.
A class C is said to offer binary compatibility to classes X and Y
that use class C if class C can be refactored without having to
recompile classes X and Y.
You only need to worry about binary compatibility if you are developing a library to be used by software that is written by others and therefore you have no control over. If you are in this situation, then you pretty much have to use full encapsulation, which means that you have to make all fields private and only access them via getters.
However, in the vast majority of cases, what we are developing is top-layer, self-contained application software, not libraries to be used by others. So, in the vast majority of cases, there is no good reason to make final fields of immutable classes private, it is just a widely held misconception. In a top-layer, self-contained application scenario you can always refactor everything and your IDE will accordingly refactor all references, so immutable classes do not need encapsulation.
Some of the answers suggest that if a field is not private, and it points to a mutable object, then someone might go and modify that mutable object, which is of course correct, but then we go into the philosophical question of what really is an immutable object. Can an object still be called immutable if it contains mutable objects? Is the mutability of an object dependent on the mutability of objects that it contains?
My rule is as follows:
There are two kinds of fields: contained and referenced, which can otherwise be thought of as owned and unowned. As an example, think of an Employee class: the name of the employee is contained/owned by the class, since each employee has their very own name. However, the Employee class may also contain a reference to a Department class, and of course each employee does not have their very own department, so the department is a referenced/unowned field.
A contained/owned field like Employee.name must of course be final and immutable in order for the owning class (Employee) to be immutable. Such a field does not need to be private, unless we are aiming for binary compatibility.
A referenced/unowned field like Employee.department also needs to be final if the referring class (Employee) is to be immutable, but it does not have to be immutable, and its immutability does not affect the immutability of the referring class. Even in this case, (and unless we are aiming at binary compatibility,) a referenced/unowned field generally does not need to be private, because there is still no issue of encapsulation: we are not going to be making a defensive copy of an employee department, that would be nonsensical.
So, unless we are aiming for binary compatibility, then both in the case of contained/owned immutable fields and referenced/unowned fields (which can be either mutable or immutable,) the fields can stay public final and everything will be fine.
final class A{
final List l = new ArrayList();
}
Suppose you have list, and you made this list as final it's reference not modified at all.
But this list is easily accessible to outer classes and they are easily modify it's contents.
so prevent that we have to add private access specifier.
An object that is referred to by a public final reference-type field can still be modified through that field. (What you can't do is change the field to refer to a different object.)
To disallow unwanted modifications, you need to make the field private.
public fields can be accessed from any class anywhere and modified. But making fields private and final and using constructor injection / defensive copies, you ensure that the class is completely immutable.
Non-private fields may still be read-accessed - and if that field is an object, mutable operations on that object may be invoked.
Making the fields private will prevent this possibility.
If you'll use public field other objects will be able to change state of your "almost-immutable" object which will break encapsulation and make it a mutable object.
Say I have a class Animal and then a bunch of sub-classes that extend Animal. Say I want to have a common field called name that should also exist in each child class. What is the proper way to include and initialize this field in each sub-class?
1) Declare the field in the parent as protected, and then initialize it inside of each sub-class. If I do it this way, is it proper to refer to the field as super.variable or simply variable? Personally to me, using super makes it more obvious that the field is declared in the parent. (This is what I am currently doing)
2) Declare the field in the parent as private and then create getters and setters to access the field
3) Just declare and initialize the same variable in each sub-class
4) Another method I'm missing?
Thanks for the help. I understand this question is fairly basic, but I'm curious of what the most proper style is.
Edit:
I'm not to sure if you guys will see this, but here is a follow up question.
Is there any good way to ensure that the sub-classes initialize the field?
The answer depends on whether you need to control access to that field for correctness (e.g., to make sure that some other field gets updated at the same time). If it's okay for subclasses to twiddle the field directly, then just use protected. If you need to perform additional checks or actions whenever the field is set, you should make it private to the superclass and make the subclass use the setter to ensure your logic is run. You shouldn't duplicate the field if you know that it'll always be needed; if you're not sure, then you should consider using an interface Animal and putting the field on an AbstractAnimal implements Animal.
In Java, you don't use super for anything except to call the superclass's version of a method. Just access protected fields directly; that's what they're there for, and your development environment will keep track of where they're declared if you need to know.
I vote for 2:
Create a private field, and have setters and getters (which can be protected to make them accessible only to subclasses).
Other options if you don't need a setter (just a getter):
4) Abstract getter and leave it up to the subclass how to implement it
5) private final field, set by abstract class constructor, and a getter.
I always make fields protected fields, since this helps debuggability & extensibility, and put public getters & setters on them to make a 'property'.
(Private fields in various open-source libraries, Swing components etc have repeatedly been a hindrance to me when trying to do quite legitimate debugging/ extension engineering. So I'm fairly anti- them.)
If I'm concerned about traceability, where there is possible behaviour or errors involved (such as values being got & cached), I might access the variable in subclasses via the getter.
I always use this.name when writing to variables -- it works well for code clarity, and it simplifies parameter-naming in setters. (Use just name for the parameter & this.name for the field.)
I don't use this when reading variables -- it's the writes I want to be clear about. For collections, I suffix the field with List or map or whatever ie childList -- but the parameter and locals are "children".
I never use super when referring to variables. Super would only make sense to disambiguate inherited & declared variables with the same name, which you can legally do -- but is almost guaranteed to be erroneous for code style, clarity & tends to lead to bugs.
I also like to make most properties mutable -- rather than settable only at construction. This helps if you ever want to use Hibernate, or persist the data. Over-reliance on constructor initialization tends to evolve into difficulties -- large & brittle call-signatures, inability to use the class for partly-formed data or "special value" answers, and order-of-init problems.
I think it depends on the situation. If the name field should be publicly accessible, I would declare the field as private and then make public get/set methods. Sometimes you want to expose fields on the base class as part of the public interface of the derived classes.
If the name field should only be used inside the derived classes I would just go with a protected field.
If you want to be sure that a subclass initializes a field add a parameter in the base class constructor, then initialize the field in the base class using the argument supplied by the derived classes constructor.
I usually using option 2 (private + accessors - protected,not necessary public) to have a chance to customize variable access.
About your edit: Force in constructor name if it is a mandatory requirement
Animal(String name) {
this.name = name;
}
or
String getName() {
if(null == name){
name = initializeName();
}
return name;
}
and make initializeName() abstract
Let's say I have a separate GUI class that has a public boolean called "guiWait" and also has a boolean method that returns guiWait.
What's the difference between:
while(gui.guiWait)...
and
while(gui.getGuiWait())...
The difference is visibility. When you make guiWait public to be used like the first example, outside callers can modify the value. If you use a method and make the variable private, callers cannot modify the guiWait variable (although they can modify the object it references if it's mutable). Furthermore, if you make a habit of using getters and setters, then later on if you need to add logic to the getting or setting process (such as you need to make the value derived from some other new field), you already have the methods and won't break any caller's code by making the variable private. So it's considered "best practice" to always use getters and setters in Java.
If guiWait is a public boolean, there is no point in having a "getter" method for it. If it were private or protected, then it'd be a different story. The private-getter method is more flexible because you can change the implementation of the "getting" of that variable, and add checks or whatever inside the method. Private getters/setters also make things clearer and establish which things should be seen by other classes and which are only meant to be used inside a single class they are apart of. If you find you do need a getter for a specific member variable (need some kind of verification or checking), which is very common, then it would be inconsistent to do it just for that variable.
The core concept of OOP is encapsulation. The getter and setter methods (eg. your getguiWait() method) are used so that nobody is able to access the internal fields of an object. This way no one else is able to set the internal fields to an inconsistent/abnormal value. By using the "getter" and "setter" methods (and hiding the inner fields by using private), you ensure that anyone willing to set or get a field will have to go through the checks that you have put up. Example Class Cat can have age as its field. In the setter method you would check that the user input value is not negative. If you allow the age field to be public, someone could potentially set it to negative which would make no sense.
Its the pure concept of Data Encapsulation in JAVA.
A language mechanism for restricting access to some of the object's components.
A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
http://www.tutorialspoint.com/java/java_encapsulation.htm
I'm trying to understand the usage for getter/setter methods in a class. Let's say we have a class called A with some public instance variables followed by a constructor with parameters where arguments were passed from another class(main) to it. Inside the constructor we let those instance variables equal what was passed.
Now if this class were to be used by another programmer, nothing would stop them from directly accessing/changing the instance variables to something that isn't valid. By making the instance variables private we can eliminate access to those variables. However if we wanted to have those instance variables updated/changed indirectly or under some specific condition or perhaps just letting the person have access to the instance variable, we would create a getter/setter pair for this purpose.
Benefits?:
1.Change instance variable only under certain valid reasons under the set() method
2.So that we can show what the instance variable actually is without giving the programmer who is using this class the ability to change it.
Is this a correct interpretation?
Encapsulation – refers to keeping all the related members (variables and methods) together in an object. Specifying
member variables as private can hide the variables and methods. Objects should hide their inner workings from the
outside view. Good encapsulation improves code modularity by preventing objects interacting with each other in
an unexpected way, which in turn makes future development and refactoring efforts easy.
Being able to encapsulate members of a class is important for security and integrity. We can protect variables from
unacceptable values. The sample code above describes how encapsulation can be used to protect the MyMarks object
from having negative values. Any modification to member variable vmarks can only be carried out through the setter
method setMarks(int mark). This prevents the object MyMarks from having any negative values by throwing an
exception.
Your interpretation is correct. Also (off the top of my head):
It allows the implementation of the class to change (eg if you wish to remove the field and replace it) without forcing consumers to interact with your class any differently.
It allows AOP frameworks to intercept calls to your get / set method.
You can specify permissions via annotations for access to methods.
Yes, your interpretation is correct. But it's because limits of language. For instance in python you don't need write everytime getter or setter, because you can override behavior of member variables. For example:
class MyClass:
def __init__(self, myproperty):
self.myproperty = myproperty
And if everybody use it in way like:
print(new MyClass("test").myproperty)
you can still change behavior of you getter:
class MyClass:
def __init__(self, myproperty):
self._myproperty = myproperty
#property
def myproperty(self):
return self._myproperty + " changed behavior"
or even of setter without touch code what use you class:
#myproperty.setter
def myproperty(self, myproperty):
if len(myporperty) > 0:
self._myproperty = myproperty
See property reference for better example.
if an instance variable is to be used only by methods defined with in its class, then it should be made it as private.If an instance variable must be within certain bounds, then it should be private and made available only through accessor methods[getter as well as Setter] Methods.