C # Duplicate code with zero validation

I am working with RPC (protobuf-remote) and I need to do some checking if the other end (server) is down. Let's say I have many RPC methods, for example:

public FirstObj First(string one, string two) { if (rpc == null) return (FirstObj)Activator.CreateInstance(typeof(FirstObj)); return rpc.First(one, two); } public SecondObj Second(string one) { if (rpc == null) return (SecondObj)Activator.CreateInstance(typeof(SecondObj)); return rpc.Second(one); } public ThirdObj Third() { if (rpc == null) return (ThirdObj)Activator.CreateInstance(typeof(ThirdObj)); return rpc.Third(); } 

Is there a way to change this duplicate zero checking code? So I could write something like:

 public FirstObj First(string one, string two) { return rpc.First(one, two); } 

To check for null and create an object by type if the RPC server is down, so I will get the default values ​​for the required object.

+5
source share
2 answers

You can create an extension method like this:

 public static class RpcExtension { public static T GetObject<T>(this RPC rpc, Func<RPC, T> func) where T: class , new () { if (rpc == null) { return Activator.CreateInstance<T>(); } return func(rpc); } } 

for this use:

 var first = rpc.GetObject(r => r.First(a, b)); 
+5
source

You can simplify the code using the general method:

 private static T Make<T>() { return (T)Activator.CreateInstance(typeof(T)); } public FirstObj First(string one, string two) { return rpc == null ? Make<FirstObj>() : rpc.First(one, two); } public SecondObj Second(string one) { return rpc == null ? Make<SecondObj>() : rpc.Second(one); } public ThirdObj Third() { return rpc == null ? Make<ThirdObj>() : rpc.Third(); } 

If FirstObj , SecondObj and ThirdObj are all classes, not struct or primitives, and rpc never returns null for them, you can do this:

 public static T RpcOrDefault<T>(T obj) where T : class { return obj ?? (T)Activator.CreateInstance(typeof(T)); } 

and name him

 FirstObj first = RpcOrDefault(rpc?.First(one, two)); // ^ 

Pay attention to ? in ?. which protects you from null referential exceptions.

+2
source

Source: https://habr.com/ru/post/1260761/


All Articles