1
\$\begingroup\$

I have a simple Java model Class called Person which have a constructor that receives a JSONObject. In that constructor I get the values from the JSONObject and put in my instance variables. This is just a simple question but which way is best?

public Person(JSONObject personJsonObject) {
    // Without setter
    this.name = personJsonObject.getString("name");
    // With setter passing String
    setName(personJsonObject.getString("name"));
    // With setter passing JSONObject
    setName(personJsonObject);
}

And when my setter isn't just a simple attribution but a evaluation, which one should I use?

public Person(JSONObject personJsonObject) {
    // Without setter
    this.fullName = personJsonObject.getString("name") + personJsonObject.getString("lastName");
    // With setter passing String
    setFullName(personJsonObject.getString("name"), personJsonObject.getString("lastName"));
    // With setter passing JSONObject
    setFullName(personJsonObject);
    // Or should I put this logic in the getFullName method? The caveat is if there is a huge calculation in the getter method. It wouldn't be efficient.
}

Thanks for your answer.

\$\endgroup\$
2
  • \$\begingroup\$ This is a lot about your preference. What did you choose initially? \$\endgroup\$
    – ButtersB
    Commented Apr 25, 2013 at 17:58
  • \$\begingroup\$ If there is evaluation, I prefer your suggestion: setFullName(personJsonObject); If you are going to evaluate, accept only what you need, unless it ruins the 'legibility' of the code. \$\endgroup\$
    – ButtersB
    Commented Apr 25, 2013 at 18:02

1 Answer 1

1
\$\begingroup\$

If you have setter methods (setName, setFullName) in your class, then your constructor should call the setter methods.

setName(personJsonObject.getString("name"));

If you don't have setter methods in your class (your class is immutable), then your constructor should perform the evaluation.

this.name = personJsonObject.getString("name");

You should only pass to a method what it needs. In this case, your setName method takes a String as a parameter, which is what the method needs. If your method needs 3 or more values from the personJsonObject (arbitrary rule of mine), then you would pass the personJsonObject to the method.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.