Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK for a factory method to return null?

I'm wondering about best practice here. Is it good practice for a factory method to return null if it can't create anything? Here's an example:

ICommand command = CommandFactory.CreateCommand(args); if (command != null)     command.Execute(); else     // do something else if there is no command 

An alternative would be to return a NullCommand or something, I guess, but what is best practice?

like image 297
Jeff Pratt Avatar asked Jun 20 '12 17:06

Jeff Pratt


People also ask

Can a factory return null?

Null reference as a product of a factory is incompatible with the concept of a factory as an object where something is produced.

Is it good practice to return null?

Returning Null is Bad Practice The FirstOrDefault method silently returns null if no order is found in the database. There are a couple of problems here: Callers of GetOrder method must implement null reference checking to avoid getting a NullReferenceException when accessing Order class members.

Is it better to return null or empty string?

Returning null is usually the best idea if you intend to indicate that no data is available. An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.

What happens when return null?

A function that returns a null reference achieves neither goal. Returning null is like throwing a time bomb into the software. Other code must a guard against null with if and else statements.


1 Answers

I think it's potentially reasonable for a factory method to return null in some situations, but not if it's a method called CreateCommand. If it were GetCommand or FetchCommand, that might be okay... but a Create method should throw an exception on failure, I would suggest.

Whether you really want it to return null in this situation depends on the bigger picture, of course. (Is there a reasonable null object implementation you could return instead, for example?)

like image 100
Jon Skeet Avatar answered Sep 21 '22 01:09

Jon Skeet