Empty object mode, Object Mode
When developing data at the business layer, I always worry that the data layer will return null to the object instance.
Therefore, every time I use the object instance returned by the data layer, I have to determine whether it is null.
UserRepository respository = new UserRepository(); var user = respository.GetById("008"); if (user!=null) { user.SayHello(); }
Although this avoids exceptions caused by null values, it adds a lot of work to the client code, and once I forget to judge somewhere, my code will have a null exception; to solve this problem, we have introduced the empty object mode, killing empty objects at the data source.
public interface IUser { void SayHello(); }
public class User : IUser { public string Id { get; private set; } public User(string id) { Id = id; } public void SayHello() { Console.WriteLine("{0}:Hello", Id); } }
Public class NullUser: IUser {public void SayHello () {// for an empty object instance, no processing is required for any method }}
Public class UserRepository {private ICollection <User> users; public UserRepository () {users = new List <User> () {new User ("001 "), new User ("002"), new User ("003"), new User ("004"), new User ("005 ")};} public IUser GetById (string userId) {IUser user = users. singleOrDefault (s => s. id = userId); if (user = null) // check whether the User's instance is null. if yes, a special Iuser {user = new NullUser ();} is returned ();} return user ;}}
In the code above, the data layer directly determines whether the user instance is null. If it is null, an object instance is returned for processing the null value.
static void Main(string[] args) { UserRepository respository = new UserRepository(); var user = respository.GetById("008"); user.SayHello(); user = respository.GetById("003"); user.SayHello(); Console.ReadLine(); }
Now, Mom no longer has to worry about calling the object instance of the data layer to report null references. Of course, this method is not limited