Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question
    
This is a lot about your preference. What did you choose initially? –  ButtersB Apr 25 '13 at 17:58
    
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. –  ButtersB Apr 25 '13 at 18:02

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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