Clean Coding - Real-World Examples (EP 0) - Refactoring C# to Eliminate Duplication (DRY Principle)

preview_player
Показать описание
In today's episode, we identify some duplicated code segments and eliminate them by moving duplicated code to a shared method and using some additional local variables.

Alright, here's an example of some duplication that can be removed.

So we have two methods here that are event handlers for a context menu click. One is to select Sort Descending and the other is Sort Ascending. But you'll see, the implementations repeat this line and this line. The only real difference is that this line has a different value. That means we can create a subroutine out of this and just pass this value and eliminate that duplication.

So make a new method. I'll call it SortSelectedColumn because that's what we're operating on here, and we're going to want a SortDirection argument.

Alright, I'll just copy this down, and now we'll make this be this...

Hmmm, yeah there's more that we can do here too. So we'll start, though, by just calling our new method. There ya go.

Cool, so we got rid of the duplication. There's some more duplication, though, still in here. One is this phrase and the other is this method. Let's start with the phrase.

So that data type, I'll hover here - it's OrderByColumns, so OrderByColumns. Ooops, my indentation got off because of that. Let's try that again - Boop! Alright. So this actually making the routine larger, but it's more efficient because we're not dereferencing these object properties twice. Also can enhance readability a little bit.

OK, let's go after the other offender, this "zzSelectedColumn". OK, so here we got... do doot do due do dew... a bunch of stuff happening, right? It's calling another method here, doing some more work, so we *really* don't want to call that twice.

Go back here... You know, usually I don't want to declare a variable before it gets used because, let's say this for some reason caused an exception, then we would have wasted work making that other instance. So I'm going to move it down here, even though it might be tidy to have them both up here, 'cuz right? This one will be, um, is it an OrderByColumn? Just a Column. Alright. We get the selected column and then we say... we *really do* want to move it down here. So we'll get that sort column, set its sort direction and then add it.

Alright, so there we go!
Рекомендации по теме