Refactor two steps to avoid redundancy

60 Views Asked by At

We have a specification where we

  1. build 84 configurations
  2. define 167 relations between the 84 configurations
  3. add all of the 84 configurations to one joint configuration

My issue is twofold:

  • I find the last part repetitive: We're using 84 LOC on adding all the configurations to the joint one.
  • When we add a new configuration, we often forget this caveat of adding the new configuration to the joint one.

My own trail of thought has been to combine the first step and third step, but I haven't found a way of doing that while still being able to refer to the configurations for the second step.

Do you have any suggestions on how to improve this?

The relevant parts of the code looks like this:

var x = X.Build()
var y = Y.Build()
var z = Z.Build()
// 84 times

x.AddRelation(y)
x.AddRelation(z)
// 167 times

var config = new Config(...) {
    Entities =
    {
        x,
        y,
        z,
        // 84 times
    }
}
1

There are 1 best solutions below

0
SMSTJ On

Due to the lack of Detail this is the best I can give you atm.

//since I dont know the Details of how this will have to look im just doing some guesswork here
public Config Builder(List<ConfigurationToBuild> configsToBuild)
{
    List<BuildConfig> buildConfigs = new List<BuildConfig>();
    foreach(ConfigurationToBuild cTB in configsToBuild)
    {
        buildConfigs.Add(cTB.Build());
    }
    
    BuildConfig relationConfig = buildConfigs[0];
    bool skip = true;
    
    foreach(BuildConfig bC in buildConfigs)
    {
        if(skip)
        {
            skip = false;
            continue;
        }
        
        relationConfig.AddRelationSingular(bC);
    }
    
    //I will run on the assumtion that Entities is a List
    
    var config = new Config(...)
    {
        Entities = buildConfigs
    };
    
    return config;
}

public static class ExtensionClass
{
    public static void AddRelationSingular(this BuildConfig config, BuildConfig configToAdd)
    {
        config.AddRelation(configToAdd);
        configToAdd.AddRelation(config);
    }
}