Summary
I am looking at a scenario, such as this:
File someFile = null;
try
{
   someFile = File.createTempFile( SOME_PREFIX, SOME_SUFFIX, targetDirectory );
}
catch( IOException e )
{
    throw new SomeException( "Unable to create file for domain specific task", e, SomeExceptionErrorCode.FILE_MANAGEMENT_ERROR );
}
            
try( BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream( someFile.getAbsolutePath() ) ) )
{
    stream.write( byteData, 0, byteData.length );
    stream.flush();
}
catch( IOException e )
{
    throw new SomeException( "Unable to write domain specific data to domain specific file", e, SomeExceptionErrorCode.FILE_MANAGEMENT_ERROR );
}
For this scenario someFile is initialized with null. My intent is to translate this code into something that follows proper practices.
What I considered
- Simply initializing someFiletonull, as shown in the current code snippet. However typically I am avoiding this, so this does not seem satisfactory as of now
- Initializing someFilewith e.g. an emptyString. This provides a default instance ofFileof sorts. The problem I see with this is, if this error handling changes in the future, a validFilewith nonsense properties could be passed to some other place inside the code.
- Nesting the try-catchblocks. This does work, however for some reason feels bad, especially since both nested blocks catchIOException
- An Optional<File>was also considered, I am however not convinced if everytry-catchblock where a somewhat complex object is initialized to be used outside that block justifies the use ofOptional
Question
Is initializing someFile to null an antipattern? If so, how is a scenario, such as the one posted, handled best?
 
     
    