consider the class:
class MyClass{
MyOtherClass obj;
//setObj and getObj methods
public void someMethod(){
...
//access to obj needs.
...
}
}
How to right replace
//access to obj needs.
through getter or explicitly?
P.S.
I saw both variants in my expirience.
Personally I would say it depends on the level of "connection" between both classes. If they are in the same package and part of the same "mecanism" (one would have no reason to exist without the other), bypassing accessors is acceptable.
So here we're talking about code in Class MyClass accessing information in an instance of MyOtherClass.
Typically you don't get a choice. If MyOtherClass exposes a getter for a data member, it's unlikely to also expose that data member. If it does (even if the data member is, say, protected but the accessor is public), the design is a bit questionable.
But if you do have the choice, I would use the getter, rather than the exposed data member. It's a bit subjective, but using data members rather than accessors more tightly binds the classes together. In my protected/public example, you'd have more work to do if for any reason you wanted to move MyClass to a different package.
It's worth noting that using the getter is not more expensive in performance terms with a decent JVM (such as the one from Sun). If the code becomes a performance "hotspot" for whatever reason (or possibly even if it doesn't), the JVM's JIT will convert the call to the getter into a direct access anyway (presuming it's a pure getter), so you get the benefit of abstraction at the coding/design-time without the function call overhead at runtime.
To answer this, let's first see why getters and setters were introduced in the first place. It is clear that direct access to data members is simpler.
SOme of the reasons are:
for a better encapsulation, to hide the property implementation from a class user. For example you can internally store a temperature value in C and return it by a getter in F.
for more control over the access. If you want to do something more besides pure getting/setting a piece of data, you would need a method. For example, you might want to log the change of value for audit purpose
methods are much more "interface friendly" than pure data members.
In this case the class itself accesses its own property. Are you sure you want that?
If so, let's see the reasons:
Encapsulation is definitelly not needed, since the class itself accesses its own attributes.
Do you need to somehow control access here? Do you need to do something else, besides get/set? Are there any other possible users of this class?
If all these answers are NO, ans especially if the only user of this class the mentioned method, then go for a simpler option and use direct access, without getters/setters.
If some of the answers is true, just make a simple trade-off and decide.
Related
It is common in Java classes to have lots of getter and setter methods, one each for every data model class variable. I realize that many IDEs will create these for you, but I'm trying to avoid this clutter and not have all these methods in my classes. So, is there any way to access a variable in a read only fashion outside the class (as if it were public final), while retaining write access inside the class or subclass exclusively (as if it were private or protected).
The only pseudo-solution I've come up with is a base class (or interface with default methods) that has a get(String variableName) method which then gets the fields of the class via reflection and returns the appropriate one. The downside is that for that to work, the variables have to be public, so only by convention does it meet my requirements (in that in the extending/implementing class that has the variables I want to access, I only call the get method from outside the class, and don't implement a set method). The main thing I don't like about this is that if a variable name changes, callers of the get methods will not cause compiler errors, since the variable name is just a hardcoded String.
Anyone have a better idea?
Yes - try to design your classes so you don't have getters and setters at all. Typically it's a bad design to have getters and setters on all of your fields because it breaks encapsulation. An exception is the case of Java Beans (where you have a model class/DTO or some class that's mapped to XML/JSON); here you should not mind them because setters and getters are the only methods.
In classes that have logic, inject your dependencies via constructor or directly if you use Spring/CDI and you like it. This is more safe because you won't have objects in inconsistent states; like for example you create an object but forget to call a setter -> NullPointerException. But by using constructors, you avoid the case of forgetting to call the setters.
Of course there might be exceptions, like when setting some optional fields when you don't want all the dependencies in the constructor all the time. This however can be solved with overloading constructors or if the case is more complex the problem can be solved in a more elegant way by using the builder pattern.
See a great article on this: http://www.javaworld.com/article/2073723/core-java/why-getter-and-setter-methods-are-evil.html
You may use lombok - to manually avoid getter and setter method. But it create by itself.
The using of lombok significantly reduces a lot number of code. I found it pretty fine and easy to use. But here you may find some pros and cons of using lombok here.
Hope it will help.
Thanks a lot.
Java FX introduced something similar to what you want: ReadOnlyProperty
Might not be exactly what you are looking for, though. In general, I don't think exposing a variable is a good idea.
I know this applies to many languages, and not just Java, but that is the language I'm most familiar with.
I understand what the modifiers do, and how to use them. I just want to know, why do we need them? Why can't every object be accessible, whether or not it needs to be?
The reason becomes more apparent when you have to maintain a larger project. When a method or variable is public, you have to be careful when you make changes to it, because you never know which parts of the codebase rely on its exact behavior.
But when a variable or method is private, you know that it is not used outside of the class. That means there is a lot less code you have to pay attention to when you make changes.
By making class features private and public, you clearly separate the interface to the outside world from the internals. The less you exposes to the outside world, the more freedom you have with what the internal implementation does.
When you, for example, always make variables private and accessed them through getters and setters, you can later change them from a variable to a computed value, and then even later add caching to the computation for performance reasons. When it would be a public variable, you would have to change code everywhere the variable is used. But when you expose it to the outside world through getters and setters, all other code can keep using the class as if nothing had changed.
Making fields and methods private keeps other classes from improperly depending on the specific details of how a class works. The public interface (and the best case of all, an actual interface) describes how client code should interact with a library based on the semantics of the work being done. The implementer is then free to use whatever appropriate techniques to implement that interface and can make significant behind-the-scenes changes knowing that the client code will keep working.
An everyday example is the Collections group of interfaces. Most of the time, it's not important logically for code to know what particular kind of Set is in use, just that it's a collection that supports certain operations and doesn't have duplicates. This means that a method that accepts a Set<Integer> will work with any Set, including HashSet and ImmutableSet, because the person who wrote the interface wasn't poking around in the implementation's internals.
An example where this breaks down is the unfortunate tendency of some programmers to use packages in the com.sun namespace, especially when using cryptography. Upgrading to a new version of the JRE routinely breaks this code, which would have worked fine if the programmer had used the proper javax.crypto interfaces and factory methods instead of poking around in the JVM internals.
More or less they are used to control who can access your member variables and functions. It's the broader concept of encapsulation at work in Java(http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)).
From the Oracle Docs:
Access level modifiers determine whether other classes can use a
particular field or invoke a particular method. There are two levels
of access control:
At the top level—public, or package-private (no explicit modifier).
At the member level—public, private, protected, or package-private (no
explicit modifier).
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
As to why you should do this:
It has to do with intent of use. It would probably be best described as a design choice that helps guide usage through-out the code-base. By marking something private you are telling other developers that this field or method should not be used outside it's current purpose. It really becomes important on large projects that shuffle developers over time. It helps communicate the purpose & intended uses of classes.
To avoid other classes having direct access to internal members of the class.
This is most useful for avoiding that member variables are mutated in an uncontrolled way (e.g. without proper validation, without notifying listeners, ...).
Another reason to avoid this is that the internal implementation may change at any time but you don't want to break code that uses it.
As others have noted, the concept is called Encapsulation.
Access modifiers are there to set access levels for classes, variables, methods and constructors. This provides an individual with the chance of controlling better the privacy of the application. There are 4 access modifiers.
Modifier | Class | Package | Subclass | World
no modifier:--|----yes----|------yes--------|--------no--------|-----no----|
private:-------|----yes----|-------no--------|--------no--------|-----no----|
public:--------|----yes----|------yes--------|-------yes-------|----yes----|
protected:---|----yes----|------yes--------|-------yes-------|-----no-----|
Regarding your question, we do need and use access modifiers because we need to restrict whom can call our program and in what way.
Also, when it comes to variables if you make something public, that means that I have direct access to it. Therefore, I am allowed to do whatever I want without following your guidelines through your methods.
For example:
public int maxUsers;
public void setMaxUsers(int users) throws IllegalArgumentException{
if(users > 0 && users <= 1000){
maxUsers = users;
}else{
throw new IllegalArgumentException("The users can not be less than 0 or greater than 1000")"
}
}
Imagine your whole program being based on its maxUsers. Since, you give me the right to access that variable directly, I could do this: maxUsers = -15; and not use the setMaxUsers method, which will simply make your program behave in an abnormal way (in the best case).
Explanations
A private member is only accessible within the same class as it is declared.
A member with no access modifier is only accessible within classes in the same package.
or
If a variable is set to protected inside a Class, it will be accessible from its sub classes defined in the same classes or different package only via Inheritance.
A protected member is accessible within all classes in the same package and within subclasses in other packages.
A public member is accessible to all classes (unless it resides in a module that does not export the package it is declared in
Here's a better version of the table. (Future proof with a column for modules.)
I want to get my head around the idea of using setters and getters in superclass and subclass in terms of software good practices.
From your experience, which method of the below are appropriate and also promote good software re-usability:
declaring a protected instance variables in the superclass and let the subclass uses them.
declaring a private instance variables in the superclass with public getter methods to let the subclass inherits the getter methods from the superclass.
Depends on your style of coding. Some prefer concise code over more verbose structured code. If your ultimate goal is interoperability and scalability, you're 'safer' using getters/setters. Another advantage is with the getters/setters you can perform multiple operations instead of only a single operation, for instance getUsers() may actually tabulate multiple data rows. This way you can consolidate that operation instead having to repeat it in subclasses.
Use your best judgement. If the values are simple booleans or strings, probably don't need a g/s. If they're query related or make specific, repeated modifications to state or data, use a g/s approach.
Both methods are acceptable. Normally, I would have public getter/setter methods since anyone can use them, not just subclasses.
I pick number 1. That's exactly the situation where the existence of protected is justified. Getters and setters are for classes using another non-related class.
I pick 1 mostly when I am going to create an abstract class.
Otherwise, I always pick 2 (creating getter/setter). Because:
Not only that avoid any accidental/unintended modification to
class's member variable, it also help when you will go about
creating jUnit test-cases for your classes.
Decouple the classes.
Any good book on Object Oriented Programming will list other benefits of using getter and setter.
I am writing a game and I have a class for the input which contains booleans for all the different keys. I create an instance of this class in the main game class. Is it ok for the booleans to be public, or should I access them with accessors?
Instead of having a boolean for each key, it would be more readable and easier to code if you had a private Map<String, Boolean> keyStates, with all keys initialized to false. Then your accessors might be:
public void setPressed(String keyName) {
keyStates.put(keyName, true);
}
public void setReleased(String keyName) {
keyStates.put(keyName, false);
}
public boolean isPressed(String keyName) {
return keyStates.get(keyName);
}
The general reason for having accessor methods rather than public variables is that it allows the class to change its implementation without requiring changes in the classes that interact with its members. For example, with the above, you can now add code to count or log key presses, or change the underlying type of Map used, without exposing any of this to the outside.
This is not personal preference. Encapsulation and Interfaces are integral parts of OO Software Engineering, and are the primary design reasons that the Internet is possible from a technical POV.
Generally I would recommend using getters and setters as it is cleaner, more organized, and more readable. This will also help if you have a lot of different programmers looking at your code. My outlook is to always make your variables private unless you need to expose them for a specific reason. If performance is really an issue in your game then making your variables public will help a little by reducing function calls.
It's mainly a personal taste thing - I'm sure you'll find people arguing on both sides, and I'd say it's not black or white but depends on how "big" the class is.
The rationale for using getters and setters is so that you abstract out the actual representation as a field, in order to give you the freedom to start presenting this as e.g. a derived value without changing your interface. So really it comes down to how valuable the interface to this class is to you.
If it's part of your first-class public interface, then definitely use getters and setters. At the other extreme, if it's a simple data holder like a tuple that's used solely within a single class (e.g. to map database rows before transformation into another class), then I wouldn't hesitate to use fields; there's no real value to the interface as it's only being used internally.
So how many classes/packages would use this class? If it's a private, "local" class then I don't think there's anything wrong with just using the fields, and updating your callers if this ever needs to change.
Accessing fields is much easier to justify if they're final too, which is often the case with this sort of object.
It's not bad, but usually you'll want to encapsulate the state of an object.
Standard practice is to make member variables either protected or private with getters/setters that follow java bean convention. This tends to be somewhat verbose, but there is a very nice library (www.projectlombok.org) out there that generates the getters/setters/constructors/toString/hashCode/equals methods for you.
It is always a good java programming practice to declare the class variables as private and access them with public getter and setter methods unless its really needed to declare them as public .
If you are using an IDE , then its just a click away to generate getters and setters for class variables/member variables .
And now that you have been told over and over to use getter and setters, and because you are in Java (where IDEs help you make getters/setters trivially, and everyone clearly uses them), read over this thread to help add some balance to your usage of them:
Getters and Setters are bad OO design?
What is the "correct" way to access an object's properties from within an object method that is not a getter/setter method?
Getter/Setter is the recommended way of accessing properties of an object. Otherwise you to have to use public properties, but public properties are not recommended.
If a classes' properties don't have getters and they are not visible (e.g. not public), that means that the class is designed so that you can't access them. In that case, there is no proper way to access them.
Flipping this around, if you are designing a class and you intend that other classes can access its attributes, you ought to provide getters. You could alternatively declare the attributes to be public, protected or package private, but that makes your abstraction leaky and has a number of undesirable consequences.
If you are asking how one of an object's methods should access its own attributes, the simple answer is whichever way is most convenient. If the class has getters, you could call them. Alternatively, you could just access the attributes directly. The problems of leaky abstraction don't apply in this case because the method accessing the state is inside the abstraction boundary.
This is mostly a matter of preference.
I personally prefer not to use the getters and setters in my object. This increases readability, allows me to change my getters and settings to return copies (of lists mostly) without it changing my own object. If you do something special in your getter then you can make a helper method that is used by both your getter and your other functions. This will go wrong if your classes get too large though (so don't make large classes). I don't like how using a getter setter hides the side effects inside the object (unlike for external users, they should be hidden from any side effects inside the object), when you want to have the side effects, give the private method a clear name indiciting it has them.
First off I'll answer the question as is:
What is the "correct" way to access an object's properties from within an object method that is not a getter/setter method?
When you are within an object, you can reference the properties directly where the method is part of the object. For example:
public class testClass() {
public int x;
private someMethod() {
x = 4;
}
}
To answer the comment:
I think the question can be reformulated: Should I use getters and setters when implementing my object methods? Or should I access member variables directly?
You should always hide the internal data and other implementation details within a class as much as possible; seperating the API from the implementation (a.k.a encapsulation). Encapsulation decouples the modules thereby allowing them to be developed, tested and modified in isolation.
Generally, you should use the lowest access modifier possible (e.g. private, protected, package-private) whilst maintaining functionality for the application you're writing. The benefits of designing and devloping this way is that you can change implementation details without breaking code that uses the modules. If you make everything public, and other people are using your classes, you are forced to support it forever maintaining compatibility - or until they change their implementation that is using your modules.
Instance fields should never be public as you give up the ability to limit the values that can be stored in the field, and if it is a mutable object, you open your object up for misuse (see here). It is important to note too that classes with public mutable fields are not thread-safe. It is also important to note that instance fields that are declared public static final but are mutable objects can also be modified and can be a security risk.
Basically, in public classes - always use accessor methods, not public fields. It allows you to protect your mutable objects from modification outside of the class (be it intentionally or unintentionally) and allows you to change implementation detail later without harming your clients.