Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Strategy for limiting scope of a variable

Tags:

java

I just stumbled over an error and asking myself if there is a better way do do it.

First I had this code.

// read lines out of a file and do something with it in foo
BufferedReader br = new BufferedReader (new FileReader ("bla.txt")); 
String line; 
while ((line = br.readLine ()) != null) 
{
  foo (line);
}
br.close ();

Then I changed it. Introduced a list instead of working in the read-loop.

BufferedReader br = new BufferedReader (new FileReader ("bla.txt")); 
List <String> lst = new ArrayList <String> ();
String line; 
while ((line = br.readLine ()) != null) 
{
  lst.add (line);
}
br.close ();
for (String s : lst)
{
  foo (line);   // !!!
}

Please ignore the fact that is is not a real optimization. The code is just a simplification for my question.

In using the collection I did a mistake. I did keep foo(line) instaed of foo(s). Thats no compiler error but wrong for my algorithm.

Whats a good strategy for avoiding this problem if making it more modular (using functions etc.) is not apropriate?

I thougt about limit the scope of line by putting it into a block.

BufferedReader br = new BufferedReader (new FileReader ("bla.txt")); 
List <String> lst = new ArrayList <String> ();

{
  String line; 
  while ((line = br.readLine ()) != null) 
  {
    lst.add (line);
  }
  br.close ();
}

for (String s : lst)
{
  foo (line);   // error now
}

But I am not sure thats a common and good strategy. Any suggestions for that kind of problem? Thanks!

like image 809
chris01 Avatar asked Apr 24 '26 02:04

chris01


1 Answers

What you are looking for is having a pure function [1]. In order to achieve that you should have two separate functions, one to read the content and another to process it. The second function should take a parameter as a list. Something like below :

List<String> readContent(){ 
   BufferedReader br = new BufferedReader (new FileReader ("bla.txt")); 
   List <String> lst = new ArrayList <String> ();

   {
     String line; 
     while ((line = br.readLine ()) != null) 
     {
       lst.add (line);
      }
    br.close ();
   }
   return lst;
}

void processContent(List<String> contentList){
 for (String s : contentList){
  foo (s);   // error now
 }
}

In your main method, you will call both the functions like following:

List<String> contents = readContent();
processContent(contents);

Furthermore, there should be a Unit Test for both of the function as well.

[1] https://en.wikipedia.org/wiki/Pure_function

like image 93
royalghost Avatar answered Apr 26 '26 14:04

royalghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!