Copying strings in a less ugly way

So, for one reason or another, I was in a method that I had limited power to refactor. In this method there where two strings that, if certain conditions applied, needed to have the same value (Yeah, don’t get me started).

Let’s say it looked something like this:

s1 = "Hello";
s2 = "World";
s3 = "Hello Brave New World";

[...]
if(SomeCondition)
{
s1 = s3;
s2 = s3;
}
[...]

“So, what the hell can I do to make it less of an eyesore?”, I thought to myself.

After thinking about it, I came up with this:

private static (string, string) DuplicateString(string s)
{
    return (s, s);
}

And the end result looks like this instead:

s1 = "Hello";
s2 = "World";
s3 = "Hello Brave New World";

[...]
if(SomeCondition)
{
(s1, s2) = DuplicateString(s3);
}
[...]

Still not good, but a whole lot better!

Leave a Reply

Your email address will not be published. Required fields are marked *