的方法返回部分不完整的結果,我想上的情況下的一些反饋:從拋出異常
的方法構造一個對象,但一些工作,同時構建它可能無法完成。這將導致缺少一些數據的對象。我想給這個方法的用戶處理對象的能力(如果完成的話),但是如果不完整則處理對象,同時也能夠處理拋出的異常。
使用案例:
我從磁盤讀取一個文件到一個POJO和文件的一些屬性,如創建可以拋出,而從操作系統中讀取一個例外日期。在這種情況下,我拋出了一個自定義的異常,但我也希望用戶能夠處理不完整的文件表示(POJO)。
我的解決辦法:
我用它包裝拋出的異常和不完整的對象自定義異常。
我的代碼:
public FileDto getFromFile(File f) throws IncompleteFileDtoException {
FileDto dto = new FileDto();
dto.setName(f.getName());
dto.setPath(f.getAbsolutePath());
dto.setDirectory(f.isDirectory());
dto.setSize(f.length());
dto.setModifiedAt(f.lastModified());
try {
BasicFileAttributes attr = Files.readAttributes(f.toPath(), BasicFileAttributes.class);
dto.setCreatedAt(attr.creationTime().toMillis());
}
catch(Exception e)
{
throw new IncompleteFileDtoException("Unable to transform " +f.getAbsolutePath() + " to DTO.", e, dto);
}
return dto;
}
public static class IncompleteFileDtoException extends Exception
{
private FileDto fileDto;
public IncompleteFileDtoException(String message, Exception e, FileDto fileDto)
{
super(message,e);
this.fileDto = fileDto;
}
public FileDto getFileDto() {
return fileDto;
}
}
會這樣的代碼有什麼負面影響?
這聽起來確實是一個有趣的補充。我能從中看到的一個好處是,Builder將對象構造過程(可能很重)委託給方法的用戶,如果認爲它不是必要的,他不會構造對象並且不會使用資源,對嗎? –
這是正確的。它在很多情況下非常有用:例如像你的,當你在對象初始化過程中遇到問題時,或者當你想用許多最終參數來構建不可修改的對象時(而不是使用具有所有這些參數的構造函數)。 「四人幫」是關於它的很好的書。 –