News for hackers. Stuff that matters.
Re:Be wary of functions which take several parameters of the... by thelazydogsback on Thursday September 26, 2019 @07:34PM (#21086810)
KW's:

  CopyFile(from: 'foo', to: 'bar')
or JS:

  CopyFile({from: 'foo', to: 'bar'})
or as types:

  CopyFile(Source('foo'), Dest('bar'))
or as fluent:

  Copy.from('foo').to('bar')
Re:Be wary of functions which take several parameters of the... by jez on Friday September 27, 2019 @02:01AM (#21088908)
The thing I like the most about the "as types" approach is that once the thing is wrapped, passing it around has zero boilerplate.

In this program below, the only place that suffers from having created a newtype for the strings is the place where they're created (parseArgs) and where they're used (copyFile). None of the other functions (main, helper1, helper2) ever need to peek inside the type, so there's no boilerplate but still all the type safety.

  newtype Source = Source Filename
  newtype Dest = Dest Filename

  -- Boilerplate at usage
  copyFile :: Source -> Dest -> IO ()
  copyFile (Source from) (Dest to) = ...

  -- Boilerplate at creation
  parseArgs :: IO (Source, Dest)
  parseArgs = do
    [arg1, arg2] <- getArgs
    (Source arg1, Dest arg2)

  -- Helpers with NO boilerplate
  helper1 :: Source -> Dest -> IO ()
  helper1 from to = copyFile from to

  helper2 :: Source -> Dest -> IO ()
  helper2 from to = helper1 from to

  main :: IO ()
  main = do
    (from, to) <- parseArgs
    helper2 from to
And by "all the type safety," I mean it's a type error to accidentally swap the args incorrectly to the function call:

    (from, to) <- parseArgs
    helper2 to from
Re:Be wary of functions which take several parameters of the... by mlthoughts2018 on Friday September 27, 2019 @08:22AM (#21091069)
In Python I might do something like this.

    class Source(str):
        pass


    class Dest(str):
        pass


    def helper1(a, b):
        assert isinstance(a, Source)
        assert isinstance(b, Dest)
        copyFile(a, b)

    
    if __name__ == “__main__”:
        # obvs use argparse instead and store
        # directly to Source & Dest objects
        # but here to be quick:
        a, b = sys.argv[1:3]
        a, b = Source(a), Dest(b)
        helper1(a, b)
Re:Be wary of functions which take several parameters of the... by collyw on Friday September 27, 2019 @08:28AM (#21091128)
You know how to complicate something very simple.

What is the advantage here? As I would prefer to have the authors original problem than this.

Re:Be wary of functions which take several parameters of the... by mlthoughts2018 on Friday September 27, 2019 @10:04AM (#21092109)
You’re assuming I would endorse this as a good approach in Python in the real world.

I was merely trying to show how to quickly emulate the Haskell example with less code in Python. Both the Haskell approach and asserting on types in Python seem like wastes of time to me personally, and I’d rather just have copyFile by itself and consenting adults can pass the args they want to pass. Use unit tests to make sure you’re not passing paths the wrong way.

Also, what’s with the attitude? “You know how to complicate something very simple” (from ~15 lines of Python?) — geez, you must be a joy to work with.

Re:Be wary of functions which take several parameters of the... by lonelappde on Friday September 27, 2019 @01:52PM (#21094453)
How is writing extra boilerplate tests better than saying what you mean in the primary code?
Re:Be wary of functions which take several parameters of the... by mlthoughts2018 on Friday September 27, 2019 @03:29PM (#21095475)
It addresses exactly the cases you care about, whereas trying to bake it into designs or type system usually adds heavy restrictions that don’t necessarily have anything to do with your exact use cases.

Basically from a You Aren’t Gonna Need It point of view, doing it in tests lets you minimally address the real use case with much less risk of premature or incorrect abstraction.

In my experience, premature abstraction is one of the worst problems in business software. To contrast two far ends of the spectrum, minimalistic patchworks of gross hacking are asymmetrically way better than overhead of premature or incorrect abstractions.

Re:Be wary of functions which take several parameters of the... by throwaway744678 on Friday September 27, 2019 @09:00AM (#21091418)
Python has named arguments; you can use something like:

    copy(source=file1, destination=file2)

and be done with it. Or am I missing something?
Re:Be wary of functions which take several parameters of the... by mlthoughts2018 on Friday September 27, 2019 @10:06AM (#21092132)
This would do nothing to prevent passing it like

    copy(source=file2, dest=file1)
whereas the parent post is trying to use the type system to make this sort of mistake much more difficult to make.
Re:Be wary of functions which take several parameters of the... by Too on Friday September 27, 2019 @10:38AM (#21092477)
Parent would not stop me from doing this either:

    copy(source=Src(file2), dest=Dest(file1))
At some point you will have to make a human decision which file to copy, only thing helping you out in that situation is that it clearly states on call-site which arg is src and which arg is dest, instead of remembering left or right argument.
Re:Be wary of functions which take several parameters of the... by mlthoughts2018 on Friday September 27, 2019 @03:33PM (#21095500)
Sure, I mean ultimately you could shoot cosmic rays at your computer to rearrange bits and bypass any type safety you want. I don’t get why you think this bears relevance?
Re:Be wary of functions which take several parameters of the... by GordonS on Friday September 27, 2019 @06:13PM (#21096724)
I'm not sure how @Too's example is any worse than named parameters - surely the point is that it's just as likely to transpose source/destination either way.
Re:Be wary of functions which take several parameters of the... by mlthoughts2018 on Friday September 27, 2019 @06:34PM (#21096869)
I think the point is that it’s irrelevant, because type checking or type assertions would take place at the parameter ingestion step specifically to render transposing the arguments impossible.

Any solution could be screwed up on purpose if you’re imagining someone at an interpreter prompt getting the arguments wrong or omitting unit tests that verify a certain file is used as source and a different file as dest... which is why this kind of objection just totally doesn’t matter.

Re:Be wary of functions which take several parameters of the... by kedean on Friday September 27, 2019 @02:53PM (#21095116)
But it's the "wrong" solution for python. Python is heavily focused around the idea of duck-typing, and forcing things like this completely blocks duck-typing. What if I want to pass down a complex object that can be used as a string? Python functions should let me pass any string-like thing I want, which is why named arguments are the preferred way to deal with this. You can even force named arguments using kwargs, I believe this is what the boto interface to AWS does.
Re:Be wary of functions which take several parameters of the... by mlthoughts2018 on Friday September 27, 2019 @06:40PM (#21096909)
Your argument doesn’t work. Python affords you tools like metaclasses, __instancecheck__, __subclasshook__, properties and descriptors exactly so you can use the type system to determine how duck typing is handled in whatever cases you want.

Using inheritance and metaprogramming to enforce how and when a given instance or class object satisfies the contract of some interface is a core, fundamental, first-class aspect of Python.

Just because you don’t need to use it very often doesn’t mean “it’s the wrong choice for Python” or anything like that at all.

It is a thing Python goes way out of its way to enthusiastically support, so therefore it is absolutely a Pythonic way to solve problems.

Re:Be wary of functions which take several parameters of the... by Spoom on Friday September 27, 2019 @11:01AM (#21092731)
Such an error would be immediately obvious on code review. The idea is to make it obvious, not foolproof.
Re:Be wary of functions which take several parameters of the... by mlthoughts2018 on Friday September 27, 2019 @06:46PM (#21096960)
In static typing paradigms, the idea most certainly is to make it foolproof and not merely easy to spot. Literally to convert the problem into something the compiler can prove is unbroken.

Not saying this makes static typing better or anything, just pointing out that “easy to spot in code review” is massively different from “absolute mathematical proof this problem isn’t affecting me.”

I’d argue you rarely care about such compiler proofs in real software development, but that’s beside the point if you assume a static typing paradigm has already been chosen.

Re:Be wary of functions which take several parameters of the... by Multicomp on Friday September 27, 2019 @05:37AM (#21090036)
This is the killer feature that made me sit up and take notice of F#.

Add exhaustive pattern matches and I was hooked

Re:Be wary of functions which take several parameters of the... by kragen on Friday September 27, 2019 @10:02AM (#21092092)
Levels of indirection are not a “code smell” but they offer many more opportunities for bugs than parameter list order does.
Re:Be wary of functions which take several parameters of the... by lonelappde on Friday September 27, 2019 @01:50PM (#21094437)
How?
Re:Be wary of functions which take several parameters of the... by edflsafoiewq on Friday September 27, 2019 @07:10AM (#21090579)
In another module, there's the boilerplate of importing Source and Dest.
Re:Be wary of functions which take several parameters of the... by masklinn on Friday September 27, 2019 @07:17AM (#21090622)
They get brought in alongside the functions. Especially given Haskell (sadly) defaults to unqualified import.
Re:Be wary of functions which take several parameters of the... by Shoue on Friday September 27, 2019 @08:10AM (#21090968)
Not necessarily, you can use coerce or Newtype instances, so you'd import one thing to deal with all the boilerplate wrapper types in all the modules they come from. This is specific to Haskell, but you could mimic it in other languages.
Re:Be wary of functions which take several parameters of the... by raverbashing on Friday September 27, 2019 @05:16AM (#21089923)
Yes but creating the scaffolding is the hard part and getting to the "once the thing is wrapped" takes more time than the other solutions.

You could "force" parameter naming, and it would be easier.

Types are good but having 10 types of string doesn't make sense.

Re:Be wary of functions which take several parameters of the... by louthy on Friday September 27, 2019 @07:11AM (#21090590)
> Types are good but having 10 types of string doesn't make sense.

It really does make sense. Types like string, int, float, etc. are poorly defined for most things they represent. There's no context and are just one step away from being dynamic, like values in a dynamic language.

By enforcing a contextual contract (perhaps with additional constructors that constrain the value) you leverage the type-system to do the hard work of checking for stupid mistakes. On large code-bases this reduction in cognitive complexity makes a whole class of bugs go away.

So, 100s of types of string could make sense, it really does depend how many types of thing you have which are distinct and can be represented as a string.

But once they're defined, they're not strings any more, they have an internal state which is a string, yes, but their type is not a string.

Re:Be wary of functions which take several parameters of the... by bluGill on Friday September 27, 2019 @08:07AM (#21090947)
The hard part - at least in languages I've worked with - is how hard it is to create a new string that acts like a string should act but isn't a string. In many (C's typedef) you can create two new types, but nothing stops you from using mixing them up as they freely convert to each other without even a warning. In some object oriented languages you can often create a new string - but only by writing by hand every single member function.

Of course none of the above are unsolvable problems. I've never seen anything that actually makes it easy, but I won't claim to have seen everything.

Re:Be wary of functions which take several parameters of the... by lonelappde on Friday September 27, 2019 @01:54PM (#21094473)
You are conflating dynamic types with weak types. Int is a relatively weak type and HttpPort is a strong type regardless whether static or dynamic
Re:Be wary of functions which take several parameters of the... by eterps on Friday September 27, 2019 @06:35AM (#21090360)
> Types are good but having 10 types of string doesn't make sense.

Not if the strings are clearly distinct (like a name being different from an e-mail address).

Re:Be wary of functions which take several parameters of the... by michaelcampbell on Friday September 27, 2019 @07:54AM (#21090852)
> 10 types of string

It's not. It's 10 types.

Re:Be wary of functions which take several parameters of the... by bewo001 on Monday September 30, 2019 @11:12AM (#21116175)
I want to agree, but the problem is that you now need 10 versions for many operations that are in a string library. Hidden assumptions -- like 'replacing a character in a string can never fail' -- may fail (eg in an email address type which only allows only a limited char set). Some constraints can't be expressed without dependent types (say you want to define a URI type that limits the length to 2000 chars total but is composed of variable length components, like the domain name, query strings etc).
Re:Be wary of functions which take several parameters of the... by michaelcampbell on Wednesday October 02, 2019 @05:17PM (#21140826)
> but the problem is that you now need 10 versions for many operations that are in a string library

Do you? Or do you need just the operations for the things that are relevant to the type at hand? Limiting a broad API to the needed interface for the type you're modeling is a GOOD thing.

Re:Be wary of functions which take several parameters of the... by kragen on Friday September 27, 2019 @08:07AM (#21090944)
I agree that named parameters are a better solution in this case.

A problem I have with the types solution is that, although it's easy to tell if the code is wrong, it's often a bit of a puzzle in my experience to figure out how to write it in the first place: "Hmm, this takes a Foo and a Bar. Can I construct a Foo from a string? No, but I can construct it from a Baz or a Quux. Can I construct a Baz from a string? No, just an int. How about a Quux? Yeah, there we go. Now, how about that Bar?". And I've seen other people have that problem too, especially novice programmers. I'm not a novice but it's still a problem for me in a new type-heavy API.

I realized I was creating that problem in Yeso, and I couldn't figure out how to simplify the API, so in addition to starting the documentation with complete examples, I made a graph with graphviz that shows the type structure of the API: https://gitlab.com/kragen/bubbleos/blob/master/yeso/README.m...

I don't have that problem with named-parameter interfaces (I just look at the list of methods and parameter lists), and maybe I could run into it with fluent interfaces in theory, but in practice that hasn't been much of a problem in my experience.

The article author was writing in Golang, which doesn't have named parameters, but in languages like Python, Lua, Clojure, or, as you say JS, named parameters are straightforward. In Lua it's even simpler than in JS:

    copy {from='presentation.md', to='/tmp/backup'}
I would never claim that Lua isn't bug-prone, though!
Re:Be wary of functions which take several parameters of the... by gregmac on Thursday September 26, 2019 @11:03PM (#21088038)
> Copy.from('foo').to('bar')

Funny, I don't think I've actually seen a fluent file API like this before. I guess most languages have file I/O built in to their standard libraries.

My immediate reaction to this, though, is that you could make it more general:

    File('foo').CopyTo('bar');
You could then also have

    .ReadAsText()

    .MoveTo(target)

    .SetOwner(owner)

    .GetFullPath() 
This is readable and solves the problem the original post is discussing, but it's also nice when learning because an IDE can give very useful help about possible operations, and all you have to remember is the File() function.
Re:Be wary of functions which take several parameters of the... by yawgmoth on Friday September 27, 2019 @08:00AM (#21090901)
Personally, in C#, I don't enjoy debugging and maintaining Fluent APIs. An exception thrown in the chain is sometimes opaque and the necessary extension methods to make everything come together is not neat code. The former reason is why I also discourage use of object initializers.
Re:Be wary of functions which take several parameters of the... by tluyben2 on Friday September 27, 2019 @09:39AM (#21091796)
I like those API's much better for reading, but when there are issues with them, like you say, debugging is often a right pain compared to the other examples. Especially when a chain became a bit too long (over time) and there is suddenly a null somewhere (for whatever reason). VS indicates the error in the first line of the chain and debugging can become quite hairy.

Is that better in other language runtimes/debuggers?

Re:Be wary of functions which take several parameters of the... by GordonS on Friday September 27, 2019 @06:17PM (#21096751)
If you want to be more opaque, I guess you could do:

```c# var file = File("source"); file.CopyTo("target"); ```

(apologies if this is formatted badly; no clue what HN supports here, and I'm on mobile)

Re:Be wary of functions which take several parameters of the... by lonelappde on Friday September 27, 2019 @01:57PM (#21094495)
The proper place to pay the dev cost is once in the library, not in all its callers.
Re:Be wary of functions which take several parameters of the... by stouset on Friday September 27, 2019 @03:11AM (#21089262)
Your suggestion is basically Ruby’s `Pathname` class (sans convenient copy method).
Re:Be wary of functions which take several parameters of the... by xeeeeeeeeeeenu on Friday September 27, 2019 @08:55AM (#21091362)
That's how Perl's Path::Tiny[1] works, for example:

  path("/tmp/foo.txt")->copy("/tmp/bar.txt");
[1] - https://metacpan.org/pod/Path::Tiny
Re:Be wary of functions which take several parameters of the... by kragen on Friday September 27, 2019 @10:09AM (#21092165)
Amusingly, this has the same ambiguity problem the original post was trying to solve!
Re:Be wary of functions which take several parameters of the... by anonytrary on Friday September 27, 2019 @01:31AM (#21088737)
> also nice when learning because an IDE can give very useful help about possible operations

Why is chaining necessary for this? On-instance tab-autocomplete list-all on-tab accomplishes the same thing.

Re:Be wary of functions which take several parameters of the... by skrebbel on Friday September 27, 2019 @03:10AM (#21089261)
> On-instance tab-autocomplete list-all on-tab

I have no idea what you just said.

Re:Be wary of functions which take several parameters of the... by nurettin on Friday September 27, 2019 @04:11AM (#21089586)
I think it means:

(While editing code, position the cursor) on (a class) instance (and press) tab (to swith to) autocomplete (mode and) list all (members of that instance by clicking) on tab (again).

Re:Be wary of functions which take several parameters of the... by coldtea on Friday September 27, 2019 @04:57AM (#21089828)
He said that clicking TAB on an instance in an IDE

(e.g. foo.[TAB])

can list all possible operations available on that instance -- in other words, you don't need a fluent interface for this.

Re:Be wary of functions which take several parameters of the... by jjoonathan on Thursday September 26, 2019 @08:09PM (#21087084)
or as Objective C:

    [[NSFileManager defaultManager] copyItemAtPath:src toPath:target error:&error];
Inspired by smalltalk, of course. ObjC's verbosity is legendary, and I'm not its hugest fan, but there's a key innovation here that I am a huge fan of: the language forces other people to name their arguments, in much the same way that python forces other people to indent their code, even if they would otherwise default to making a hot mess of things.
Re:Be wary of functions which take several parameters of the... by Scapeghost on Thursday September 26, 2019 @10:10PM (#21087786)
That verbosity isn't even a big deal as you write once, but read many times.

One of the first things about Swift that I fell in love with was the difference between things like DrawRect(10, 20, 30, 40) in languages like C#, and DrawRect(at: origin, width: 30, height: 40) in Swift.

Re:Be wary of functions which take several parameters of the... by anonytrary on Friday September 27, 2019 @01:33AM (#21088751)
Named function parameters are nice, but you can accomplish something similar with only two more characters in some languages:

      DrawRect({at: origin, width: 30, height: 40})
  vs. DrawRect(at: origin, width: 30, height: 40)
I can understand why this is considered a nice-to-have. The verbosity didn't really change.
Re:Be wary of functions which take several parameters of the... by thom on Friday September 27, 2019 @05:53AM (#21090112)
And then you have to check that the map you're being given has all the correct keys with the correct typed values. And when you're looking at the code, you see:

function DrawRect(options) {...

Unless you're immediately destructuring it or whatever. I don't think it's _that_ straightforward to compare the two, unless I'm thinking of the wrong languages here.

Re:Be wary of functions which take several parameters of the... by Too on Friday September 27, 2019 @10:46AM (#21092551)
Typescript can specify required keys in a dictionary: function DrawRect(options: { at: Point2D, width: number, height:number}}

It will be checked compile time that all keys are provided (unless dict comes from serialized json or something).

Re:Be wary of functions which take several parameters of the... by thom on Friday September 27, 2019 @04:43PM (#21096092)
That's more verbose than just having arguments though, right?
Re:Be wary of functions which take several parameters of the... by Too on Saturday September 28, 2019 @01:18AM (#21098605)
Slightly more verbose but not much. Just having arguments takes you back to square one where you might mix up the order of width and height since nothing is forcing the caller to use named parameters. Perhaps it would be better to have some linter enforcing such things.
Re:Be wary of functions which take several parameters of the... by thom on Sunday September 29, 2019 @06:52AM (#21106311)
It doesn't take you back to square one in languages which enforce named parameters, which I thought we were talking about.
Re:Be wary of functions which take several parameters of the... by kalleboo on Friday September 27, 2019 @02:53AM (#21089169)
You can accomplish it in other languages, but will all the other library authors do so? Do the OS libraries do so?
Re:Be wary of functions which take several parameters of the... by wruza on Friday September 27, 2019 @02:21AM (#21089001)
Two more characters and one more allocation per each LoC.
Re:Be wary of functions which take several parameters of the... by a13n on Friday September 27, 2019 @04:23AM (#21089653)
Most of us are just writing crud apps anyway so one more allocation is extremely affordable
Re:Be wary of functions which take several parameters of the... by lonelappde on Friday September 27, 2019 @02:03PM (#21094541)
Maybe but this highly dynamic programming style is why Macs have always been so much slower than Windows on equivalent hardware.
Re:Be wary of functions which take several parameters of the... by Scapeghost on Friday September 27, 2019 @02:47PM (#21095048)
Where did that come from? Apart from games that were obviously optimized for Windows first then ported to macOS, has that claim been measured? Because macOS has always certainly FELT faster than Windows.
Re:Be wary of functions which take several parameters of the... by anonytrary on Saturday September 28, 2019 @02:22AM (#21098811)
As if my app stops working because of this?
Re:Be wary of functions which take several parameters of the... by masklinn on Friday September 27, 2019 @07:21AM (#21090636)
> I can understand why this is considered a nice-to-have.

Well typing is one good reason, maps usually are not statically typed with key:value pairs. That's more of a class / struct thing. And then the verbosity increases quite a bit.

Re:Be wary of functions which take several parameters of the... by gregoryl on Thursday September 26, 2019 @11:16PM (#21088091)
You can (optionally) do the same name specified parameters in the more recent versions of c#.
Re:Be wary of functions which take several parameters of the... by Scapeghost on Thursday September 26, 2019 @11:39PM (#21088188)
Their documentation still encourages unnamed parameters:

https://docs.microsoft.com/en-us/dotnet/api/system.drawing.r...

Re:Be wary of functions which take several parameters of the... by __m on Friday September 27, 2019 @01:53AM (#21088858)
You can do that in c#, though an IDE like Rider can also display it like that when no label is provided, or insert the labels, depending on your preference.
Re:Be wary of functions which take several parameters of the... by jjoonathan on Friday September 27, 2019 @09:38AM (#21091787)
IntelliJ does that for Java these days too, and I love it.

I'd rather have syntax-level support (works with ctrl+f, works outside IDEs, works in IDE when auto-analysis is broken), but if IDE support is what I can get, I'll take it.

Re:Be wary of functions which take several parameters of the... by naniwaduni on Thursday September 26, 2019 @10:18PM (#21087834)
> That verbosity isn't even a big deal as you write once, but read many times.

One of the most pernicious myths of software engineering is that it happens.

Re:Be wary of functions which take several parameters of the... by Scapeghost on Thursday September 26, 2019 @10:29PM (#21087883)
"Reading" code in this sense doesn't just mean explicit review by different people, but also as in reading it subconsciously as you scroll through your own code.

If I see a chain of numbers like 1, 2, 3, 4 my brain has to recall the order of parameters or look it up.

If I'm looking for rectangles that should be wider than they are tall, I have to keep thinking "the third number should be higher than the fourth number"

Oh and I can't just Cmd+F "width:" or "height:" either.

Re:Be wary of functions which take several parameters of the... by kragen on Friday September 27, 2019 @10:17AM (#21092250)
It's unusual to sit down and read a subroutine for pleasure, but it's common to read it when you're debugging a problem, trying to figure out how to extend the subroutine, refactoring something it calls, or doing something similar somewhere else.
Re:Be wary of functions which take several parameters of the... by benji-york on Friday September 27, 2019 @08:18AM (#21091029)
I would enjoy an explanation of your thinking.
Re:Be wary of functions which take several parameters of the... by istjohn on Friday September 27, 2019 @08:53AM (#21091336)
In Python, by default you can use keyword arguments for any function parameter.

And if you want, you can make arguments keyword-only:

  def copyFile(*, source, dest):
      ...
Parameters after the asterisk cannot be specified by positional arguments. It must be called with keyword arguments:

  copyFile(source=src, dest=dst)
Re:Be wary of functions which take several parameters of the... by jjoonathan on Friday September 27, 2019 @09:15AM (#21091571)
Python's kwargs are still optional in the sense that I care about. Same goes for many other kwarg-supporting languages.

The strategy you propose can only force other people to use kwargs when calling functions you write. When you're reading code, there is no guarantee that arguments to functions you didn't write will be labeled, and indeed they often aren't, even when they ought to be. In ObjC, all arguments are labeled, always. It's heavily opinionated, and the experience is qualitatively different as a result.

Re:Be wary of functions which take several parameters of the... by Cthulhu_ on Friday September 27, 2019 @04:45AM (#21089773)
This syntax is part of the reason why I really enjoyed working with objective-C, it's just so self-descriptive. Coming from Java which doesn't have that, which relies on an IDE like intellij to give you hints on what arguments go where, OR on design patterns like argument objects or builders, it was a big relief - even if it's kinda long / verbose.

Honestly thinking back on Java there were a lot of design patterns and code (sometimes generated) that could've been avoided with e.g. named function parameters.

Re:Be wary of functions which take several parameters of the... by cat199 on Thursday September 26, 2019 @08:21PM (#21087168)
> otherwise default to making a hot mess of things.

one can still make a hot mess of 1000-wide lines, bad variable names, and various other forms of spaghetti cowboy-ism.

Re:Be wary of functions which take several parameters of the... by jjoonathan on Thursday September 26, 2019 @08:23PM (#21087185)
Yep, no doubt about it.

My aim isn't to argue that forced named args will cure all that ails you, just to share that they "feel" quite different from optional named args, and that on the balance I felt they were a net positive.

Re:Be wary of functions which take several parameters of the... by elliottkember on Thursday September 26, 2019 @10:29PM (#21087879)
outputImageProviderFromBufferWithPixelFormat:pixelsWide:pixelsHigh:baseAddress:bytesPerRow:releaseCallback:releaseContext:colorSpace:shouldColorMatch
Re:Be wary of functions which take several parameters of the... by jasonhansel on Thursday September 26, 2019 @10:15PM (#21087819)

  [NSCarpalTunnelSyndromeInducer induceCarpalTunnelSyndromeForProgrammer: ....]
Re:Be wary of functions which take several parameters of the... by teej on Thursday September 26, 2019 @10:22PM (#21087844)
Or, ya know, you use XCode and it autocompletes the function signature for you.
Re:Be wary of functions which take several parameters of the... by wruza on Friday September 27, 2019 @02:24AM (#21089019)
[NSStream dammit]
Re:Be wary of functions which take several parameters of the... by TheCoelacanth on Thursday September 26, 2019 @11:12PM (#21088076)
Okay then

     [NSEyeStrainInducer induceEyeStrainForProgrammer: ....]
Unless XCode can read the signature for me in addition to writing it
Re:Be wary of functions which take several parameters of the... by arcticbull on Friday September 27, 2019 @04:40AM (#21089752)
Good news, it can! Either way objective-c is much more readable than it is writeable. It’s writeable with an IDE and readable without.
Re:Be wary of functions which take several parameters of the... by root_axis on Thursday September 26, 2019 @10:56PM (#21088004)
XCode is really unpleasant as far as IDEs go.
Re:Be wary of functions which take several parameters of the... by friend-monoid on Friday September 27, 2019 @04:34AM (#21089714)
As C:

  struct copy_args_s {
    char * src;
    size_t src#;
    char * dest;
    size_t dest#;
  };
  int copy(struct copy_args_s args) {
    ...
  }
  int main() {
    copy((struct copy_args_s){ .src = "foo", .src_len = 3, .dst = "bar", .dst_len = 3 });
  }

Or with some macro magic:

  struct copy_args_s {
    char * src;
    size_t src#;
    char * dest;
    size_t dest#;
  };
  int copy(struct copy_args_s args) {
    ...
  }

  #define copy(...) copy((struct copy_args_s){__VA_ARGS__})

  int main() {
    copy(.src = "foo", .src_len = 3, .dst = "bar", .dst_len = 3);
  }
Re:Be wary of functions which take several parameters of the... by coldpie on Friday September 27, 2019 @08:34AM (#21091182)
> Or with some macro magic

Stop! Put down the editor and step away from the compiler, please. No one wants to get hurt.

Re:Be wary of functions which take several parameters of the... by elygre on Friday September 27, 2019 @04:20AM (#21089635)
In the fluent scenario, I will be waiting for the instruction to execute:

   Copy.from('foo').to('bar').execute();
Because of variations like these:

   Copy.from('foo').to('bar').owner('me');
   Copy.to('bar').from('foo');
Re:Be wary of functions which take several parameters of the... by toyg on Thursday September 26, 2019 @07:59PM (#21087015)
or as Python:

   shutil.copy(src='foo', dst='bar')
That's straight out of stdlib, btw.
Re:Be wary of functions which take several parameters of the... by echelon on Thursday September 26, 2019 @08:05PM (#21087051)
Those are keyword args and are not specific to just Python. :)

The parent post outlines many techniques, including this. Some are more apt than others depending on your language of choice.

I would argue that there's another option of passing a strongly typed struct for args, and that the JavaScript and Ruby solution of dicts falls between this and kwargs.

I'm fond of properly designed fluent APIs, myself.

While on the subject of homogenous argument types, especially bad are the APIs that not only accept the same types, but have order semantics that differ between functions within the same library. PHP used to be a notoriously bad example of this with respect to their needle and haystack search parameters. (I think they fixed it?)

Re:Be wary of functions which take several parameters of the... by toyg on Thursday September 26, 2019 @08:38PM (#21087303)
Yeah, I was just showing that in Python keyword arguments are first-class in every respect, which is not that common.

The "JS solution" for example is not a solution, but only a convention: the actual interface is just expecting an object, and there is no explicit check on the validity of such object or its contents. That is nowhere near "strongly typed", if anything it's weaker than average.

Re:Be wary of functions which take several parameters of the... by thelazydogsback on Thursday September 26, 2019 @08:56PM (#21087431)
> The "JS solution" for example is not a solution, but only a convention: the actual interface is just expecting an object,

Well if it uses de-structuring syntax, then it can be type-checked.

Re:Be wary of functions which take several parameters of the... by tomjakubowski on Thursday September 26, 2019 @09:59PM (#21087715)
De-structuring syntax isn't required, this is just as easily type-checked:

    interface CopyArgs {
        src: string;
        dst: string;
    }

    function copy(args: CopyArgs) {
        exec(["cp", args.src, args.dst])
    }
Re:Be wary of functions which take several parameters of the... by thelazydogsback on Friday September 27, 2019 @12:13AM (#21088342)
Sure, if you want to get all interfacy - but pretty soon it'll be Java :)
Re:Be wary of functions which take several parameters of the... by davedx on Friday September 27, 2019 @07:16AM (#21090613)
Hah I thought that initially, but TypeScript interfaces are simpler (and usually co-sited) compared to their OO cousins. I find them a pleasure to use.
Re:Be wary of functions which take several parameters of the... by RobertKerans on Friday September 27, 2019 @01:52AM (#21088851)
It can, manually (as it can for a non-destructured object), but it has no typing guarantees - the function will still happily be interpreted and run as long as _any_ object is given as an argument.
Re:Be wary of functions which take several parameters of the... by ambicapter on Friday September 27, 2019 @01:02AM (#21088602)
> (I think they fixed it?)

No, they put out a conf talk that stated that there _was_ a logic to it, you just needed it to be explained to you.

Re:Be wary of functions which take several parameters of the... by timw4mail on Friday September 27, 2019 @09:08AM (#21091496)
Really, most of the relevant PHP functions are just thin wrappers around the C functions with the same name.

But nobody talks about how nonsensical C function names are.

Re:Be wary of functions which take several parameters of the... by Waterluvian on Thursday September 26, 2019 @11:25PM (#21088130)
I love this part of Python. I can choose to include the argument names if I think they tell a more clear story.
Re:Be wary of functions which take several parameters of the... by ww520 on Thursday September 26, 2019 @08:22PM (#21087178)
Swift has keyword parameter for function parameters, as in copy(from: "foo", to: "bar")
Re:Be wary of functions which take several parameters of the... by goatinaboat on Friday September 27, 2019 @03:01AM (#21089213)
Did they fix the thing where the first argument can’t be named but the rest can? I kicked the tyres on Swift when it was new and that was a real turn-off.
Re:Be wary of functions which take several parameters of the... by ww520 on Friday September 27, 2019 @03:19AM (#21089313)
The first argument can be named just fine.

    func fn1(myLabel1 myParam1: int, myLabel2 myParam2: int) {
    }

    fn1(myLabel1: 123, myLabel2: 456)

    func fn2(_ myParam1Omitted: int, myLabel2 myParam2: int) {
    }

    fn2(123, myParam2: 456)
Re:Be wary of functions which take several parameters of the... by masklinn on Friday September 27, 2019 @07:28AM (#21090684)
Yes, however that wasn't the case before SE-0046 (Swift 3): the early iterations had much stronger ties to objective-c where the method "names" the first parameter, so the first parameter could not be labelled separately.

From Swift 3 onwards, parameters and their labelling is completely consistent.

GP is wrong in one place though (at least for swift 2, not sure for swift 1): you could label the first formal parameter explicitly, it just wouldn't be labelled by default (unlike other parameters). That is:

    func f(p1:p2:)
would define

    f(_:p2:)
but

    func f(p1 p1:p2:)
would define

    f(p1:p2:)
Also, just to make things weirder, this special-casing would not apply to initialisers.
Re:Be wary of functions which take several parameters of the... by masklinn on Friday September 27, 2019 @07:27AM (#21090671)
That was fixed in Swift 3.0 following the acceptation of SE-0046.

In Swift 1.0, this applied to methods but not functions as it was following up from Objectice-C (foo:bar:baz: would become foo(_:bar:baz)), in Swift 2.0 it was expanded to all callables, and in Swift 3.0 it was removed and to be specified explicitly making labelling completely consistent.

Re:Be wary of functions which take several parameters of the... by goatinaboat on Friday September 27, 2019 @08:01AM (#21090908)
Thanks!
Re:Be wary of functions which take several parameters of the... by GordonS on Friday September 27, 2019 @06:23PM (#21096795)
You can get something like your last example in c#:

```c# var source = new FileSystemFile("source"); source.CopyTo("target"); ```

Of course, this isn't the only way to do it; you get the usual footguns as described in the article too.

Also apologies if the formatting is crappy - on mobile, and TBH not sure what markdown-like syntax HN supports, despite being a long-time user!

Re:Be wary of functions which take several parameters of the... by reifiedgent on Thursday September 26, 2019 @10:07PM (#21087772)
or C#:

CopyFile(src: "foo", dest: "bar");

Re:Be wary of functions which take several parameters of the... by gnud on Friday September 27, 2019 @03:34AM (#21089400)
c# already has the 'chained' API in the standard library:

    new FileInfo(srcPath).CopyTo(dstPath)
On the other hand, it also has the more error-prone

    File.Copy(sourceFileName,destFileName);
Re:Be wary of functions which take several parameters of the... by Lio on Friday September 27, 2019 @04:06AM (#21089557)
I know nothing about C# so please pardon my ignorance but how does:

  new FileInfo(srcPath).CopyTo(dstPath);
provide more protection vs

  CopyFile(src: srcPath, dest: dstPath);
Assuming that both path strings are set correctly isn't a typo here going to cause the same error and be just as visible?

e.g.

  new FileInfo(pathA).CopyTo(pathB);
  CopyFile(src: pathB, dest: pathA);
neither would seem to show which is correct without knowing what the path values are if the variable names are ambiguous.
Re:Be wary of functions which take several parameters of the... by gnud on Friday September 27, 2019 @07:03AM (#21090533)
When using the FileInfo api, it's obvious which argument is the source and which argument is the destination. When using the CopyFile, it's not.

If you can't keep track of your variable names, then using keyword arguments, like others here talk about, won't help much, either.

Re:Be wary of functions which take several parameters of the... by Lio on Friday September 27, 2019 @07:21AM (#21090637)
Sorry, not sure if your parent was edited to remove keynamed parameters from the second example or if I've responded to the wrong comment.

I'd definitely agree with you that the not having named arguments is worse than your method chained example.

To me named parameters seem to be on a par with the chained OO api.

Re:Be wary of functions which take several parameters of the... by gnud on Friday September 27, 2019 @08:27AM (#21091112)
Ah, the reason is simple: C# allows named parameters, but do not enforce them. You can call File.Copy both as

    File.Copy(a,b)
and

    File.Copy(sourceFileName: a, destFileName: b)
And confusingly, also as

    File.Copy(destFileName: b, sourceFileName: a)
Re:Be wary of functions which take several parameters of the... by Lio on Friday September 27, 2019 @10:51AM (#21092623)
OK I see. That explains it and also gives a very concrete reason for using the chained API. Thanks.
Re:Be wary of functions which take several parameters of the... by keithnz on Thursday September 26, 2019 @10:56PM (#21088006)
this doesn't really solve the problem, its a little better, however, as it STILL accepts positional arguments you can still get in trouble if you don't use parameter names.
Re:Be wary of functions which take several parameters of the... by alkonaut on Friday September 27, 2019 @04:08AM (#21089569)
A compile time analyzer that says "always use named parameters when calling functions with similar type of consecuitve arguments" should be pretty easy to write.

It would be better to have a foolproof API, but obviously it can't change now.

Re:Be wary of functions which take several parameters of the... by GarvielLoken on Friday September 27, 2019 @03:44AM (#21089456)
new File().Source("xyz").CopyTo("zyx") is the cleanest I believe, and also the most (real) OO way.
Re:Be wary of functions which take several parameters of the... by DarkWiiPlayer on Friday September 27, 2019 @08:30AM (#21091137)
> and also the most (real) OO way.

No. Far from it. First of all, what is File in your example? a class? an object? and what does File().Source() return? an object? what does that object represent?

If you want it to be OO, you have a File object, to which you send a "copy" message. Depending on how strictly OO you want it to be, it then returns the new file object (or a reference to it).

Re:Be wary of functions which take several parameters of the... by ulucs on Friday September 27, 2019 @08:28AM (#21091130)
for things that have clear direction,

    'foo' `copyTo` 'bar'
Re:Be wary of functions which take several parameters of the... by yellowapple on Thursday September 26, 2019 @09:05PM (#21087482)
Or sidestep this problem entirely by being explicit:

    contents = ReadFile('foo')
    WriteFile('bar', contents)
Or more concisely:

    WriteFile('bar', ReadFile('foo'))
(Of course, this would likely preclude the ability to do some means of copying that doesn't involve reading the whole file into memory).
Re:Be wary of functions which take several parameters of the... by jiggawatts on Thursday September 26, 2019 @09:18PM (#21087538)
Please don't ever recommend such code, even in jest.

This is Wrong, with a capital W.

The file copy API is fundamentally different to reading and and then writing the contents of a file.

The "copy" system call on most platforms also:

- Copies metadata such as attributes.

- Copies alternate data streams.

- Preserves advanced features such as sparse files, compression, encryption, BTRFS/ReFS/ZFS integrity settings.

- Can copy externally archived files without restoring them.

- Can copy files server-to-server without transferring the data to the client computer.

- Copies block-by-block instead of all at once, allowing files to be copied that do not fit into memory.

- Copies asynchronously so that reads and writes are overlapped

- Etc...

Re:Be wary of functions which take several parameters of the... by viraptor on Friday September 27, 2019 @01:34AM (#21088753)
- can be almost instant and copy only metadata on CoW filesystems
Re:Be wary of functions which take several parameters of the... by yellowapple on Friday September 27, 2019 @12:58PM (#21093926)
There are lots of usecases where the things you mention are either not important or outright bad. My code also allows for extra data processing steps in between should the use case evolve beyond mere copying.

The code above could, however, just deal with references to some file handle and not actually read or write the contents (though ReadFile() or WriteFile() would be less-than-ideal names for such functionality).

Re:Be wary of functions which take several parameters of the... by kedean on Friday September 27, 2019 @03:00PM (#21095212)
That completely ignores the purpose of the abstraction. Copy is a high level concept that, yes, can sometimes be reduced to a read/write pipeline, but in many cases cannot. Interfaces and abstractions are important concepts that you shouldn't naively discard.

You're also focusing too much on the example, and missing the greater problem. There are other cases that fit the original problem, such a sending an email (who is the sender and who is the receiver?)

Re:Be wary of functions which take several parameters of the... by yellowapple on Friday September 27, 2019 @06:31PM (#21096847)
> Copy is a high level concept

My point is that the high-level concept is not always appropriate. Sometimes it's overkill. Sometimes it's outright wrong.

> sending an email (who is the sender and who is the receiver?)

The sender is already encoded in the message itself in that case. The receiver is specified as a specific SMTP message, last I checked. So this problem wouldn't really apply here.

Even if it did, though, the separated functions would still be useful here:

    msg = NewMessageFrom("[email protected]")
    AddSubject(msg, "Did you ever hear the tragedy of Darth Plagueis the Wise?")
    AddBody(msg, "I thought not.  It's not a story the Jedi would tell you.")
    Send(msg, "[email protected]")
Re:Be wary of functions which take several parameters of the... by bluGill on Friday September 27, 2019 @08:12AM (#21090983)
If your file operations are designed for it they can recognize the copy situation above and fix it. I don't think it is practical to implement it, but I can design a toy language that would do the above. (Toy because to make it possible to do the above I would have to compromise other things wroth having)
Re:Be wary of functions which take several parameters of the... by kragen on Friday September 27, 2019 @10:23AM (#21092311)
You can definitely make the API you describe do the things you say it can't, as well as the things other grouchy commenters are saying it can't. But in that case it might be better to rename ReadFile to Source and WriteFile to CopyTo.