Tips on naming your variables

Tips on naming your variables

Jul 27, 2020Β·

2 min read

Hello everyone, my name is Davies Esiro. This is my first time ever writing about programming (or anything at allπŸ˜ͺπŸ˜ͺ) so I hope this is helpful and you also enjoy it.

One of the things that gives me little-ish issues when working on a project is naming variables. Yeah, it is pretty normal (for me anyways) to get confused about the name you want to assign to a variable

So with knowing that, here is a tip on naming your variables

For instance you want to store details about a student such as name, state of origin, Matric number, level and department

  • Avoid using anonymous variable names You might be tempted to give variables names like
    String n 
    String soo 
    String Mt
    int l
    String dp

As the author you might understand what you're trying to do but for someone else working with you on the same project, well, lets say it wouldn't be easy for the person to understand.

You know why? There aren't explicit. You might be also tempted to add comments too

String n //  student's name
String soo // student's state of origin
Student Mt // student's matric no
int l // student's level
String dp // student's department

Congrats someone looking at your code will know the use of each variable at the first declaration. There is still a problem though.

In a situation where you want to make use of those variables, you will may have to scroll up or navigate to the declaration of those variables just to remember them. Hope you know that will slow down your development and when done continuously it will end up being annoying.

Having too many comments can also end up being bad. Try not to be verbose

So what do you do? πŸ˜‡ Opt for giving self explanatory names

  • You can use camel casing

    String studentName
    String studentStateOfOrgin
    int studentLevel
    String studentDepartment
    String studentMatricNumber
  • Or snake case

    String student_name
    int student_level
    String student_matric_no
    String student_department
    String student_state_of_origin

Now those variables don't necessarily need comments because they say what they do and they're also easy to remember 😁

PS Try not to allow your variables to be too long, I advice not more that 25 characters