Best practice for getters, one getter or several for different variables?

I'm relatively new to Android programming (~ 2 months) Do I need to have getters for dozens of different variables?

For example -

//Yes I realise that this isn't 'dozens' public float getX() { return position.x; } public float getY() { return position.y; } public float getWidth() { return width; } public float getHeight() { return height; } public float getRotation() { return rotation; } 

Although it is necessary, for example, to have different getters and setters for floats and strings, is this a bad practice, and if so, why is it so, to use something like a switch statement to return different variables?

 public float returnSomething(String theThing) { switch (theThing) { case "height": return height; case "rotation" : return rotation; case "width": return width; default: return 0; } } 

So, is the above code considered bad? If yes, explain why.

Thanks for any help, this is not a problem, since any of the methods works fine, I just don’t understand why people will use dozens of getters and setters if there is no good reason.

I believe the same question applies to setters

+8
java android setter getter
source share
7 answers

Because as soon as you do something like

 public float returnSomething(String theThing) { switch (theThing) { case "height": return height; case "rotation" : return rotation; case "width": return width; default: return 0; } } 

I can feel the following question for: "Why is my height always 0?"

And then a postcode like

 public class GameThingy { //... private void doStuff(GameObject gameObject) { float gravity = 5*gameObject.returnSomething("hieght"); gameObject.setSomething("velocyty", gravity+50); } } 

Technically, the moment you make a typo anywhere, you will have trouble finding the source of the problem. This, and you are lucky that all fields are float , they do not have to be.

Edit:. By the way, this is actually a typical problem in determining the field of interest in some database queries. As if necessary, specify the field you are looking for with String .

Real example of RealmQuery<T> .

A RealmQuery<T> as follows:

 RealmQuery<User> query = realm.where(User.class); // Add query conditions: query.equalTo("name", "John"); // Execute the query: RealmResults<User> result1 = query.findAll(); 

Where it is assumed that the User class looks something like this:

 public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } 

It is interesting to note that Realm creates a “proxy subclass” where they override the setName and getName (aka, you need getters / setters to make some systems work!) Suppose you have them!)

But the important thing is that you need to specify the name of the field "name" .

Everyone can make a typo later, or you just won’t remember the margins from your head. In this particular case, they tend to create a metamodel (that stores the field name for you) with the goal that you do not have to use strings to indicate field names. p>

For example, in the criteria API, instead of

 Root<Pet> pet = cq.from(Pet.class); cq.select(pet.get("name")); 

They have a metamodel:

 Root<Pet> pet = cq.from(Pet.class); cq.select(pet.get(Pet_.name)); 

Thus, it eliminates the need for String s.

And similarly to what I usually do with Realm, I create a “metamodel” (although now you can automatically generate it using RealmFieldNamesHelper ):

 public class User extends RealmObject { @PrimaryKey private long id; private String name; public static enum Fields { //this is the "metamodel" ID("id"), NAME("name"); private String fieldName; Fields(String fieldName) { this.fieldName = fieldName; } public String getField() { return fieldName; } @Override public String toString() { return getField(); } } } 

And so you can replace the request in this way

 RealmResults<User> result2 = realm.where(User.class) .equalTo(User.Fields.NAME.getField(), "John") .or() .equalTo(User.Fields.NAME.getField(), "Peter") .findAll(); 

But with getters and setters, you already have type safety, and you already have methods that you don't need to memorize from head to head - and so you have compile-time error checking.

So, to answer your question, the reason why it is bad practice to refer to variables by string name in Java is because

1.) typos may occur and the error only occurs at runtime, not compile time

2.) it is not type safe; you are lucky that you will get a float back no matter what is in this example, but at the moment when it can be a String , you need to return an Object and apply it or use public <T> T get(String field) { ... } , and whoever calls the method needs to know exactly what they get, is also prone to runtime errors.

+9
source share

Getters and Setters give you type safety. However, use it only for variables that you need to get (get / set) from outside the class. You can and should minimize it by using suitable constructors, which in most cases are the right way, because it increases code clarity by eliminating magical changes in the background, which can be a serious pain for multi-threaded code, but there can be big problems even in plain code with poor programming.

Just because you have twenty private class variables does not mean that you need to create getXXX () and setXXX () for each!

BTW: Most IDEs these days, such as Eclipse, can automatically generate them for you.

+3
source share

Just create getters and setters when you need them.

 public float returnSomething(String theThing) { switch (theThing) { case "height": return height; case "rotation" : return rotation; case "width": return width; default: return 0; } } 

If you try to do area = returnSomething("width") * returnSomething("heigth") , you will always find yourself with area 0. Why, pay attention to the spelling error. If you have separate methods, the compiler will say this at compile time.

In addition, you need to do a lot of checks if you have many variables.

+2
source share

I am not a friend of getters / setters, but they are probably the best solution here. The IDE will provide code generation for such fields.

Reason: A solid body that is not prone to errors is easier for subsequent changes.

Only create getters / setters when you really need them. A public void move(float, float) and other more interesting methods can put the calculation of coordinates mainly inside the class itself.

+2
source share

You only need to declare getters and setters for the variables that you will need to use or update.

I think this is just a habit, your return. Something will work fine, but it's easier to call and understand:

 class.getHeight() 

than

 class.returnSomething("height") 
+1
source share

Interesting topic. I feel that there is a third answer. There is an argument saying Getters and Setters are evil and you should avoid using them at all. Since you essentially declare members as private , but grant access to publicly available changes through getters and seters.

Compare two. Here is a human class using getters and setters

 public class Person { private String name; private int age; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getAge() { return this.age; } public void setAge(int name) { this.age = age; } } 

Using this class:

 Person me = new Person(); me.setName("Ian"); me.setAge(24); System.out.println("Name: " + me.getName()); System.out.println("Age: " + me.getAge()); 

Now create the same class without using getters and setters.

 public class Person { public String name; public int age; } 

and access will be:

 Person me = new Person(); me.name = "Ian"; me.age = 24; System.out.println("Name: " + me.name); System.out.println("Age: " + me.age); 

As you can see, the getter and setter pattern adds quite a bit of extra input. However, there are many advantages to using getters and setters.

The entire argument against using getters and setters in an object-oriented language can be summarized as:

The procedural code receives information, then makes decisions. Object oriented code tells objects to do something. - Alec Sharp

As a simple example, let's say we want to write information about Person to a database. What some developers want to do is create a database interface that has a function

 void writeToPersons(Person person) 

which will use getters and setters to write the necessary data to the database.

According to the geyter and setter nay sayers, Person himself must be responsible for writing the database itself.

 public class Person implements Storable { public void writeToDatabase() { } } 

To answer your question, I would rather use getters and setters than your second sentence, because in the end you will add a set of constants or enumerations for each property. This requires maintaining the code in two different places, which simply adds another point of failure.

+1
source share

I agree with the previous answers, but I'm going to generalize a bit. The problem with the returnSomething approach is that it changes some spelling checks from compilation to runtime.

There are times and places for very flexible code in which most checks are performed at runtime. In such situations, I do not use Java.

The big advantage to compiling time checks and the languages ​​that support them is that they perform the equivalent of universally quantified tests: "For every compiled program that does not use reflection, every request for receipt has a valid attribute." and not "For all test cases in this test suite, each receive request for a valid attribute."

+1
source share

All Articles