Reputation: 1433
I am creating a java object to represent some JSON, using gson. This JSON defines the layout of a touchscreen game controller, and as such is very complex (each device has an orientation, each orientation has buttons, each button has location/size, etc.)
The program I am trying to create would serve as a standalone editor of a controller layout.
What I've done is created a class for each type (button, device, etc.) like this:
public class Device {
public Button dpad;
public Button a;
public Button b;
public Button start;
public Button select;
public Button l;
public Button r;
public Button menu;
public ExtendedEdges extendedEdges;
}
The object itself has no logic; all serialization/deserialization is handled by gson.
I've recently read a few programming books, and one major topic was the Law of Demeter and code coupling, and this class will cause other objects to break that. However, there wouldn't really be a way to conform to good coding practices. Providing accessor methods and making fields private would simply be redundant, as the program needs write access to the entire object. Additionally, it is fairly easy to write:
Device device = foo(); //returns Device
bar(device.dpad.width); //Does something that involves the width of the dpad
Is there a better way to handle nested JSON representations, or is disobeying the Law of Demeter fine in this case?
Upvotes: 0
Views: 245
Reputation: 106480
The coupling you have to worry about here is of your data representation, which does pose risk; if this JSON object is publicly consumed, you cannot willingly remove elements from it, as consumers that depend on it down the road would break. You can certainly add elements to it, as the consumers that are using the legacy structure won't necessarily care about the extra fields.
Outside of that, this sort of giant data object structure is common with serialization/deserialization of JSON data. Again, it's coupled, but only with the actual structure of your response.
Upvotes: 1