Good case for a Null Object Pattern? (Provide some service with a mailservice)
For a website I'm working on, I made an Media Service object that I use in the front end, as well as in the backend (CMS). This Media Service object manipulates media in a local repository (DB); it provides the ability to upload/embed video's and upload images.
In other words, website visitors are able to do this in the front end, but administrators of the site are also able to do this in the backend.
I'ld like this service to mail the administrators when a visitor has uploaded/embedded a new medium in the frontend, but refrain from mailing them when they upload/embed a medium themself in the backend.
So I started wondering whether this is a good case for passing a null object, that mimicks the mail funcionality, to the Media Service in the backend. I thought this might come in handy when they decide the backend needs to have implemented mail functionality as well.
In simplified terms I'ld like to do something like this:
Fron开发者_StackOverflow中文版tend:
$mediaService = new MediaService( new MediaRepository(), new StandardMailService() );
Backend:
$mediaService = new MediaService( new MediaRepository(), new NullMailService() );
How do you feel about this? Does this make sense? Or am I setting myself up for problems down the road?
I am a fan of this pattern. I'm also a fan of renaming objects to match semantics.
As you know, the two benefits you get from the use of a NullObject are:
1) avoid checks for null in your code
2) consolidate behavior into an object that represents what is happening semantically when null is returned.
IF you have some if statement that returns null when the administrators upload, then yes, I think capturing that in an object is cheap and potentially useful, even if you the likelihood of sending mail for backend uploads is small. IF you look at the mail service as a notification service instead, then you might have FrontendNotificationService (which sends mail) and BackendNotificationService (which currently doesn't send mail, but may accumulate useful statistics about the uploads (how many, total size, etc.).
If none of the above is true, then I would personally find a constructor without the NullMailService more readable, and one with the StadndardMailService, more readable.
The good news is that it is an easy refactoring to do when you decide it's useful, or undo if you want to try out your NullService and find it isn't useful.
HTH,
Berryl
精彩评论