Hacker News new | ask | show | jobs
by gjulianm 1449 days ago
I think that drawing conclusions from these examples is not productive at all. In the wild we're going to see functions such as

    def make_string_filename(s):
        # four lines of regex and replace magic
so that we have code like

    file_src = make_string_filename(object_name)
    file_dst = make_string_filename(object_name_2)
which is much more understandable than eight lines of regex magic where you don't even know what the regex is doing.

The problem of not knowing what it does or whether it has side effects or not is more a problem of naming and documentation than DRY. Even then, it's still better than repeating the code all over, simply because when you read and understand the function once, you don't need to go back. On the other hand, if the code is all over, you need to read it again to recognize it's the same piece of code.

2 comments

if those 8 lines of regex have been unit tested and the function is commented to describe "what" the code does, it is entirely the point that you don't need to understand how it works

additionally, the function should be stateless and have no side effects ;)

How do you test 8 lines of regex inside a function that does more things? And what's easier, to write and read the function name or copy-paste the lines with the comment (if the comment explaining what that piece does is even written, that is)?
i'm a bit confused, do we need to know the nitty gritty details of how Math.random() is written, or that it will reliably give us a random double?
you dont you mock the function that have the regex with a fixed behavior and check the actual logic inside the wrapper function
That's fair. But maybe someone wants to reuse this in another place so they do this:

``` def make_string_filename(s, style="new"): # 2 lines of shared magic if style == "old" # 2 lines of original magic elif style == "new": # different 2 lines of magic ```

When you get here, two totally separate `make_string_filenames()`, each private to the area of code they're relevant to, would be better.

The ideal is having 3 functions I think:

- make_string_filename_style1

- make_string_filename_style2

- make_string_filename

Then make_string_filename consists of logic to use the right style.

Or one function and a Sum type to be called like:

    makeStringFilename Style1 "somestring"
Given sum type:

    data FilenameStringStyles = Style1 | Style2
Except that there should be only one way to make a filename from a string. Maybe some options like "allow_spaces" if needed but the point of DRY is not only to share code but to share algorithms.