I have a singleton class containing a bunch of control data that needs to be kept synchronized with the rest of my application. As a result, there are many times which I want another class to be able to read the information but not modify it. Currently, this singleton class has many public variables. I don't want to use getter and setter functions because they are wordy and annoying. Also, there are a lot of variables.
If my singleton class is called ControlData, I could create a second create a second class called ImmutableControlData, where it has all the same members, but they are declared final. Then, when retrieving my singleton, I would return an ImmutableControlData, rather than a ControlData object. However, this means that I need to constantly maintain the ImmutableControlData class as well as the ControlData class (annoying...)
If I had const-pointers, I would just return a const-pointer to my ControlData object. What can I do in Java, instead?
Java does not have const correctness like C++.
You could make an interface that declares the methods to read the data, but not the methods to modify the data. Make the class that holds the data implement this interface. Methods elsewhere in your program that should only read the data, should accept the interface, not the class, as the parameter type. For example:
public interface ReadablePerson {
String getName();
}
public class Person implements ReadablePerson {
private String name;
#Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// Elsewhere...
public void someMethod(ReadablePerson p) {
System.out.println(p.getName());
}
Ofcourse, in someMethod you could still subvert this by casting p to Person, but at least it requires some conscious effort (adding the cast), which should alert the programmer that (s)he is doing something (s)he shouldn't do.
An advantage of this solution is that you don't have to make a defensive copy of the data.
First: If your Class has so many members, you should try to split the class into littler ones. Maybe you can summerize some variables eg.
ControlflowVariables
StateVariables
If you want to restrict the access to the variables you have to use getter. IDE can create getters and setters for you. The access to variables are the same:
singletonClass.variable is not worst then singletonClass.getVariable()
If you want to restrict the access only at some points in your code then create a final copy of tha variable
final int variable = singletonClass.getInstance().variable;
Personally, I would not try to control access in this way. There is nothing you can to do to prevent bad programmers from misusing your class. Even in C++, they could use a simple const_cast to remove your "protection" and modify the singleton any way they like.
Instead, I would restructure the code to make it easy for others to do the right thing and hard for them to get it wrong. Segregate the interface for ControlData into two separate interfaces: one for reading the object and one for updating it. Then simply provide the two interfaces where they're needed.
Related
We can access Private data members using accessor method such as
private int num=5;
public int get_num()
{
return num;
}
and we can access the returned value from any class even though num is private data member.
So on Similar note cant we create accessor method that returns private methods?
I just had a thought about it,If we cannot do this please explain.Thank You
Private methods are created when refactoring your code. They are implementation details, which nobody outside needs to know. They are used inside public methods, which are supposed to provide the functionality you want to provide to your client(each public method can be called an API which is used/consumed by other classes i.e. its clients).
Access modifiers are provided to help you achieve proper abstraction. So anything marked private is directly accessible only inside your class. But if you want someone outside to read/write its value, you expose it via getters/setters. Similarly private methods are not accessible outside the class. But nobody is stopping you from creating public method that only calls this private method. This way you do achieve access to private method. But it would be a very poor design.
You can access private method via public method. This is sometimes used to wrap complicated private method and expose simpler, public API.
class Delegator {
private void doPrivateStuff(int param) { ... }
public void doStuffOnce() {
doPrivateStuff(1);
}
public void doStuffIfConditionIsMet() {
if(condition) {
doPrivateStuff(1);
}
}
}
You can also access private methods using reflection.
http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html
Because the accessor is public, it can be accessed from outside the class; even if it returns private data.
The access modifier of the returned data isn't relevant, only the access modifier of the method matters.
If you created a public method that returned a reference to a private method, yes, you could then call the private method from outside the class. That would entirely defeat the purpose of making the method private however.
You my be wondering "why make a public getter to a private variable". The answer is that although it's possible to retrieve the private data, it isn't possible (unless you create a public setter as well) to change the public data. This assumes that the private days is immutable. If it's mutable, retuning a reference to private data negates any protection you get from making the variable private.
TL;DR
Accessing private methods violates the basic object oriented principle of encapsulation. The question is not "can we access a private method?" but "should we ever do it?". It contradicts the principle of information hiding and it breaks the contract an object "offers" to its consumers. Objects or classes that enforce you to do that should be considered poorly designed.
Why you shouldn't access private members
First a classes should implement a part of your domain logic that is so closely related that there are little interactions necessary with the outside world to fulfill its duties (this is called high cohesion). You then define a public interface for your class / object with functionality that you expose to the outside world - consumers of your object must only use this interface (this is called loose coupling).
Private methods can be seen as a way to structure your code inside your class in a better readable way - they are not intended to be shared with the outside world. Consider them as a "safe space" for the developer of the class to make arbitrary changes without breaking the contract. That's the reason why there can be bad side effects if you actually access private methods: your code is likely to break it the developer of the class decides to change the implementation of such a method. Effective Java, Chapter 4, Item 13 explains this for protected members:
For members of public classes, a huge increase in accessibility occurs when the access level goes from package-private to protected. A protected member is part of the class's exported API and must be supported forever. Also, a protected member of an exported class represents a public commitment to an implementation detail.
Exceptions
The only exception I know from the rule of "not accessing private members outside of an object" is in testing, when you either want to reset a certain variable (e.g. a Singleton) or you want to facilitate the testing of complex logic by testing the private parts of the implementation and hence reducing complexity in testing.
I have more than 20 commonly used methods in my application. I would like to move that 20 methods into a common class.
Here my doubt is, define all the methods are static or normal method and create a global object to access that normal methods.
class Common {
public String method1() {........}
public String method2() {........}
public String method3() {........}
public String method4() {........}
public String method5() {........}
...
}
Creating object.
class CommonService {
private static Common common;
public static Common getCommon() {
if(null == common) {
common = new common();
}
return common;
}
}
If we create all the methods using static means, all 20 methods are stored in PermGen section of the heap.
But if we follow above method means, only one object can be created and stored in java heap.
Please clarify which one is the best way.
If we create all the methods using static means, all 20 methods are stored in PermGen section of the heap.
Methods are not data, but code. Where code is stored does not depend on whether a method accepts an implicit this parameter or not. If you use the singleton approach, method code will still occupy storage and additionally there will be an instance on the heap.
However, all of the above is irrelevant and you are focusing on a completely wrong aspect of your design. What matters is how the decision will affect the code which uses these methods:
static methods are simple and a great choice for pure functions (which don't depend on any external state);
singletons allow polymorphism, therefore make the methods easier to mock for testing.
You should think about the "best" way in terms of design.
If the methods are used for general purposes, making them static is preferable, as you won't have any state to store and you'll save memory this way.
You should consider other things before deciding if you want to use static methods in your utility class or not. On one hand the utility class will be very easy to test, and it's highly accessible. On the other hand, it's very hard to mock static methods in your test.
If I have a utility class, I would write it as follows:
public final class Common {
private Common() { }
public static int method1() { }
public static int method2() { }
// ...
}
"Common functions" is not quite accurate. It really depends on what you want to do, for example when I make some string utils I make StringUtils class and it has what I need. Whether to make it static or not depends on data to be processed, if one information might be used more than once for a call then answer is simple - use instances.
That depends on what the methods do.
If those methods are just helper methods, that do not alter state then static is probably better because that way you do not have to create an object every time you want to use one of the methods. You can just call Common.method()
However, if the object has state then you should rater use object methods and create a new object when you want to use the methods.
Hope this helps.
If sense of this method is "execute pure function" like mathematical sin(x), cos(x) etc static method is the best.
They belongs to one domain? (range of themats) or to different? (then create more "utility classes" with correct name)
If have state (like many people say) maybe better is singleton.
Shape of the question "i have 20 method in application" and name Common suggest previous (older) design problem, I say "procedural thinking", poor vision of OOP.
Hard to say without code.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why use getters and setters?
This is a newbie question. Is it very much necessary to use getmethods to access property values? Once the value has been assigned, one can get the values directory. For example, in the below code, displayName() can display firstName value without the help of any getter method. Or it is a standard coding standards that one must have getter and setter method or any other methods which gives that value?
class Test{
private String firstName;
public void setName(String fname){
firstName = fname;
}
public void displayName() {
System.out.println("Your name is " + firstName);
}
}
Tell, Don't Ask is an important principle in object-oriented design. Generally you should tell objects to do things rather than ask them questions. getters/setters every where discourage this practise because you are encouraged to reach inside an object and get to the fields (or even worse reach in and poke things about in the case of setters). This breaks encapsulation and makes your code harder to reason about.
In your particular case, I'd create an object called Name that has a constructor taking the name and single method to display it.
In Your case (to display the display name) it is not neccessary to provide Getter.
But if your want use the field in another class We need to provide the Getter method.
Getter and setters are a part of the standard interface for Java Beans and many frameworks like Hibernate expect them in place. That being said it is of course up to you to decide if and when you need them and for what purpose. They provide access to your private member variables and they can even give you the chance to do more than just plain get and set.
The point of OO software is reuse. This means that other programmers, or you years from now, can use the code for other systems.
When you have private member variables, and use get/set functions, you can change the internal implementation of the function without breaking all the other code that uses it.
Do always use Getter and Setter to access your properties!
You should take a look at this article...
Having private state, encapsulation is good, and in A LOT of cases this is the right thing. Suppose that your class is suppose to be Thread Safe, having public fields you can't ensure that.
On the other hand there are cases when this is useless! Suppose that you access your object only in one package, you are sure you will never export it, then why bother?
I do not have any links to support this, but it's what I do.
I try to avoid public fields if they are not static. So I just use protected and private fields. From within the class, you can access them without get/set, that's completely fine. From outside the class, always try to use get/set.
So your example code is completely fine to me. :)
EDIT: One exception for me is if I create a struct-like container class like this
class Point4D {
public int x1, x2, x3, x4;
}
Then I think that public fields are ok. It would be still better to make them private and name the getters public int x1() etc though. As soon as some methods are introduced to this container that change the state of the instance (like changing the values of x1/x2/x3/x4), I make them private and add get/set.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why use getters and setters?
I have read books on Java, saying that it is good to create setters and getters for variables such as x and y. For example:
public int getX(){
return x;
}
public void setX(int x){
this.x = x;
}
But what is the difference from that and
...(shape.x)... // Basically getX()
and
shape.x = 90; // Basically setX()
If setters and getters are better, what practical problems would arise?
Multiple reasons:
If you allow field access like
shape.x = 90
then you cannot add any logic in future to validate the data.
say if x cannot be less than 100 you cannot do it, however if you had setters like
public void setShapeValue(int shapeValue){
if(shapeValue < 100){
//do something here like throw exception.
}
}
You cannot add something like copy on write logic (see CopyOnWriteArrayList)
Another reason is for accessing fields outside your class you will have to mark them public, protected or default, and thus you loose control. When data is very much internal to the class breaking Encapsulation and in general OOPS methodology.
Though for constants like
public final String SOMETHING = "SOMETHING";
you will allow field access as they cannot be changed, for instance variable you will place them with getters, setters.
Another scenario is when you want your Class to be immutable, if you allow field access then you are breaking the immutability of your class since values can be changed. But if you carefully design your class with getters and no setters you keep the immutability intact.
Though in such cases you have to be careful in getter method to ensure you don't give out reference of objects(in case your class have object as instances).
We can use the private variables in any package using getters and setters.
Using getter and setter functions allow for constraints and encapsulation. Lets say x is the radius. shape.x = -10 would not make much sense. Also, if someone tries to set an illegal value, you can print an error, set a default value, or do nothing.
It is good practice to make member variables private so they cannot be modified directly by programs using them.
Mutator functions
Encapsulation
A lot of people have mentioned encapsulating the specifics of the implementation, which to me is the biggest reason to use getters and setters in a class. With this, you also get a lot of other benefits, including the ability to throw out and replace the implementation on a whim without needing to touch every piece of code that uses your class. In a small project, that's not a big benefit, but if your code ends up as a well-used (internal or public) library, it can be a huge benefit.
One specific example: complex numbers in mathematics. Some languages have them as a language or framework feature, others don't. I will use a mutable class as an example here, but it could just as easily be immutable.
A complex number can be written on the form a + bi with real and imaginary parts, lending itself well to [gs]etRealPart and [gs]etImaginaryPart.
However, in some cases it's easier to reason about complex numbers on polar form re^(iθ), giving [gs]etRadius (r) and [gs]etAngle (θ).
You can also expose methods like [gs]etComplexNumber(realPart, imaginaryPart) and [gs]etComplexNumber(radius, angle). Depending on the argument types these may or may not need different names, but then the class' consumer can use either as fits its needs.
The two forms are interchangeable; you can fairly easily convert from one to the other, so which form the class uses for internal storage is irrelevant to consumers of that class. However, consumers may use either form. If you choose the form a+bi for internal representation, and expose that using fields rather than getters and setters, not only do you force the class consumers to use that form, you also cannot later easily change your mind and replace the internal representation with re^(iθ) because that turns out to be easier to implement in your particular scenario. You're stuck with the public API you have defined, which mandates that specifically the real and imaginary parts are exposed using specific field names.
One of the best reasons I can think of for getters and setters is the permanence of a class's API. In languages like python you can access members by their name and switch them to methods later. Because functions behave differently than members in java once you access a property thats it. Restricting its scope later breaks the client.
By providing getters and setters a programmer has the flexibility to modify members and behavior freely as long as the adhere to the contract described by the public API.
Another good reason to user getter and setter can be understand by the following example
public class TestGetterSetter{
private String name ;
public void setName(String name){
this.name = name ;
}
public String getName(){
return this.name ;
}
}
The point of getters and setters is that only they are meant to be used to access the private variable, which they are getting or setting. This way you provide encapsulation and it will be much easier to refactor or modify your code later.
Imagine you use name instead of its getter. Then if you want to add something like a default (say the default name is 'Guest' if it wasn't set before), then you'll have to modify both the getter and the sayName function.
public class TestGetterSetter{
private String name ;
public void setName(String name){
this.name = name ;
}
public String getName(){
if (this.name == null ){
setName("Guest");
}
return this.name ;
}
}
There is no requirement for getters and setter to start with get and set - they are just normal member functions. However it's a convention to do that. (especially if you use Java Beans)
Let's say, hypothetically, you find a library that does a better job of what you have been doing in your own class (YourClass). The natural thing to do at this point is to make YourClass a wrapper interface to that library. It still has a concept of "X" which your client code needs to get or set. Naturally, at this point you pretty much have to write the accessor functions.
If you neglected to use accessor functions and let your client code access YourClass.x directly, you would now have to rewrite all of your client code that ever touched YourClass.x. But if you were using YourClass.getX() and YourClass.setX() from the beginning, you will only need to rewrite YourClass.
One of the key concepts of programming, and especially object oriented programming, is hiding implementation details so that they're not used directly by code in other classes or modules. This way, if you ever change the implementation details (as in the example above), the client code doesn't know the difference and doesn't have to be modified. For all your client code knows, "x" might be a variable, or it might be a value that is calculated on the fly.
This is an oversimplification and doesn't cover all the scenarios where hiding implementation is beneficial, but it is the most obvious example. The concept of hiding implementation details is pretty strongly tied to OOP now, but you can find discussions of it going back decades before OOP was dreamed up. It goes back to one of the core concepts of software development, which is to take a big nebulous problem, and divide it into small well-defined problems which can be solved easily. Accessor functions help keep your small sub-tasks separate and well-defined: The less your classes know about each other's internals, the better.
There are lots of reasons. Here are just a few.
Accessors, getters in particular, often appear in interfaces. You can't stipulate a member variable in an interface.
Once you expose this member variable, you can't change your mind about how it's implemented. For example, if you see a need later to switch to a pattern like aggregation, where you want the "x" property to actually come from some nested object, you end up having to copy that value and try to keep it in sync. Not good.
Most of the time you are much better off not exposing the setter. You can't do that with public fields like x.
Before get into the answer, we gotta know something prior...! "JavaBeans".
JavaBeans are java classes that have properties. For our purpose, think of properties as private instance variables. since they're private, the only way they can be accessed
from outside of their class is through 'methods'in the class.
The methods that change a propertiy's value are called setter methods, and the methods that retrieve a property's value are called getter methods.
I would say that neither the getters/setters nor the public members are good Object Oriented design. They both break OOP Encapsulation by exposing an objects data to the world that probably shouldn't be accessing the properties of the object in the first place.
This is done by applying the encapsulation principle of OOP.
A language mechanism for restricting access to some of the object's components.
This means, you must define the visibility for the attributes and methods of your classes. There are 3 common visibilities:
Private: Only the class can see and use the attributes/methods.
Protected: Only the class and its children can see and use the attributes/methods.
Public: Every class can see and use the attributes/methods.
When you declare private/protected attributes, you are encouraged to create methods to obtain the value (get) and change the value (set). One example about visibility is the [ArrayList][2] class: it has a size property to know the actual size of the inner array. Only the class must change its value, so the code is something like
public class ArrayList<E> {
private int size;
private Object[] array;
public getSize() {
return this.size;
}
public void add(E element) {
//logic to add the element in the array...
this.size++;
}
}
In this example, you can see that the size value can change only inside the class methods, and you can get the actual size by calling it in your code (not mutating it):
public void someMethod() {
List<String> ls = new ArrayList<String>();
//adding values
ls.add("Hello");
ls.add("World");
for(int i = 0; i < ls.size(); i++) {
System.out.println(ls.get(i));
}
}
Getters and setters encapsulate the fields of a class by making them accessible only through its public methods and keep the values themselves private. That is considered a good OO principle.
Granted, it often seems like redundant code if it does nothing more than setting or returning a value. However, setters also allow you to do input validation or cleanup. Having that in one place improves data integrity for your objects,
Because we are using Object oriented programming language.
Here we are using Data hiding and encapsulation.
The variable should not directly accessible from out side world (for achiving data hiding) so we will create it private so
shape.x
is not correct.
Getter and setter method are used to get and set the value of x which is the way to achive encapsulation.
My question involves specifically Java, abstract classes, and the use of protected data. I am being told that all the data should be private, and protected getters/setters used only.
Now, I understand we want to shield data from direct manipulation by casual users of the class, and that public data members in general are a questionable practice. I have looked at "Java protected fields vs public getters" ( Java protected fields vs public getters ), but I still am dubious that:
protected int i;
is worse in an abstract class than:
private int i;
protected int geti();
protected void seti(int j);
I am just not seeing the down side when the abstract class is there precisely to provide parent/common facility to the children classes, and the protected scope is meant to provide access to children, while protecting the data from casual users. I note in the question referenced above, that most of the answers seem to address the issue of why data in general should be private rather than public. I am trying to focus my question specifically on data existing in an abstract parent intended for use by the children. The sole reasonable comment I have heard to date is that using the parents protected data (e.g., int i above) leaves you with code in the child class that references a variable not declared in the child class. Less compelling is the argument (see Common protected data member in base class? ) that you may want to change the access some day, and now you have to honor your interface. This is an abstract class, and is intended to be extended 100% of the time.
Thanks! Specific Title/page# references to books are far more helpful that references to "..any basic Java programming text..."
========================================== 10-13-2010
This was as much a question about abstract classes as it is about protected data. I find it disappointing that the focus seems to have shifted in the responses to whether data hiding is a good thing in OOP (answer: yes). There's a lot of depth here involving the nature of the abstract class, and how it differs from a regular non-final class, and what possible advantages there might be for fixing the names and types of data-items in the abstract parent for use by the child classes. I think there is the possibility here for innovation and greater control being extended down from the abstract parent to the implementing child classes. I am concerned that general principles, such as the advantages of data-hiding, can become dogma, and inhibit innovation and the development of new patterns and ideas.
Thanks to all who contributed.
If the field is private and access is through getters and setters, you will be able to reimplement getters and setters (for instance, dropping the field and updating/reading the value from an external source), and thus change how the "field" works without touching any child classes.
Whether this is worth it, that's up to you.
Think of protected methods as an interface for subclasses, in the same way that public methods are an interface for everyone else.
Providing accessors enables the base class to maintain its state: there's no way a subclass would corrupt it without an intentional trick.
Having less access isn't a drawback, it's a benefit. Classes should always limit access to as much of their internal state as possible. Don't think of why internals should be hidden, instead think of why they should be exposed. In this case as in every case, unless there is a really good reason to expose the variable then don't expose it.
In Java protected members are accessible to all members in the same package in addition to any extending classes. Making the field private will prevent classes in the same package from directly accessing it.
As well there is the point that alex raised earlier.
If you don't need your child to directly access it, why would you let them ?
It isn't a down side to use protected. But if it isn't necessary, maybe it's better to avoid it and control access on your fields.
If someone subclasses your class, and puts the subclass in the same package as your current class, they may want to override your getters and setters. For example, they wantto make sure that i may only be set to a value greater than 1.
Other than that, it's really up to you. The convention is that there are getters and setters for everything though.
Information hiding is valuable, even among classes related by inheritance.
In addition to allowing re-implementation, as noted by alex above:
You can set breakpoints in methods.
You can add constraints in one place.
You want to use getters/setters because using protected int i; allows for field overriding (which you want to avoid at all costs).
You want to disallow field overriding because it works differently than method overriding. Field overriding does not make the overridden field inaccessible (the type of the reference determines which instance of the field you are working with).
Accessible fields should be final or in a class that is final.
public class OverridingFun {
public static class Base {
public int i = 1;
public int getI(){ return i; }
}
public static class A extends Base {
public int i = 2;
public int getI(){ return i; }
}
public static class B extends A {
public int i = 3;
public int getI(){ return i; }
}
public static void main(String [] args){
B b = new B();
A bAsA = b;
Base bAsBase = b;
System.out.println(b.getI());//3
System.out.println(bAsA.getI());//3
System.out.println(bAsBase.getI());//3
System.out.println(b.i);//3
System.out.println(bAsA.i);//2
System.out.println(bAsBase.i);//1
b.i = 4;
bAsA.i = 5;
bAsBase.i = 6;
System.out.println(b.i);//4
System.out.println(bAsA.i);//5
System.out.println(bAsBase.i);//6
}
}
At first glance this looks like something that would just make code hard to read but it has implications on functionality. Say the field does get overridden by a derived class, since setters are not being used, there is no way to automagically update the base field and no way to detect if someone has changed the base field (since the base value is still accessible) and update the derived field. It's easy to imagine that the base and derived states could get out of sync and that the errors would be hard to track down. Simply put it makes for a very brittle API.
Unfortunately there is no way to guard against this since the final keyword, which protects against overriding, also makes fields write-once. So no writable non-overloadable fields.
Personally I'm rather surprised the language designers allowed field overriding at all. The advantage of using setters is that each level can guaranty the integrity of it's own state and trust that derived classes haven't fouled it up. Field overriding is just asking for trouble.