Related
This question already has answers here:
Why make defensive copies in getters inside immutable classes?
(7 answers)
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 3 years ago.
I'm learning Java and I have some doubts.
If defined a class with a private variable like
class test<A>{
private A var;
...
public A get(){
return var;
}
}
Is the get method wrong?
I think so because with this definition I can modify the variable "var" like
test<A> x = new test<A>();
A temp = x.get();
temp.set(*something*);
At the end x is changed (I tested it using Vector as A). If I understand correctly, this works because object reference (I miss C pointers, sob). Am I wrong? Maybe I don't understand the purpose of the keyword "private"! Thanks in advance!
Edit: I have no problems with "pass-by-reference" and "pass-by-value". I have doubts defining get() method for a private variable in a class (you don't say?). Please stop linking Is Java "pass-by-reference" or "pass-by-value"?
If your getter method is returning a reference to a mutable object, then this greatly weakens the quality of the encapsulation provided by your class, because it becomes possible to modify the state of an instance of your class without calling a method of the class.
One standard strategy to guard against this problem is what J. Bloch calls defensive copies (Effective Java, 3rd edition, Item 50: "Make defensive copies when needed").
This would mean creating a copy of var in the getter method, and returning that copy instead. How to do this depends on the design of A.
Because A is a type parameter, making a copy of the instance requires additional support in the design. To see how to achieve this using Java's cloning mechanism, see my answer to the post "Does it make sense to create a Copyable type interface instead of using Cloneable?".
If this is a problem, you can create a façade to protect your variable
public class Facade extends A {
A myObj;
public Facade (A obj) {
myObj =
}
public A get(){
return myObj.get();
}
public B set(Object val) {
throw new RuntimeException("Setting is not allowed");
}
}
This might be a bit too much detail for just starting, but you might review class java.util.concurrent.atomic.AtomicReference<V>, which is very similar to your example.
Generally speaking, placing instance variables in private variables, while providing access to the variable using a getter and a setter, is standard practice.
Note that your class name should be capitalized, type parameter 'V' is more standard, and the variable name would more usually be 'value'. Also, try to pick a more communicative name for the class. (Type parameter type variable could be 'ValueType', which would fit some preferences. But, single character type variable names are more usual.)
public class Wrapper<V> {
private V value;
public V get() {
return value;
}
public void set(V value) {
this.value = value;
}
}
I'd add some other point here: as others have said, you hand out the object reference and it can be modified, which could be bad.
Object orientation is about keeping the data and the code that works on it in one place. If you need getters, think what the callers of the getters need to do, and whether that action should rather be a method on the class that has the data. Your code could suffer from the Feature Envy code smell, as it violates the Tell, Don't Ask principle.
To fix this, remove the getter, and introduce new methods as needed. For example, if you have some data object that needs to get printed, you could pass the Printer to the object and have it print itself to the given Printer.
If you're dealing with a collection class (just a guess from your template parameter), you may need to keep the getter, but then you're probably not concerned with the caller changing the value anyway.
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 7 years ago.
Why do we exactly need to use the set and get methods in our class that use private attributes?
When it is really used during our program process?
Can we still make it work without it (without changing the private attributes to public)?
This is an example of a source code when we are using the set and get methods:
public class Dog {
private String dogName;
private int dogAge;
public Dog(String dogName, int dogAge) {
this.dogName = dogName;
this.dogAge = dogAge;
}
public String getDogName() {
return dogName;
}
public void setDogName(String dogName) {
this.dogName = dogName;
}
public int getDogAge() {
return dogAge;
}
public void setDogAge(int dogAge) {
this.dogAge = dogAge;
}
#Override
public String toString() {
return "Dog{" + "dogName=" + dogName + ", dogAge=" + dogAge + '}';
}
}
Why do we exactly need to use the set and get methods in our class
that use private attributes?
If you want to hide details of implementation (encapsulation - a fundamental principle of object-oriented programming), you don't want someone from outside to access them, you only supply a method that returns some value, but you don't want to reveal implementation.
Also sometimes when you set a value, you need to change other variables that might be related, or changing some logic, it's not always a simple assignment statement.
When it is really used during our program process?
It's very hard to answer this question, it really depends on the program. You use setters and getters when you want to.. get, or set a value.
Can we still make it work without it?
Sure, it works when you have public fields instead of privates, in sense of design, it's recommended to start with private variables always, and change them only when you must.
If you don't see the point of encapsulation, allow me to demonstrate with a "real life" example (which .
private boolean amIDrunk = true;
public boolean getAmIDrunk(Object asker){
if (asker instanceof PoliceOfficer){
return false;
} else if (asker instanceof DrinkingBuddy ){
return true;
}
return amIDrunk;
}
public void setAmIDrunk(boolean setter){
if (hadLessThen10Beers()) {
this.amIDrunk = false;
return;
}
this.amIDrunk = setter;
}
Sure, this is a 'nitwit' example, but it's just to show that sometimes, just because you call a setter, there might be a reason not to set that value, and sometimes, when a getter is called, there might be a reason, you don't want to return the actual value.
Anyway, to continue in this example: having amIDrunk as a private variable, makes sure someone else doesn't declare you as 'drunk' by setting amIDrunk to true, without the implementation of your own set method to agree with it.
I personally don't like the setters and getters and replace them with public fields if I can. However, there are techical reasons to keep them:
Mocking: Mocking frameworks such as Mockito or Easymock cannot mock or override direct field accesses
Proxies: For various reasons, proxies are used (Scopin in DI frameworks, logging, etc). Again, does not work with fields
JavaBeans based frameworks: Some frameworks for XML serialization don't support field access.
So, in many cases using the getters/setters just makes your life easier. However, if you are in charge of all code depending on your classes, just use Refactor->Encapsulate Field in eclipse (quite sure similar functionality exists in all major IDEs) as soon as you run into problems.
I recommend to read about Kotlin kotlinlang.org
You can write getters/setters for POJO in 1 line:
e.g.
data class Customer(val name: String, val email: String, val company: String)
Another reason for using 'access methods' (setters and getters) is that it is a convention used in IoC (inversion of control). So frameworks like Spring etc.
It may seem tedious to create them, but if you're using eclipse as an IDE for example you can generate setters and getters automatically (source|generate getters and setters).
Further your private member variables are important.
Let's say you have :
public String telephoneNumber;
What is to stop someone doing this :
object.telephoneNumber = "not a telephone number".
If you used a setter you could do this :
public void setTelephoneNumber(final String telephoneNumber) {
if (telephoneNumber==null||telephoneNumber.length()==0) {
throw new IllegalArgumentException("you cannot supply null telephone numbers");
}
... etc.
this.telephoneNumber = telephoneNumber;
}
In this manner your telephoneNumber member variable will only ever hold a valid telephoneNumber. Your class is now totally self contained (encapsulated) because you are not relying on external classes to treat your member variables with respect.
Setters and getters are used to achieve Encapsulation.
Yes, we can make it work without setters and getters.
Why do we exactly need to use the set and get methods in our class that use private attributes?
The Getters() and Setters() methods called also Accessors and Mutators are used so we can acces the private fields in a class from outside.
public class myClass(){
public void newDog(){
Dog d=new Dog("Foxy", 2);
d.setDogAge(d.getDogAge()+1);//get the age of the dog and increment it
}
}
When it is really used during our program process?
They are used when we need to achieve read(with getters)/write(with setters) operations with our private fields(like in the previous Example).
Can we still make it work without it?
Yes, of course we can if we declare those fields as public(default case):
String dogName;
int dogAge;
And the prvious example will be:
public class myClass(){
public void newDog(){
Dog d=new Dog("Foxy", 2);
d.dogAge=d.dogAge+1;//get the age of the dog and increment it without getters and setters
}
}
Take a look at TutorialsPoint's Encapsulation Tutorial for further information.
Getters and setters are indeed for the principle of encapsulation, there is a good explanation in the answer here. According to convention getter and setters cannot add any functionality besides storing and retrieving the property. Since this is the only thing these methods do, there is a growing support for setting these variables to public and access them directly, without these methods. Since these methods just expose them publicly, there is no functional difference. For convention, and some frameworks, getters and setters are expected.
You can always let your IDE (Eclipse, IntelliJ, Netbeans) write the getters and setters for you. But if you want your code to be DRY and easy to read you can also consider using Lombok, which makes the getters and setters for you automatically.
Why do we exactly need to use the set and get methods in our class that use private attributes?
This term "Encapsulation" comes under Object oriented programming. Encapsulation is you hide the implementation but giving access.
When it is really used during our program process?
Getters are there to get some value where setters are to set a value. In your code you set Dogs name as a String and age as an int. Finally you have getters to get the set value.
Can we still make it work without it?
Yes. You can make it work by changing the private declared variables to public. Actually private keyword will make that variable visible only to the class where it is declared.
This gives you an in detail explanation about Objects.
http://docs.oracle.com/javase/tutorial/java/concepts/object.html
This question already has answers here:
Return multiple values from a Java method: why no n-tuple objects?
(7 answers)
Closed 8 years ago.
While working with Java Applications, I feel most of the times one question : Why Java doesn't support multiple return values of methods?
I know that people who designed Java, must have done thinking about this topic but I didn't get any answer or particular reason while thinking myself.
If all the values are of the same type, you can just return an array of them:
public String[] myMethod{} {}
If they are not, they you have multiple options:
The ugly one is to cast everything into an Object and return either:
public Object[] myMethod{} {}
or
public List<? extends Object> myMethod() {}
The problem with these implementations is you really don't know what's what in the object/list unless you look at the method implementation. So it can be a shortcut if you know noone else is going to use this.
There's cleaner but a bit more time consuming. But it's usually a good practice because carries more information:
Say you want to return two values, an int and a String. You need to design an object that represents those two (or more values):
public class MyResponse {
public String myString;
public int myInt;
}
And return an instance of MyResponse. Note that here I made the attributes public. There are multiple schools of thoughts around this. Some will prefer to make them private and add getter/setter methods. That's homework for you.
Conceptually Java method should acomplish only one action on data and return concrete result. If you could not decide what should return your method this is a cause of bad OOP design of the class.
If you just want to return a several objects (one type of objects) from method you should use collections or arrays as #mprivat said.
This question already has answers here:
Java Pass Method as Parameter
(17 answers)
Closed 8 years ago.
I'm trying to write a function, so I can pass a function as a parameter, such as
public class HashFunction {
private Function f;
public HashFunction(Function f) {
this.f=f;
}
public Integer hash(String s){
return f(s);
}
}
So I can write code like
new HashFunction(function(String s){ return s.charAt(0)+0; });
Like in javascript.
How can I do this?
Unlike many other modern languages, currently java doesn't syntactically support "floating chunks of code" (known as closures).
However, the concept may be achieved through the use of anonymous classes, which are "on the fly" implementation declarations that typically implement an interface, but can also extend a class.
Here's how you would code your example in java:
public interface Hasher {
int getHash(String s);
}
public class HashFunction {
private Hasher f;
public HashFunction(Hasher f) {
this.f=f;
}
public Integer hash(String s){
return f(s);
}
}
then to use:
new HashFunction(new Hasher() {
public int getHash(String s) {return s.charAt(0)+0;}
});
Passing functions as parameters is not possible in Java, unless they added it in a recent language change.
The Java pattern is to use so-called anonymous classes, which implement a member method which has the desired behavior.
For example, see:
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm
or
How are Anonymous (inner) classes used in Java?
I think you can use interface, the same way like Comparable or Comparator interface, or use annotation to mark some functions, and then use reflection to invoke them
Please check this
I can only second the other answers. Basically, it is not possible to pass real references to functions, like in JavaScript or Haskell, where "everything is a function".
However, if you want to have a little bit of "functional"-style programming in your code, take a look at the "Functional Java" library at http://functionaljava.org/
Maybe taking a look at Scala also can be helpful, as it runs in the JVM and is a very mature, upcoming and modern programming language. In Scala, you can pass functions and it would interoperate with your existing Java code, too. (There are functions, functors, monads, list comprehensions, ...)
functions are called methods in java. And you can pass them!!!
But this is advanced java. Use java.lang.reflection.Method to pass a method.
But you will not happy with that technique.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
For classes that have a long list of setters that are used frequently, I found this way very useful (although I have recently read about the Builder pattern in Effective Java that is kinda the same).
Basically, all setter methods return the object itself so then you can use code like this:
myClass
.setInt(1)
.setString("test")
.setBoolean(true);
Setters simply return this in the end:
public MyClass setInt(int anInt) {
// [snip]
return this;
}
What is your opinion? What are the pros and cons? Does this have any impact on performance?
Also referred to as the named parameter idiom in c++.
#pek
Chained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return this. If you're interested in this topic, there is a bunch of links and a simple example on Alex Miller's Java 7 page.
This is called a Fluent Interface, for reference.
Personally, I think it's a pretty neat idea, but a matter of taste really. I think jQuery works this way.
I wouldn't do it myself, because to me it muddies what a particular method does, and the method-chaining is of limited use to me over doing it longhand. It isn't going to send me into a quivering ball of rage and psychosis, though, which is always a good thing. :')
I wouldn't be concerned about performance; just ask Knuth.
I find this to be in poor style when used in setters. Immutable classes are usually a better fit for chaining, such as:
aWithB = myObject.withA(someA).withB(someB);
where myObject is of this class:
class MyClass {
withA(TypeA a) {
this.a.equals(a) ? this : new MyClass(this, a);
}
private MyClass(MyClass copy, TypeA a) {
this(copy);
this.a = a;
}
}
The builder pattern is also useful, since it allows the final object to be immutable while preventing the intermediate instances you would normally have to create when using this technique.
It makes sense for builders, where all you are going to do is set a load of stuff, create the real object and throw the builder away. For builders, you might as well get rid of the "set" part of the method name. Similarly, immutable types don't really need the "get".
Something thing = new SomethingBuilder()
.aProperty(wotsit)
.anotherProperty(somethingElse)
.create();
A useful trick (if you don't mind a ~2K runtime overhead per class) is to use the double brace idiom:
JFrame frame = new JFrame("My frame") {{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocation(frameTopLeft);
add(createContents());
pack();
setVisible(true);
}};
This idea is seen a lot in c++, it allows operations to be cascaded...
for example
std::cout << "this" << "is" << "cascading"
is where the stream method << returns an instance of itself (*this).
see this: http://www.java2s.com/Tutorial/Cpp/0180__Class/Cascadingmemberfunctioncallswiththethispointer.htm
I use to be a fan of the Java (and worse C#) practice of making getters and setters (get set properties) throughout an object. This use to be what I considered object oriented, but really this leads us just to exposing the guts and implementation of the object and not really taking advantage of encapsulation. There are times you can't get away from this (OR/M comes to mind), but in general the object should be set up and then perform its function. My dream objects tend to have one or two constructors, and maybe a half dozen functions that do work.
The reason for this is that once I started developing API's there is a real need to keep things simple. You really only want to add as much complexity as is required to get the job done, and getters and setters, while simple in themselves, add complexity in heaps when added in mass. What happens when I load setters i na different order? Anythign different? Are you sure?
#Dan again, for more complex situations (immutability comes in mind) the Builder Pattern is a great solution.
Also, I agree with you mostly in getters. I believe what you are saying is to mostly follow the "Tell don't ask" paradigm and I greatly agree. But that is oriented mostly at getters.
Lastly, all of the above are for classes that have a great deal of attributes. I don't see a reason for any if you only have less than, say, 7.
I ended up doing this a lot when working with the Apache POI excel library; I ended up writing helper methods that chained so I could apply formatting, data types, internal cell data, formulas, and cell positioning.
For stuff with lots of little tiny flyweight elements that need to have finicky little tweaks applied it works pretty well.
How To Use
/**
*
* #author sanjay
*/
public class NewClass {
private int left ;
private int top;
public void set(int x,int y)
{
left=x;
top=y;
}
public NewClass UP(int x)
{
top+=x;
return this;
}
public NewClass DOWN(int x)
{
top-=x;
return this;
}
public NewClass RIGHT(int x)
{
left+=x;
return this;
}
public NewClass LEFT(int x)
{
left-=x;
return this;
}
public void Display()
{
System.out.println("TOP:"+top);
System.out.println("\nLEFT\n:"+left);
}
}
public static void main(String[] args) {
// TODO code application logic here
NewClass test = new NewClass();
test.set(0,0);
test.Display();
test.UP(20).UP(45).DOWN(12).RIGHT(32).LEFT(20);
test.Display();
I agree with #Bernard that method chaining like this muddles the purpose of the setters. Instead I would suggest that if you are always creating chains of setters like this that you create a custom Constructor for your class so instead of
MyClass
.setInt(1)
.setString("test")
.setBoolean(true)
;
You do
new MyClass(1,"test",true);
This makes it more readable and you can use this to make your class immutable if you chose to.