Home > OS >  Should I define variables inside methods in Java?
Should I define variables inside methods in Java?

Time:10-20

I am new in Java and sometimes I encounter such kind of situations as shown below:

public class DataServiceImpl implements DataService {

    private WorkSheet workSheet;
    private Cell cell;

    @Override
    public MultipartFile export() throws IOException {
        workSheet = new WorkSheet(SHEET_PERMISSION_TITLE);
        // ...
    }

    private void writePersonalInfo() {
        cell = row.createCell(0);
        cell.setCellValue(data.getName());

        final List<String> titles = new ArrayList<>();
        // ...
    }

    private void writeSalaryInfo() {
        cell = row.createCell(0);
        cell.setCellValue(data.getSalary());

        final List<String> titles = new ArrayList<>();
        // ...
    }
}

As in this example, I generally use the variables at the beginning of the class. So, my questions:

1. Should I use like this if there is no obligation? Or should I create inside method e.g. Cell cell = row.createCell(0);?

2. Does it make any sense using the variable in different methods? For example, cell variable is used in writePersonalInfo and writeSalaryInfo. I am not sure if I should define this variable in each of these 2 methods as Cell cell = row.createCell(0);.

CodePudding user response:

To answer your question: In your case above, you should declare the cell variable inside the method.

Explanation: If you declare the variable with the class scope, you introduce a bug in your code: Think of multiple threads. One thread is going to the writePersonalInfo method, another thread at the same time through the writeSalaryInfo method:

  • Thread A calls cell = row.createCell(0);
  • Thread B calls cell = row.createCell(0); (replaces the previously created cell)
  • Thread A calls cell.setCellValue(data.getName());
  • Thread B calls cell.setCellValue(data.getSalary()); (and replaces the name)

With your code, there will always be just one cell instance in this object. You should always limit the scope of a variable as much as possible.

CodePudding user response:

Should I use like this if there is no obligation? Or should I create inside method e.g. Cell cell = row.createCell(0);?

It depends. If it is your intent that the value in a variable should only be used in a method, then you should declare the variable as a local variable ... inside the method that uses is.

If it is your intent that that value in the variable should be shared by different methods ... or between different calls of the same method, then it may be appropriate to declare the variable as a field (aka attribute) .... like you have done.

If sharing is not necessary, then local variables have distinct advantages:

  • There is avoid the possibility that one method might accidentally causing problems for another method by updating the variable. And it means that someone reading the code can eliminate that ...

  • It also (potentially) saves space. Local variables go away as soon as a method returns. Fields will continue to exist as log as the object (your DataServiceImpl) continue to exist. This could also lead to a memory leak.

  • Inappropriate fields (that should be local variables) can also present problems if your code is multi-threaded or method calls are recursive.


In your example, it looks like cell should be different local variables in each method. But worksheet looks like object state that needs to be used by multiple methods (not shown ...)

  • Related