public class NullDAO implements SomeDAO
{
public Something retrieveSomethingById(int id)
{
throw new UnsupportedOperationException
("You did not specify a valid SomeDAO");
}
public void saveSomething(Something something)
{
throw new UnsupportedOperationException
("You did not specify a valid SomeDAO");
}
}
Or probably implement something more meaningful but nonetheless does the same thing for all methods.
The argument won't be effective anymore though as far as Groovy is concerned. In Groovy, interfaces can be implemented via Closures and Maps. For the example above, the long class could instead be written as:
Then could be used using the "as" keyword:
Closure nullSomethingDAO = { Object[] args ->
throw new UnsupportedOperationException
("You did not specify a valid SomeDAO")
}
daoUser.setSomethingDAO( nullSomethingDAO as SomeDAO)
As you can see, the null object is now a one liner.
For cases you want your methods to vary, you could use Closures in combination with Maps:
Map nullSomethingDAO = [
retrieveSomethingById : {int id -> doSomething},
saveSomething : {Something something -> doSomethingElse}
]
And inject the same way mentioned above.
4 comments:
hey, nice post; if you want blogger to retain your formatting wrap your code in a <pre> tag; it will retain your formatting; otherwise your code becomes VERY hard to read. =)
thanx robert... will do!
I realized it wasn't retaining the indentation needed to keep code readable; googled and found a post talking about wrapping it in a <pre> tag :)
yeah realized that too.. didn't know we could use tags in the default text box. such a blogger noob i am :)
Post a Comment