DEV Community

Cover image for Code Smell 65 - Variables Named After Types
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

Code Smell 65 - Variables Named After Types

Names should always indicate role.

Problems

  • Declarative

  • Design for Change

  • Coupling to accidental implementation

Solutions

  1. Rename your variable according to the role.

Sample Code

Wrong

Right

Detection

This is a semantic rule. We can instruct our linters to warn us from using names related to existing classes, types o reserved words since they are too implementative.

Tags

  • Declarative

Conclusion

The first name we can across is related to an accidental point of view. It takes time to build a theory on the models we are building using our MAPPERS. Once we get there, we must rename our variables-

Relations

More info

XUnitPatterns

Credits

Photo by Sangga Rima Roman Selia on Unsplash

This idea came from this tweet


Types are essentially assertions about a program. And I think it’s valuable to have things be as absolutely simple as possible, including not even saying what the types are.

Dan Ingalls

Top comments (1)

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Well, I mean... regex is the type. I get that this code won't confuse anyone, but it's as type-named as string or bytes or num and as uninformative as data or object.

public bool verifyPasswordFormat(string password) {
  // 2-7 lowercase chars, then 3-4 digits
  return new Regex(@"[a-z]{2,7}[1-9]{3,4}").IsMatch(password);
}
Enter fullscreen mode Exit fullscreen mode

the above is probably ideal in terms of readability, but if you have to for example hoist the Regex in a particular language to avoid recompilation, would this be a close second?

static Regex has3To7LowercaseCharsFollowedBy3or4Numbers = new Regex(@"[a-z]{2,7}[1-9]{3,4}");
public bool verifyPasswordFormat(string password) {
  return has3To7LowercaseCharsFollowedBy3or4Numbers.IsMatch(password);
}
Enter fullscreen mode Exit fullscreen mode

Some will say yes, because "it's good to declare things that do one job, and will be replaced rather than modified".

But personally, I'd end up with

// 2-7 lowercase chars, then 3-4 digits
static Regex passwordRegex = new Regex(@"[a-z]{2,7}[1-9]{3,4}");
public bool verifyPasswordFormat(string password) {
  return passwordRegex.IsMatch(password);
}
Enter fullscreen mode Exit fullscreen mode

Yes, it has a type in its name. But in a wider scope like that it might be a boon and not a sin, as that still reflects its "role" in the code, and is not an implementation detail of how the role is accomplished. You could replace that with "Pattern" but I think that's purely harmful.

And of course I renamed the function.