stevep
stevep

Reputation: 199

Handling mis-ordered string arguments?

OK, so I have a variety of methods that require a serial number and part number. My problem is that some methods have the order swapped:

void Foo(string serialNumber, string partNumber);
void Bar(string partNumber, string serialNumber);

This is an absolute pain because I have to find all references to these methods and manually check all the variable names and values passed in as arguments. Carefully reading is much harder than compiler errors. I could do something like the following:

public class SNString
{
    public SNString(string serialNumber)
    {
        SerialNumber = serialNumber;
    }

    public string SerialNumber { get; set; }

    public override string ToString()
    {
        return SerialNumber;
    }
}

and reset the methods

void Foo(SNString serialNumber, PNString partNumber);
void Bar(PNString partNumber, SNString  serialNumber);

This allows for compler errors, but it's really ugly to call:

Foo(new SNString("123"), new PNString("456");

I would also have to go through the long slog of fixing all the compiler errors generated by this change, and it's probably more work than manually validating all my method calls. Is there a better way to do this?

Maybe even a coding AI that would look for all variations of variables named "sn", "serialn", etc, and flag potential problems?

Upvotes: 2

Views: 156

Answers (1)

emoacht
emoacht

Reputation: 3591

As Raymond touched on, calling methods with named arguments could be a solution. It assures the correct arguments to be handed over regardless of the order of arguments in method signatures.

You can call Foo and Bar methods with the same order of arguments.

Foo(serialNumber: "Serial Number", partNumber: "Part Number");
Bar(serialNumber: "Serial Number", partNumber: "Part Number");

Upvotes: 1

Related Questions