Naming is Too Hard : Finding the Right Level of Abstraction

How we can make our code more readable !! The answer of this question is “With The Help Of Good and appropriate naming”. In programming Experience has confirmed Naming things is too hard.So hard in fact that it’s common for programmers with years and years of experience to regularly name things poorly.

There is a number of nuances to giving something a right and appropriate name, but the one I am going to talk about here is finding the right level of abstraction. Here is some simple instances:

val employeeList = new List[Employee]();

val sqlServerConnection = getDatabaseConnection();

In these Two examples the variable name contains information about its type Now, in a real program the lines of code following these declarations will use the variables in one way or another – employeeList will have Employees added to it and the next sqlServerConnection will be used to execute SQL queries, etc. In this way we can think of each of these variables as providing a service to the code which uses them – that code will have a certain set of interactions with them and require a certain interface to do so; it’s in that interface – in the service provided by each variable to the code that consumes it – that the appropriate level of abstraction is found.

To be more specific: the code that uses employeeList probably just needs to be able to put a bunch of Employee objects in a group – odds are the fact that the object fulfilling that need of List is irrelevant, therefore ‘List’ doesn’t need to be in the name. Further, if we change employeeList to be acollection, the variable name is now not only exposing details about the underlying implementation – it’s lying about them. We could change it to employeeCollection as part of the same refactoring, or… we could just name the variable employees.

sqlServerConnection is similarly specific about the implementation the variable represents. Does it matter to the code which consumes sqlServerConnection that it’s using an SQL Server database as opposed to a (e.g.) MySQL database? The method which creates the database connection is the provider-agnostic getDatabaseConnection, so probably not. If not and we’ve established in my made-up scenario that it isn’t – we can just name the variable connection.

To try and summarize this in a single, pithy statement: a name with the right level of abstraction describes the role played in the code without any unnecessary details.

Like this:

Kunal Sethi is a Software Consultant with experience of more than 1.5 years. He is a Java enthusiast and has the knowledge of various programming languages such as Scala, C++. He is familiar with Object Oriented Programming Paradigms, love to code applications in J2EE. He developed his own stand alone application in Java based on intranet chating System and email system during his Master's Degree.