top | item 43720623

(no title)

disillusionist | 10 months ago

I started using this pattern years ago and haven't looked back. React components are defined using a single properties param and it feels natural to extend the practice to other methods and helper functions that I write.

One nice unexpected side effect is that I end up with more consistency in variable naming when using a param object in order to benefit from object definition shortcuts.

ie I will usually write something like

  const firstName = getFirstName(); doTheThing({ firstName });
rather than

  const fName = getFirstName(); doTheThing({ firstName: fName });

discuss

order

hyperhello|10 months ago

What bothers me a lot is that return values can't have a name. Suppose I have a function

string combineName(string first, string last);

Okay, I assume the result is the full name, but I don't really know that like I would if the return had a name in the header. (The function can be getFullName, yes, but that's so simple it doesn't matter).

disillusionist|10 months ago

you can do this rather easily by returning an object rather than a primitive. if you're using a language like TypeScript, destructuring the resulting returned object is rather trivial and (in my opinion) delightful to read. eg

  function combineNames({ first, last }) {
    const fullName = `${first} ${last}`;
    return { fullName };
  }
  const { fullName } = combineNames({first: 'John', last: 'Doe' });

geakstr|10 months ago

Some languages allow to define type alias, name of this type can be self-explanatory:

  type FullName = string;
  function combineName(first: string, last: string): FullName;
Also documentation comment for function is what specifically solves this - describes what function does and returns.

avandekleut|10 months ago

Similarly to passing an object argument, you can return an object.

Then pair it with destructuring assignment!

`const { fullName } = getName({ firstName, lastName )}`

wvenable|10 months ago

I fail to see the distinction, for documentation purposes, of this versus just giving it that `getFullName` function name.

A more complex example will probably return a more complex type that is more self-documenting. If the type is a single scalar value then I don't see the value of adding another name here.

mpweiher|10 months ago

Name the function/method as the thing it "returns".

In fact, just forget that it is a function that does something. Treat it as the thing it returns.

string fullName( string firstName, string lastName )

carlos-menezes|10 months ago

Likewise. Even if the input object only has a single property, I'll still use this pattern.

avandekleut|10 months ago

Another common pattern is to put the "primary" argument first, and the rest in an "options" object argument.

disillusionist|10 months ago

because i'm likely going to refactor this function "tomorrow" with additional properties. :)