Question

I frequently find myself pulling up helper methods in order to make my code better, but end up with duplicate method names. Is there a standard way to name such methods without getting duplicate names?

Example of code before:

function hello(suffix) {
  if (typeof suffix === 'string') {
    return `Hello ${suffix}`
  } else {
    return 'Invalid entry'
  }
}

Becomes:

function hello(suffix) {
  const isSuffixString = isSuffixString(suffix) // can't do in JavaScript
  if (isSuffixString) {
    return `Hello ${suffix}`
  } else {
    return 'Invalid entry'
  }
}

Of course this is contrived and isn't very useful, but it illustrates the point.

I could call the helper getIsSuffixString, for example, but it feels like too much.

I just find that the helper method name and the ensuing variable often should have the same name.

Était-ce utile?

La solution

First, in the shown case, it makes no sense to introduce an explaining variable since using the function directly is equally readable, so you could write:

function hello(suffix) {
  if (isSuffixString(suffix)) {
    return `Hello ${suffix}`
  } else {
    return 'Invalid entry'
  }
}

However, if you need the result of a function call more than once, it may be useful to store the value of a function call to avoid multiple calls, even if it does not add anything in readability. In a case-sensitive language, one could make use of the convention for beginning method names with an upper case letter, but local variables with a lower case letter:

const isSuffixString = IsSuffixString(suffix)

Unfortunately, there are lots of environments where the usual convention is to use lower case letters for both, functions and local variables. In those languages, I would recommend to use a more descriptive name for what the functions does, and a slightly more abbreviated name for local variables, like:

const isSuffixString = isTypeofSuffixEqualToString(suffix)

And of course, it would also work the other way round, but that's up to your personal taste. Use whatever your peer reviewer tells you he/she understands best.

Autres conseils

This is probably a matter of personal tastes.

I have several verb prefixes that I use for functions. In your case I'd use check. For me, a function like check...() must always return true or false (or raise an exception), and must be idempotent.

So I would write,

const checkedIsSuffixString = checkIsSuffixString(suffix)
if (checkedIsSuffixString) {
    // suffix has been checked and is a string.
    // (This comment is clearly redundant)
    ...
}
Licencié sous: CC-BY-SA avec attribution
scroll top