Search code examples
c++readability

How do I name members of a parent class (library) for readability in both parent and child classes?


I created a custom library that is usually used as a parent class.
After I used it for 1 month, I begin to face difficulty about its readability.

It is better described by a simplified real example.

Library Level

There is my c++ library to manage Object in 2D space.

It has 2 classes : Grid (the space) and GridMember (object in space).

Game-logic Level

I create a Table derived from Grid, and Ball derived from GridMember.

Problem

When I want to call function of Grid from Table like this:-

Table* table=new Table();
table-> .... some Grid's function .... (ctrl-space)

If ALL Grid's function name have some unique signatures e.g. all of them has prefix grid_,
... the code will gain higher readability.

As you can see, it is captivating:-

table->grid_add(new Ball());               //Grid's function member
table->grid_moveTo(ball1,VecInteger(3,4)); //Grid's function member
table->flip();                             //not Grid's function member

However, when look inside Grid.h, now it is very dirty.
Every variable/function of Grid now contains that grid_.

This is one of the worst symptom :-

class Grid{
    //--------- old version -------
    void move_grid_to_offset(){...} //move the world
    //^ I prefer this name to moveGridToOffset, because it is easier to read

    //--------- new version ---------
    void grid_move_grid_to_offset(){...} 
    //^ After a long day, I read it as  grid......grid(again)..  
    //         not sure what it is doing
}

Therefore readability is reduced.

Question

How to achieve high readability in both places?

Similar question : Why use prefixes on member variables in C++ classes but it is not related to this problem.


Solution

  • In general, any member of a subclass should actually be a member of any superclass, conceptually as well as programatically. Thus, in this case, any Table actually is a Grid, and any Ball actually is a GridMember. Since a Table is a Grid, Table->add() should be perfectly clear, without worrying about whether it's a Grid function or a Table function.

    In the case of move_grid_to_offset, the issue is not that there's too little information in the name, but that there's already too much: a better name would be move_to_offset or offset_by. Since you already know that it's a grid whose member function is being invoked, it's unnecessary to repeat in the name of the member function that it applies to the grid: grid.offset_by() is perfectly clear. And table.offset_by() is also perfectly clear, even if we don't know about the Grid class at all.