我現在正在考慮一個應該在我的java程序中處理非法狀態的概念。 我已經介紹了一個在圖像上處理步驟的類。引入僅用於異常拋出的方法是一個糟糕的決定嗎?
public class ImageProcessor{
public Image processImage(Image img){
//do some processing steps
}
}
現在,我想介紹另一個類,它應該在處理之前檢查圖像。
public class ImageChecker{
public void checkImage(Image img) throws ImageNotProcessableException{
//for example, if the image has a width of 0 the full process
//should be broken, throw an exception
if (img.width=0) throw new ImageNotProcessableException("width is 0");
//other conditions throwing also exceptions
// the image is fine, do nothing
}
}
這兩個類應該用在Coordinator類中。
public class Coordinator{
public void coordinate(Image img) throws ImageNotProcessableException{
//initialize both
imageChecker.checkImage(img); //if no exception is throw the process can run
imageprocessor.processImage(img);
}
}
現在的問題是,這種方式的異常(爲他們定義一個單獨的方法)是一種錯誤的編碼風格?這種設計的想法是爲了防止污染處理代碼和異常處理。我希望協調員拋出異常,我認爲這可能是一種有意義的方式。你覺得呢,這是一個好方法還是反模式? 謝謝!
'imageChecker'確實是一個獨立的類,它對多個其他類是有用的,還是它執行的檢查實際上特定於'imageProcessor'? 'imageChecker'有多少種方法? –