我有一个方法叫做UpdateUserDevices (UserModel)
. UserModel
包含将设备List<DeviceModel>
列表与特定用户相关联的 。(一对多)。
当我调用该方法时,一切都按预期工作,但是嵌套循环和 if 语句非常复杂。
什么是减少圈复杂度的好模式?我想到了“CoR”,但这可能有点矫枉过正。
private void UpdateUserDevices( UserModel model )
{
// Get users current devices from database
var currentDevicesFromDatabase = _deviceRepository.FindByUserId( model.Id ).ToList();
// if both the model devices and the datbase devices have records
// compare them and run creates, deletes, and updates
if( model.Devices.Any() && currentDevicesFromDatabase.Any() )
{
var devicesToAdd = model.Devices.Exclude( currentDevicesFromDatabase, d => d.Id ).ToList();
var devicesToDelete = currentDevicesFromDatabase.Exclude( model.Devices, d => d.Id ).ToList();
var workingDevices = model.Devices.Union( currentDevicesFromDatabase );
foreach( var device in workingDevices )
{
// Add devices
if( devicesToAdd.Contains( device ) )
{
_deviceRepository.Create( device );
continue;
}
// delete devices
if( devicesToDelete.Contains( device ) )
{
_deviceRepository.Delete( device );
continue;
}
// update the rest
_deviceRepository.Update( device );
}
return;
}
// model.Devices doesn't have any records in it.
// delete all records from the database
if( !model.Devices.Any() )
{
foreach( var device in currentDevicesFromDatabase )
{
_deviceRepository.Delete( device );
}
}
// database doesn't have any records in it
// create all new records
if( !currentDevicesFromDatabase.Any() )
{
foreach( var device in currentDevicesFromDatabase )
{
_deviceRepository.Create( device );
}
}
}