2

So I would like to be sure (and also the hidden part is I like to have clean code)

When I'm using variable only one time I can create a method:

 private List<Example> getExampleList() {
    return Example.getInstance().getList();
 }

Question:

  1. If I use this only once, this is equivalent to:

    private List<Example> exampleList = Example.getInstance().getList();

  2. What will the consequences be if I use my method many times instead of making a variable that stores this data? Will java load the value and return it even in cases when there was no reason for the value to change ?

  3. What will be the difference between the declaration and using the method?

1
  • Your code doesn’t use any variable. So the question makes no sense. Commented Oct 19, 2015 at 12:30

1 Answer 1

2

It depends on if Example.getInstance().getList() creates a new object or not:

  1. If it creates a new object with different content every time, you shall not store the first result into a variable.
  2. If it creates a new object with the same content every time (equivalent objects), you may store into a variable the first returned object and reuse it from then on instead of calling getList. It will produce less calls, less unuseful objects, and thus will improve throughput.
  3. If it does not create new object but always returns the same reference, it goes the same as in point 2.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.