简体   繁体   中英

Difference between Getter/Setter and this other Data object Class

I'm working on a mobile application with APIs endpoints returning JSON data and i do a lot of JSON parsing for displaying different types of data in my application.

For a long time i was using Getter Setter with constructor in my java object classes to handle data but recently by colleague told me a bit different and easy approach for handling this exact data. The two different dataObject classes are

The way I was handling my data manipulation

public class MyObject {
String _string1, _string2;
List<String> _stringsList;

public MyObject(String _string1, String _string2, List<String> _stringsList) {
    this._string1 = _string1;
    this._string2 = _string2;
    this._stringsList = _stringsList;
}

public String getString1() {
    return _string1;
}

public String getString2() {
    return _string2;
}

public List<PostO> getStringList() {
    return _stringsList;
}

}

The way my colleague suggested

public class MyObject {
public String _string1, _string2;
public List<String> _stringsList;

public MyObject() { }

}

And the app works fine with both methods. and the second way is short and easy to make edits. But whats the difference between these two? Is there any technical shortcoming in the second method or something? I really need to know before converting my classes to this new method.

I started using GSON with second method, if it matters.

From documentation :

Using fields vs getters to indicate Json elements

Some Json libraries use the getters of a type to deduce the Json elements. We chose to use all fields (up the inheritance hierarchy) that are not transient, static, or synthetic. We did this because not all classes are written with suitably named getters. Moreover, getXXX or isXXX might be semantic rather than indicating properties.

However, there are good arguments to support properties as well. We intend to enhance Gson in a latter version to support properties as an alternate mapping for indicating Json fields. For now, Gson is fields-based.

As you can read, Gson is fields-based and in your case there is no difference between fields in two versions of the same class.

If you use MyObject only for deserialisation purpose and later you convert it to some business model you can stay with shorter version. But in case, MyObject is propagated over many layers it could introduce inconsistency with other classes which uses getters / setters .

Maybe Lombok library would be the best to use for you and your colleague?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM