Domanda

In my application, we have a class which generates information within a database as static centralised data. This class is called 'GenerateOwner'. Within this class we are creating multiple entries of type 'FieldValidation'.

        FieldValidation swedishFieldValidation1 = new FieldValidation
        {
            IsRequired = false,
            DataType = "String",
            Length = 0,
            Min = 0,
            Max = 255,
            FieldValidationType = _bancPaydatabase.FieldValidationTypes.FirstOrDefault(o => o.FieldName == "InvoiceNumber"),
            IsVisible = true,
            Owner_Country = swedishOwnerCountry
        };

        FieldValidation swedishFieldValidation2 = new FieldValidation
        {
            IsRequired = false,
            DataType = "String",
            Length = 0,
            Min = 0,
            Max = 255,
            FieldValidationType = _bancPaydatabase.FieldValidationTypes.FirstOrDefault(o => o.FieldName == "InvoiceTypeId"),
            IsVisible = true,
            Owner_Country = swedishOwnerCountry
        };

And so on. There are about 20 or so entries all very much similar. My question is, how would I best refactor this code to prevent duplicating the same entries over and over? I have been pointed towards the Extract method, but I am unsure of how to implement this in my code. Thanks in advance.

È stato utile?

Soluzione

Extract method is a refactoring method that extracts code into its own method. If the extracted part needs parameters they are passed as parameters to the method.

In your code the code is exactly the same except for the field name; The field name would be a parameter to your method.

The result would look like this:

private FieldValidation CreateFieldValidation(string fieldName)
{
    return new FieldValidation
    {
        IsRequired = false,
        DataType = "String",
        Length = 0,
        Min = 0,
        Max = 255,
        FieldValidationType =
            _bancPaydatabase.FieldValidationTypes
                            .FirstOrDefault(o => o.FieldName == fieldName),
        IsVisible = true,
        Owner_Country = swedishOwnerCountry
    };
}

Usage would be now like this:

FieldValidation swedishFieldValidation1 = CreateFieldValidation("InvoiceNumber");
FieldValidation swedishFieldValidation2 = CreateFieldValidation("InvoiceTypeId");

If owner country would need to change, too, you would also make it a parameter in the method.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top