我有一个方法,我认为它与if语句相当重要,我决定在Resharper的帮助下重构它,后来发现它是我遇到的很多错误的原因.
private bool isValid(User user)
{
if (user == null)
return false;
if (user.IsBot)
return true;
if (user.GetClient() == null)
return false;
if (user.GetClient().GetData() == null)
return false;
if (user.GetClient().GetData().CurrentRoomId != _room.RoomId)
return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
我为此重构了它
private bool isValid(User user)
{
return user?.GetClient() != null && user.GetClient().GetData() != null && user.GetClient().GetData().CurrentRoomId == _room.RoomId;
}
Run Code Online (Sandbox Code Playgroud)
将重构版本返回到原始版本后,所有错误都消失了.仅仅为了自我改善的目的,有人可以告诉我我做错了什么吗?我看不到任何东西,但很明显它打破了很多东西所以它必须有所作为.
原始版本更具可读性,在您的重构期间,您引入了一个错误.该IsBot支票丢失.
您可以将方法重构为:
private bool isValid(User user)
{
if (user == null)
return false;
if (user.IsBot)
return true;
return user.GetClient()?.GetData()?.CurrentRoomId == _room.RoomId;
}
Run Code Online (Sandbox Code Playgroud)
仍然可读,但更短,更重要.
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |