i currenty thinking about a concept which should treat illegal states in my java program.
I have introduced a class which does processing steps on images.
public class ImageProcessor{
public Image processImage(Image img){
//do some processing steps
}
}
Now, I want to introduce another class which should check the the image before doing the processing.
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
}
}
The two classes should be used in a Coordinator class.
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);
}
}
The question is now, is this way of treating Exception (defining a separate method for them) a bad coding style? The idea for this design was to prevent polluting processing code with exception handling. I want the coordinator to throw exceptions and I thought this could be a senseful way. What do you think, is this a good way or is it an antipattern.
Thanks!
The validating method itself is a very good idea. You introduce very good separation of concerns – checking preconditions and validation in one place and actual processing in another.
However the usage is incorrect. The
ImageProcessorshould eagerly callImageChecker.checkImage(). Otherwise the client of your library might forget to call it and pass invalid image.Also *@Damien_The_Unbeliever* brings up a very good point about the structure of the code.
To make it as fancy as possible I would create an
ImageProcessorinterface with two implementations: one that performs the actual processing and a decorator implementation (ImageChecker) that performs validation and passes validated object to targetImageProcessor.This way you can either use safe or fast (assuming validation is costly) implementation. Also in the future you might introduce other elements to the chain like caching or profiling.