user1649803
user1649803

Reputation: 37

How to refactor Methods with same structure, different classes (Java)

What is the best way to refactor methods that have the same logic but use different classes (In Java)? Let's say

Method1(FileInputStream obj, OutputStream o){
  //stuff
  while(something){
    //---
    //some code
    //---
    obj.read();
    //---
    //some code
    //---
    o.write(..);
    //code
  }
  //code
}

and then I have

Method2(InputStreamReader obj, OutputStreamWriter os){
  //stuff
  while(something){
    //---
    //some code
    //---
    obj.read(..);
    //---
    //some code
    //---
    os.write();
    //code
  }
  //code
}

1 method deals with binary files and another deals with text. Ideally what I would want is to have a Read-Process-Write and hide away all of the specific information

Upvotes: 2

Views: 372

Answers (2)

Amir Raminfar
Amir Raminfar

Reputation: 34169

Best way is to use the correct interfaces:

void method2(Reader obj, Writer os){
   // code...   
}

Then use it like this for InputStreams

method2(new InputStreamReader(fileInputStream), new OutputStreamWriter(outputstream));

Why is this better?

This is better because you are abstracting out the way the method works. You are saying you don't care what the implementation is, as long as it conforms to a Reader or Writer. Therefore, it is the responsibility of the user to change an InputStream to a Reader. Not yours. If there is an exception being thrown in that, then you DON'T need to catch it. It is thrown in client code. This is an important note.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533540

You can't read and write the same things so they don't have anything in common except the names. The only way to make them common is to write binary and text as binary i.e. its all turned to binary in the end anyway.

Upvotes: 0

Related Questions