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
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();
}
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)
{
}
610 Uncaught (inpromise) Error on Electron: An object could not be cloned
577 PHP ssh2_scp_send fails to send files as intended
600 GDB gets version error when attempting to debug with the Presense SDK (IDE)
888 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.