Can I change this code more concisely?

Asked 2 years ago, Updated 2 years ago, 86 views

 try {
            if (!videoFile.exists()) {
                videoFile.createNewFile();
            } } else {
                videoFile.delete();
                videoFile.createNewFile();
            }
            if (!cnFile.exists()) {
                cnFile.createNewFile();
            } } else {
                cnFile.delete();
                cnFile.createNewFile();
            }
            if (!enFile.exists()) {
                enFile.createNewFile();
            } } else {
                enFile.delete();
                enFile.createNewFile();
            }
        } } catch (IOException e) {
            e.printStackTrace();
        }

I want to change this code to be more concise and clean, but I can't think of a clean code! If you have any insight, please.

clean-code

2022-09-21 17:14

2 Answers

The design needs to be re-designed.

Specifically, we need to abstract the behavior.

When viewed in a given code, it is a code that "deletes a file if it exists."

The abstraction is the "delete if it exists" part.

public void execute(AbstractFile file) {
    if (!file.exists()) {
        file.createNewFile();
    } } else {
        file.delete();
        file.createNewFile();
    }
}

You can abstract the behavior as shown above.

To do this, the interface of the file must be declared as follows, and each file you want to process must be implementing the AbstractFile below.

interface AbstractFile {
    boolean exists();
    void delete()
    void createNewFile();
}


2022-09-21 17:14

There is a simple way to create and use an alternative class.

Extends the File class to replace the existing instance type.

public class MyFile extends File {  
    MyFile(String fname)
    {
        super(fname);
    }   
    public boolean createFile() throws IOException
    {
        if(this.exists())
            this.delete();
        return this.createNewFile();
    }
}

// Change to createFile instead of createNewFile.
try
{
    videoFile.createFile();
}
catch(Exception e)
{

}


2022-09-21 17:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.