loading...
markdown guide
 

Explicit? No. But here are my rules of thumb.

1. Don't try and name things too eagerly. Naming is, if anything, the beginning of abstraction. As soon as something gets a name, it brings in mental baggage from everyone that reads it. Bad names lead to bad abstractions everywhere else.

1.1. When you're writing software, you probably have no idea what you're doing. You don't understand what you're trying to build, what the right shape, organization, style of code is for the domain you're trying to work with. Bad names are usually evidence of someone misunderstanding what they were building at an earlier time in the development process. But then the name stuck because everyone was using it... so the bad names proliferate.
1.2. So if anything, prefer a screamingly awful name that completely misses the mark than one that is full of baggage and opinion. Thingy is just fine by me.

2. If you put I in front of your interface names I will shout at you in an unkind way. This is 2019 - you don't need to use Hungarian Notation to express the type of a variable. If anything, the interface should name the general case and the implementation should name the concrete. Database could be the interface, PostgreDatabase could be the concrete type.

2.1. If your interfaces are describing behaviour (á la Go), use an agent noun based on the verb that captures the behaviour: Fetcher, JSONParser, etc.

4. Name length should be proportional to how long the variable will live, and how it's scoped. If it's just the iteration counter, i is fine. But if it is exported then I want to see a bit of verbosity.

4.1. This matters less with typed languages; I'm pretty confident I know what db is if it's declared as Database db = ...

5. Functions and method are actions - name them appropriately: fetch, read, get etc.

5.1. Name methods (and namespaced functions) fluently, taking into account the (likely) receiver name; file.write() not file.writeFile().

6. Stop trying so damn hard - you're probably giving it the wrong name anyway so come back to it tomorrow when you've had some time to think.


Edit: removed point 3 about screaming snake case for constants as I've been convinced it's just pointless

Edit: just want to point out that I pulled these out of the top of my head so I'd hate it if anyone quoted them back to me in a code review in six month's time

 

I've never understood why constants should be uppercase? I see no valuable semantic difference between these two forms of code:

  • create_deck( num_cards )
  • create_deck( NUM_CARDS )

The second form adds a visual clutter which provides no useful information to the reader.

 

Top-level constants (in a library or call function) would be uppercase as they are there to ensure capacity of use for the space they live in, and that . For instance, your create_deck( num_cards ) one would be better as a variable or simply a literal numeric value such as 52, 54, 128 or so on. Or it would be function called as a higher order function, eg

create_deck(Options { type: Cards::Playing, with_jokers: false, })

A better example would be

#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ErrorCode {
  Other = 0,
  ServerDown = 1,
  BadRequest = 2,
  NotFound = 3,
  Gone = 4,
  EnhanceYourCalm = 5,
  DDoS = 6,

}

const ENUM_NAMES_ERROR_CODE: [&'static str; 7] = [
    "Other",
    "ServerDown",
    "BadRequest",
    "NotFound",
    "Gone",
    "EnhanceYourCalm",
    "DDoS"
];

pub fn enum_name_error_code(e: ErrorCode) -> &'static str {
  let index: usize = e as usize;
  ENUM_NAMES_ERROR_CODE[index]
}

where it's a constant; but it really is only used for one task and could be replaced with a match statement. This just avoids allocations in inlined code.

 

I'd agree - but I think the convention is so widespread that I'd be surprised if it wasn't followed. Principal of least astonishment and all that.

I've seen normal casing on constants used on many projects.

It's something that nobody would notice about, nor complain about. Nobody would miss the uppercase constants.

OK, you've convinced me! I'm removing it now as it's really not that important.

 

This is so thorough and great advice! Thank you for this response.

 
  1. Stop trying so damn hard - you're probably giving it the wrong name anyway so come back to it tomorrow when you've had some time to think.

Yep. A lot of my refactoring is "why the hell did I name it that?"

It's not difficult since most IDE's and even VS Code implement a "Rename symbol" functionality that makes refactoring a snap.

 

I didn't put it in the original, but I think a lot of the problem is that we give things names before we go as far as working out what they do. It's usually days or even weeks after I've written something that the right name becomes apparent - usually when I'm trying to talk about the code with someone else.

