views:

37

answers:

1

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:

Frontend:

$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?

+2  A: 

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

Berryl
Hi Berryl. Thanks for your answer. I've decided to go a different route; I made my Media Service dispatch events (CRUD events), and set up a mail service in the front end and let it listen for the CREATED event. However, I like your answer for reference. Sensible stuff! It may come in handy at some other point in time. I'll leave the question open for a while though. Who knows what other bright ideas will get added by other people. +1 though.
fireeyedboy