Reducing Program Complexity - Method 1 降低程序複雜度 - 方法1

Cognitive Complexity from 99 to the 15 allowed

if if if if if if if if if if if if if if if if if if if if

 

definition

public class InDataClassDto
{
	public string? DataA01 { get; set; }
	public string? DataA02 { get; set; }
	...
	public int? DataA98 { get; set; }
	public Decimal? DataA99 { get; set; }
}

public partial class DataTableADto
{
	public string? Db01 { get; set; }
	public string? Db02 { get; set; }
	...
	public int? Db98 { get; set; }
	public Decimal? Db99 { get; set; }
}

var update = (
		from a in _database.DataTableA
		where a.Id == sId
		select a
	).SingleOrDefault();

 

Cognitive Complexity 99

if (update != null)
{
    if (inData.DataA01 != null) { update.Db01 = inData.DataA01; }
    if (inData.DataA02 != null) { update.Db02 = inData.DataA02; }
    ...
    if (inData.DataA98 != null) { update.Db98 = inData.DataA98; }
    if (inData.DataA99 != null) { update.Db99 = inData.DataA99; }
}
_database.SaveChanges();

 

Solution 1

var mappings = new (Func<InDataClassDto, object?> Source, Action<DataTableADto, object?> Target)[]
{
    // DataA01 and Db01 are used as field correspondence rules
    (x => x.DataA01, (y, v) => y.Db01 = (string?)v),
    (x => x.DataA02, (y, v) => y.Db02 = (string?)v),
	...
    (x => x.DataA98, (y, v) => y.Db98 = (int?)v),
    (x => x.DataA99, (y, v) => y.Db99 = (Decimal?)v),

};
foreach (var map in mappings)
{
    // Get the corresponding source value from inData
    var value = map.Source(inData);

    if (value != null)
    {
        // Write the value into update
        map.Target(update, value);
    }
}
_database.SaveChanges();

 

我只是一棵樹