Yes - refactoring tools are your friend in this! 💯

I have a good example for this. I wrote a minesweeper game. I wrote a function called clearBlanks that does what it says, it clears blank squares in a contiguous region when you click on a blank. There's a function defined inside clearBlanks that I had named clear that was recursive. What it does is create an array of the squares adjacent to the ones passed in that need to be cleared.

It does not actually clear them. They get cleared after the recursion is complete and the array is returned back to the clearBlanks function that actually does clear them. So clear was the wrong name for it.

I renamed the recursive function getAdjacentSquares because that's what it actually does, it gets the squares adjacent to the ones passed in. It should probably be further renamed getAdjacentBlankSquares or getSquaresToBeCleared But then we start going down a rabbit hole of finding the perfect name.

The problem in naming is that often as we develop, what our functions do changes from what we initially intended. In this particular example, I rewrote this function (and crashed Chrome with stack overflow errors) several dozen times getting it to work and by the time it did work, getAdjacentSquares had nothing to do with actually clearing the squares.

 
  1. Don't try and name things too eagerly. Naming is, if anything, the beginning of abstraction. As soon as something gets a name, it brings in mental baggage from everyone that reads it. Bad names lead to bad abstractions everywhere else.

1.1. When you're writing software, you probably have no idea what you're doing. You don't understand what you're trying to build, what the right shape, organization, style of code is for the domain you're trying to work with. Bad names are usually evidence of someone misunderstanding what they were building at an earlier time in the development process. But then the name stuck because everyone was using it... so the bad names proliferate.

1.2. So if anything, prefer a screamingly awful name that completely misses the mark than one that is full of baggage and opinion. Thingy is just fine by me.

For these three, I agree that a developer should hold off on naming if they do not understand what they are trying to build. But I feel that developers should do some planning to know what they are building (assuming it is not a side project without any real goal). They should plan out the steps they need to achieve a particular end goal, then refine that into a more detailed technical to-do list for each step. I will often write the skeleton of the code with comments and function definitions before writing any code that actually does anything. It helps me to break down the problem into the smaller pieces to make it more manageable. After doing that, naming the variables is easy.

I agree with all of the other points. 😄

 

First I start with something like this:

const aaaaaaaaa = () => /* my code here */

Then after figure out what the thing does, I change the name to match.

Then after I check the code into source control and push it up to the repo, I change the name one last time.

It's also possible that later, I will change the name once more when a co-worker complains that my naming isn't correct for the thing.

Naming things is hard.

 

1- Be consistent within your team or project
2- Names should describe why a programming element exists
3- Names should be pronounable, searchable, and without encoded info
4- Avoid numbers in names
5- Not too abstract, not too detailed

 

I feel like consistency is the most important thing. When you are done you can go about making things more readable / use better naming.

 

The chapter in Clean Code on naming conventions usually resolves a lot of naming-esque questions on PRs (the lazy answer)!

Something I've seen come up a lot is naming projects after abstract concepts. Something like Kubernetes isn't super obvious at first, but when explained you think "huh that's clever". However for repositories at work it can get really annoying when everything is named after a Greek god or plants or something.

 

I had to go look it up... it's a Greek word, κυβερνήτης, meaning “helmsman” or “pilot.

The More You Know.

 

As a Greek I can explain better. The word can mean a helmsman when used on a ship captain. The basic meaning of the word is governor though(or commander). It's derived from the verb κυβερνώ which means govern

 

Oh that's complex.

I have some loose rules:

Make sure everything that is global is properly prefixed

  • APIOrder
  • APIOrderBag
  • APIOrderProduct
  • APIOrderProductIngredient

Exceptions are suffixed with WithSomething, FromSomewhere, etc

  • Menu
  • MenuFromGlobal
  • MenuFromStore

Build a glossary for your project

Basically indicates that Account, User, Person, Individual are all treated as User.


Maybe more, I don't remember.

 
 

I was working on a project.

Our ex-developers created a stored procedure called "getAllUsersByInvoiceAndNonZeroInvoicesWithNonNullCustomerNamesAndBalanceBiggerThanZero".

