In these cases, the refactoring is quite easy: extract the common functionality into another subroutine:
functionequal_strings(a,b)returna==bendfunctionequal_strings_ignore(a,b)a,b,=a:lower(),b:lower()returnequal_strings(a,b)-- EDIT: Forgot to change this line after copy-paste 😜end
When the code being toggled happens in the middle of the subroutine, it's often the kind of situation where passing a function as an argument is a better option:
I am an OpenEdge (aka Progress) developer that loves clean code and good looking applications that are easy to use. My main pet project is the Progress DataDigger
Indeed, that was what I intended to do, but apparently I forgot to actually change that line after copy-pasting it. You're totally right in that this only makes sense when you actually use the subroutine with the extracted logic :D
Calling it "inversion of control" almost seems a bit weird to me because it implies that it is the "inverted" form of how it should normally be. But the example of a select (or filter or whatever one wants to call it) function makes it very obvious how it's really just another way to write a loop. It's not "inverted"; it's just normal control-flow.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I find that quite often flags are added to toggle code at the end or at the beginning of a subroutine. For a simple example:
In these cases, the refactoring is quite easy: extract the common functionality into another subroutine:
When the code being toggled happens in the middle of the subroutine, it's often the kind of situation where passing a function as an argument is a better option:
Cases where neither of those apply, are often a sign of over-complicated program logic, or code that shouldn't be shared at all.
Note: examples in Lua because that's what I find easy to write.
But now you have the logic in two places, shouldn't you call one function from the other to avoid that?
Indeed, that was what I intended to do, but apparently I forgot to actually change that line after copy-pasting it. You're totally right in that this only makes sense when you actually use the subroutine with the extracted logic :D
yes, passing the function is what is described in the
inversion of control
article I linked to. Definitely worth a read, a very nice concept.Calling it "inversion of control" almost seems a bit weird to me because it implies that it is the "inverted" form of how it should normally be. But the example of a
select
(orfilter
or whatever one wants to call it) function makes it very obvious how it's really just another way to write a loop. It's not "inverted"; it's just normal control-flow.