On 7/20/2012 7:23 AM, Shapper wrote:
> I have the following code which I repeat in many places:
>
> FindUserByIdResponse response = disp.FindUserById(id);
>
> if (response.Exception == null) {
> if (response.User == null)
> return new StMessage("NotFound");
> } else
> return new StMessage("Error");
>
> Response can be a FindUserByIdResponse, FindPostByIdResponse, ...
>
> Each response implements IRequestResponse and as a property:
>
> - FindUserByIdResponse has the property User;
>
> - FindPostByIdResponse has the property Post;
>
> I would like to move the previous validation to another class:
>
> Message msg = ValidateResponse<FindUserByIdResponse.User>(response);
>
> In this case the response would be tested against null.
>
> And its property of type User would also be tested against null.
>
> Is this possible?
Maybe a Func<T, object> argument.
Example:
using System;
namespace E
{
public interface IRequestResponse
{
Exception Exception { get; set; }
}
public class FindUserByIdResponse : IRequestResponse
{
public Exception Exception { get; set; }
public string User { get; set; }
}
public class FindPostByIdResponse : IRequestResponse
{
public Exception Exception { get; set; }
public string Post { get; set; }
}
public class Demo
{
public FindUserByIdResponse FindUserById(int id)
{
return new FindUserByIdResponse();
}
public FindPostByIdResponse FindPostById(int id)
{
return new FindPostByIdResponse { Post = "Something" };
}
}
public class Message
{
}
public class OkMessage : Message
{
public IRequestResponse Response { get; set; }
}
public class ErrorMessage : Message
{
public string Text { get; set; }
}
public class Util
{
public static Message ValidateResponse<T>(T response,
Func<T,object> f) where T : IRequestResponse
{
if(response.Exception != null)
{
return new ErrorMessage { Text = "Exception: " +
response.Exception };
}
else if(f(response) == null)
{
return new ErrorMessage { Text = "Not found" };
}
else
{
return new OkMessage { Response = response };
}
}
}
public class Program
{
public static void Main(string[] args)
{
Demo demo = new Demo();
FindUserByIdResponse resp1 = demo.FindUserById(123);
Message msg1 = Util.ValidateResponse(resp1, r => r.User);
Console.WriteLine(msg1.GetType().FullName);
FindPostByIdResponse resp2 = demo.FindPostById(456);
Message msg2 = Util.ValidateResponse(resp2, r => r.Post);
Console.WriteLine(msg2.GetType().FullName);
Console.ReadKey();
}
}
}
Arne
PS: There are several thing in the demo that are not good code, but the
Func<T, object> may still be a good suggestion.
|