It was in the Turkish language. I only translated into English.

Is this kind of naming good? Because there was also a method with this name in the backend project.

 

This reminded me of a talk I saw recently where the presenter suggested that if a method name has words like "And" or "Or" in it, that tells you that the method has too many responsibilities.

I think in this case the long name tells me that the procedure is not working as an abstraction. The implementation is leaking into the name, so you may as well inline the implementation into the calling code.

To put it another way, the name tells me how the procedure does what it does, but not what the result represents or why I should call it.

It's also quite inflexible because if I added another condition I would have to change the name as well, even if the overall purpose of retrieving this data hasn't changed. The change would impact all of the code that calls the procedure.

If these users actually represent something meaningful to the domain you're working in (maybe something like "customersWithOutstandingInvoices") then renaming it would make the procedure more useful, because the calling code can describe a business process at a high level and the stored procedure has the responsibility of ensuring the correct set is returned.

 

And the award for the longest most descriptive name goes too... Seriously though, there are situations where names like this cannot be reduced, perhaps at that point get another opinion. Perhaps a set of more generic things composed to do whatever that did would have worked better, but who knows.

 

My general rule is to "call it what it is." What I mean by that is to pretend another developer came to you to ask about a variable, function, or class that you have knowledge about. I think that most people would provide a good explanation. That explanation should be fairly close to the name. Other developers should not have to do detective work or ask what something means, make it apparent.

Some examples:
"It gets the user." - getUser()
"It stores the number of milliseconds that have passed." - elapsedTimeInMilliseconds
"It compares data from flights." - compareFlights()
"It calculates the amount of fuel used in a flight." - calculateFlightFuelUsage()
"It stores the size of the fuel tank in liters" - sizeOfFuelTankInLiters

I think that is usually enough to have a good name. In development, there seems to be this compulsive need to have short "concise" variable names. I think the word "concise" is misused to mean "short and obvious to me, writing the code at this moment." But it really should mean "short, accurate, and complete." In an example of var d; vs. var elapsedTimeInDays;, I think defenders of d would say that you can use the context of how it is used and deduce that it means "days". The problem is that I have to look further and see what is actually being stored when I shouldn't have to. Another issue is when that code is updated in the future. If the next developer has to add another "days" variable in that scope, guess what it will be named? d2. It is wishful thinking to assume that it will be refactored and named properly when the time comes. Finding a good middle ground and being concise (for real) is important. Use enough words to accurately and completely describe something. If it happens to be a little longer, no big deal, we have auto-complete.

Beyond that, I have some "do not" rules and general guidelines that I try to follow.

  • No prefixes (also known as Hungarian notation). Name it so that a prefix is not needed and it is more human-readable. Example: isActive instead of bActive. Using it is easier to read, in my opinion. if (isActive) translates easily to "if it is active."
  • Limit abbreviations and acronyms. Commonly used ones in the field are okay (like "URL" or "API") but do not create new ones. Learning a codebase is difficult enough for newcomers, introducing specific acronyms that developers have to ask about and remember makes it that much more difficult for everyone on the team. There are acronyms I use at work on a weekly basis, but I have no idea what they mean or their origin.
  • Variables are usually nouns, classes are usually singular nouns, and functions are usually verbs.

These types of discussions can seem nitpicky and spark negative emotions if brought up in a code review, but it is important to look at any suggestions holistically. One var d; in the code is not the end of the world, it will not ruin code quality. But multiple developers across multiple years consistently using not so great names becomes a problem. Will it be understood by you a few years later? Will it be understood by a developer that starts this job tomorrow?

 
 

Functions:

  • How succinctly can I describe what the function does? Can I make this succinct function its name? Here's a function that fetches football scores off ESPN:
async function fetchScores() {
    const scores = await fetch(urlToEspn);
    return scores;
}

See? Does what the name says.

Variables:

  • What does this variable hold? const person = new Person() Gee, i wonder what person is.

Objects

  • What it is, and first letter of the type is capitalized, always.

Methods of objects:

  • avoid naming the object in the function, example filereader.readfile(). I know that it comes off the file reader object, so naming the method readfile is redundant. read() is fine. filereader.read()
 

