Quantcast
Channel: Question and Answer » encapsulation
Viewing all articles
Browse latest Browse all 12

Query on hiding implementation details in java

$
0
0

With the below piece of thread related code, I see that author of Thread class is hiding the details about the working of start() method. What a user of Thread class need to know is, class Thread would expect a piece of his own code which will be an instance of Runnable‘s anonymous concrete sub-class that gets passed.

/* TestThread.java */
public class TestThread{

    public static void main(String[] args){
    Thread threadObject = new Thread(new Runnable(){
        public void run(){
           /* your own code that has to run*/   
           System.out.println("a new thread");
        }
    }); 
    threadObject.start();
    System.out.println("Main thread");
    }
}

But in this below program, It looks like we partially hide the implementation details of listFiles(filter) method. Because if author has to change the logic of listFiles(filter) in future without affecting the users, he should make sure that method signature boolean accept(File dir, String name); should not get affected.

/* ListDirectoryWithFilter.java */

import java.io.File;
import java.io.FilenameFilter;

public class ListDirectoryWithFilter{
    public static void main(String[] args){
        String path = System.getProperty("user.home") + File.separator + "workspace" + 
                                            File.separator + "JavaCode" + File.separator + "src";
        File dir = new File(path);

        if(dir.isDirectory()){
            File[] files = dir.listFiles(new FilenameFilter(){
                public boolean accept(File dir, String file){
                    return file.endsWith(".java");
                }
            });
            for(File file : files){
                System.out.println(file.getName());
            }
        }
    }
}

Do you think, it would have been better that listFiles(filter) method just expect a regular expression(*.java) from the user and rest is the result that user expects?

It looked a bit unnecessary approach for me, to implement a two argument accept(,) method and then pass it to listFiles() method.

So, Are such implementations a good practice? If yes, when do we think of such implementations?


Viewing all articles
Browse latest Browse all 12

Trending Articles