0
votes

I've written a simple program that retrieves weather data from OpenWeatherMap API and de-serializes the JSON response into objects. One of the objects is called CurrentForecast. Here is a snippet of the class:

public class CurrentForecast {
    String name;
    long dt;
    LocationCoord coord;
    List<WeatherObject> weather;
    MainInfo main;
    WindInfo wind;

    public static class LocationCoord {
        Double lon;
        Double lat;

        public LocationCoord(Double lon, Double lat) {
            this.lon = lon;
            this.lat = lat;
        }
    }

    public static class WeatherObject {
        String description;

        public WeatherObject(String description) {
            this.description = description;
        }
    }

    public static class MainInfo {
        Double temp;
        Double temp_min;
        Double temp_max;
        Double pressure;
        Double humidity;

        public MainInfo(Double temp, Double pressure, 
                        Double humidity) {
            this.temp = temp;
            this.pressure = pressure;
            this.humidity = humidity;
        }

There are several classes nested within the CurrentForecast class. The fields of CurrentForecast and the nested classes were not set to private or public. I also didn't include a constructor for CurrentForecast to initialize 'name' and 'dt'. I also noticed that if I don't include the constructors for the other nested classes, the JSON data is de-serialized just fine.

My question is, do I set the fields for CurrentForecast and the nested classes to private and include get methods? Do I also have to include constructors or can I take those out?

Would love to get input on how I can properly set up my object classes (specifically for de-serializing JSON data using GSON in the main driver) and improve my programming style. Thank you!

1

1 Answers

0
votes

Should you set the fields to private and include getters?

There's no need to, especially if other people aren't going to use your code, but I think it's good practice to do so since it helps to keep things neat. Up to you! Obviously keep in mind the circumstances; if you have a variable that you only want the class it resides in to have access to it, make it private.

Do you have to include constructors?

If you don't need some code to run when your class is instantiated (when you create a new object from a class), then there's no need to create a constructor since Java will create a default (non-parameterized) one for you.

I don't know much about GSON and de-serializing JSON data, but I think getters and setters would be beneficial in this situation to quickly be able to set and get your different variables without the code getting too messy.

Hope that helps!