Well, give a name and check the following things while keeping the context in mind:

  1. Is it unambiguous?
  2. Does it reflect the intent and not the implementation?
  3. Is every word necessary?
  4. Is it correctly spelled?
  5. Is it likely to be unique within its scope? (Python module, CSS, etc)
 

Yeah, I follow certain guidelines that I outlined in my post. Things such as prefixing booleans with is, ensuring array names are plural, etc.

 

On a huge automotive project I used to work we used the Hungarian notation. IDEs are cool and stuff, but when there are millions of lines of C code you'll be glad to see ProjName_ModName_nenLightColor

 

My gold and confusing rule:

Be explicit according the context, but not too much

Ex.

activeOnlineUsers
activitiesMarkedAsComplete

They are "Ok", but i prefer take them into an object (JS example)

onlineUsers.active
activities.markedAsComplete

Anothers simple examples might be:

user.getName()

  • this is wrong if the user has first and last name

db.getUser(id)

  • this is wrong because you might seek the user with another param

util.map()

  • this is wrong if the util object can handle others type, not just arrays

i prefer named them like:

user.getFullName()

db.getUserById()

util.arrayMap()

Is better a long names, than a generic and inexpressive ones. But if the name is too long, is because there's something wrong in my code design.

 
  • variable names in camel case, uppercase combos gets camel cased too:
const filePath = "";
const displayAsap = true;
  • Boolean variables always positive :
const fileExists = true;
// not "fileEmpty" or "fileNotExist" 
const reportErrors = false;
// not "ignoreErrors" 

plural for arrays:

const routes = [];

for (const route of routes) {} 
  • length of arrays/list gets "count" appended, the target is in plural:
const routes = [];
const routesCount = routes.length;
  • Boolean properties gets "enabled" appended to their names:
class Request {
  static debugEnabled = false;
  static cacheEnabled = true;
} 
  • Get, get...s, delete, delete...s, enable, disable, enabled, add, add...s, set, set...s, has, store, read, display, for method names :
class Request {
  static _debugEnabled = false;
  static _routes = [];

  enableDebug() {} 
  disableDebug() {} 
  debugEnabled() {} 
  addRoute() {} 
  addRoutes() {} 
  setRoute() {} 
  setRoutes() {} 
  hasRoute() {} 
  hasRoutes() {} 
  deleteRoute() {} 
  deleteRoutes() {} 
  getRoute() {} 
  getRoutes() {} 
  storeResponse() {} // only for writing in file
  readResponse() {} // only for files
  displayResponse() {} 
  displayErrors() {} 
} 
  • Am not a code nazi so methods that do not display or CRUD can be named normally:
class Router {
  get() {} 
  post() {} 
  listen() {} // this one 
} 

For Vue component gets "item" if sub components:

component/
  Breadcrumb.vue
  Breadcrumb/
    Item.vue
  Menu.vue
  Menu/
    Item.vue

I try to stick with this as best as I can to keep consistancy 😅

(really need to write those somewhere...)

 

I'll leave this here:

[feature/action-grandma e1488c2] add action Grandma 
 10 files changed, 157 insertions(+), 200 deletions(-)
 create mode 100755 src/action/actionGrandma.ts
 delete mode 100644 src/action/builder.test.ts
 delete mode 100644 src/action/builder.ts
 rewrite src/bot/index.ts (64%)
 rewrite src/index.ts (99%)

Actual branch used for a bot we're working on 😂

 

I tried that naming standard that's out there (I forget what it's called) for a while but I had to bookmark it for later. And then I lost the bookmark.

Now I just do my very best to not use variants of the letter x. Other than that I generally err on the side of verbose names if I'm really struggling. I figure that if I don't get around to changing the name later I'll at least know what the thing I named means-ish.

 

I'm the one on my office that gets asked for naming help. Most of my co-workers are not native English speakers, and my mom is a school teacher, so it's in my blood.

I usually start by ask questions:

What's the business case (or who are the users)

What is the data?

What transformations are you doing?

Who are the consumers?

