我无法弄清楚为什么这个方法的可维护性指数(在Visual Studio中计算)只有40,我实际上必须删除几乎所有的行除了前两个以达到60以上:
public void getNewPasswordDetails(Int32 newPasswordId)
{
int UserId = HttpContext.Current.User.Identity.GetUserId().ToInt();
bool userIsAdmin = HttpContext.Current.User.IsInRole("Administrator");
//get a list of userIds that have UserPassword records for this password
var UserIDList = DatabaseContext.UserPasswords.Where(up => up.PasswordId == newPasswordId).Select(up => up.Id).ToList();
//Retrive the password -if the user has access
Password newPassword = DatabaseContext.Passwords
.Include("Creator")
.Where(pass => !pass.Deleted
&& (
(UserIDList.Contains(UserId))
|| (userIsAdmin && ApplicationSettings.Default.AdminsHaveAccessToAllPasswords)
|| pass.Creator_Id == UserId)
)
.Include(p => p.Parent_UserPasswords.Select(up => up.UserPasswordUser))
.SingleOrDefault(p => p.PasswordId == newPasswordId);
if (newPassword != null)
{
//map new password to display view model
AutoMapper.Mapper.CreateMap<Password, PasswordItem>();
PasswordItem returnPasswordViewItem = AutoMapper.Mapper.Map<PasswordItem>(newPassword);
//generate a string based view of the new category
string passwordPartialView = RenderViewContent.RenderViewToString("Password", "_PasswordItem", returnPasswordViewItem);
//broadcast the new password details
PushNotifications.sendAddedPasswordDetails(passwordPartialView, returnPasswordViewItem.Parent_CategoryId, returnPasswordViewItem.PasswordId);
}
else
{
//we dont have access any more, so tell UI to remove the password
PushNotifications.sendRemovePasswordAccess(new PasswordDelete()
{
PasswordId = newPasswordId
});
}
}
答案 0 :(得分:2)
代码越复杂,维护起来就越困难。对?那么让我们看一下代码的复杂部分。我将检查它好像我是第一次查看代码的开发人员:
DatabaseContext.Passwords
.Include("Creator")
.Where(pass => !pass.Deleted
&& ((UserIDList.Contains(UserId)) // Why Check #1
|| (
userIsAdmin // Why Check #2
&& // Why Check #3
ApplicationSettings.Default.AdminsHaveAccessToAllPasswords
)
|| pass.Creator_Id == UserId)
)
.Include(p => p.Parent_UserPasswords.Select(up => up.UserPasswordUser))
.SingleOrDefault(p => p.PasswordId == newPasswordId);
在进入循环之前,人们已经知道这些状态事实:
(UserIDList.Contains(UserId)
as 为什么选中#1 userIsAdmin
为为什么选中#2 (userIsAdmin && ApplicationSettings.Default.AdminsHaveAccessToAllPasswords)
为为什么检查#3 然而,开发人员已将这些检查降级为密码中的每个密码。为什么?难道没有更好的表达方式吗?
由于程序逻辑的应用程序(编码),对于业务逻辑的决定 中的每个逻辑分支 直接,会出现复杂性增加了代码的复杂性以及随后的可维护性;因此获得了评级。
当然,代码本质上存在某些复杂性,这种情况将会发生并且应该是预期的。问题是,这种复杂性是否可以最小化到可以更好地实现代码维护的程度。