Then I throw out the most specific name I can muster, and usually at that point someone thinks if a new answer to the above questions that we have thought of yet. Rinse and repeat until everyone is, if not satisfied, then willing to compromise.

 
  • Follow existing convention where reasonable, otherwise pick something sane (IDE default, defacto standard for the language/framework, etc.)
  • Most obvious/expected, not too generic or clever or obscenelylongeither
  • Consideration proportional to visibility (public API is important, locals/privates less so)
  • Should be enforced by IDE/tooling, not long list of arcane rules nobody remembers
  • Avoid duplicating language features: namespaces, variable types, etc.
  • Remain open to renaming/refactoring
 

I generally make APIs, usually in a MVC set up, so it is relatively easy to name things. There are the entity classes and you name them under what they represent: Client, Order, Company, etc. Then, each one of them will have a service to implement the business logic for each one, so: ClientService, OrderService, etc. Then we have a controller for basically each one, then: ClientController, OrderController, etc. Methods are named under what they do, variables under they what store. Global things are generally things like authorization, database connection, configuration, etc. and they name themselves.
I don't have problems to name things and create a pattern for the names, generally it is very straightforward.

 

In OO: Imagine that your methods tell your objects something. Do you want to tell a User to getAllRelatedPosts, or do you want to tell a user to getOwnedPosts?

Similarly, when you know what message you want to send, you can understand a bit more who should receive that message. Telling a file to uploadFile is like telling a human to eatHumanFood. It’s likely that you have objects that can take less specific messages - a Dog can Eat, and a Human can Eat. Maybe both can consume({sustenance: [food, drink]}).

It sounds simple, but name things what they are.

For example, don’t name a file model “Download.” A Download would be an instance of the action of downloading. (This happens to be a bit of a smell - naming objects by an intended action, like UserSignup).

 

I work in Oracle, so I'll explain my variable types:

Varchar2: v_thisIsVarchar2
Number: n_thisIsNumber
Clob: c_imAClob
Blob: b_imABlob
Date: d_imADate
Raw: r_imRaw

These are the ones I used most. But if I have attributes in a specific procedure, (i.e. let's say I'm calling an LDAP procedure) for those variables I'll append l_ to it, just to separate them.

 

It really depends on what you're doing.

Consistency, establish conventions with your team, and following mantra's of the specific language can be really helpful guidelines.

Really though... not everyone is going to like your naming and way too much time is wasted arguing if it's the "right" name. I'm in the "close enough" club because I just want to get things done. I do appreciate some sanity to it though, so set some rules with your team and document what you're doing and build away.

 

Not necessarily for classes, but for all functions / actions or properties.
First I'll go for the description. Usually a name will pop out of it. If not, probably I'm doing too much with it and I'll try to break into smaller actions.

 

Variable names don't matter much to me. Variables are ephemeral (unless they're global variables, which make me sad), so the names don't go very far in the codebase.

I find consistency in naming to be rather important. Things that follow a consistent naming convention make it easier to understand disparate parts of the codebase because there are similar patterns in names.

As @gypsydave5 notes, once a name is in place it tends to stick, but bad naming only gets worse if you try to fix bad names half-way through the codebase. A bad naming convention that is followed throughout the codebase still gives valuable information, because it relates other parts of the code. A good name that doesn't follow the convention makes everything harder to understand, which actually makes it a really bad name.

 
  1. Name classes for what it is, not for what they do
  2. Name method for what they do
  3. Use Google to find synonyms if needed
 

I give them names that come to mind. When I find a better name, I rename it.

 
 
 

I start with a1, then increment the next variable to a2, then a3 etc.

I'm the devil devil

 

I start by karate chopping my keyboard, and then I prefix whatever that makes with ‘str_’ no matter what type it is.

 
Classic DEV Post from May 13 '19

What cool ideas have you seen for integrating new team members?

I came across this tweet from a couple days ago and it really struck a chord with...

Ben Halpern profile image
A Canadian software developer who thinks he’s funny. He/Him.

Hey there reader...

Do you prefer sans serif over serif?

You can change your font preferences in the "misc" section of your settings. ❤️