[TriLUG] c++ proper away do an assignment overload for a linked list.

Kevin Hunter hunteke at earlham.edu
Thu Jan 28 18:38:38 EST 2010


On 01/28/2010 02:30 PM, Ralph Blach wrote:
> To learn C++ an am trying to write a linked list, no hard, in c++,
> 
> However, creating an proper assignment overload, is very difficult.

First some stylistic suggestions:

- Rename empty() to is_empty().  Code is meant to be read by other
people.  Code is meant to be read by *people*.  Code is meant to be read
people.  Did I say that already?  I'm not sure.  Code is meant to be
read by people.  Not computers.  (The fact that computers do something
with code is a nice side effect, but should *not* the intent.)

A simple change like empty to is_empty makes it absolutely clear what
the intent of a statement is.  At first, I thought empty() meant to
erase the list contents.  Or, put differently, it helps make statements
like this read like proper English:

if ( list.is_empty() )    ->   "If list is empty, then ..."

Point: code is meant to convey algorithms to people.  Code is for people.

- Make your comments useful.  Comments like this are not helpful:

ll_node * find_value ( const string & ); // find a value

Your function definition has already said that.  If it's not clear, then
make it so.  But telling us what the code does at the statement level is
not helpful.  The canonical example of what not to do:

x++;  // increment x by one.

Duh.

But is it non-obvious /why/ you're incrementing x?  That's what one
might say there, if anything at all.

- Stylistically, consider vertically lining up functions like this:

  const ll_node * get_first ( ) const { return first; }
  const ll_node * get_last  ( ) const { return last;  }

This makes it visually clear, not just lexicographically clear, that
those functions are similar in nature.  This may seem like a small fry
now, but it removes yet another question mark in someone's else's mind
as they have to debug your code.  As I'm doing now.

- Respect the 80 columns.  'nuff said.

- Consider using the ternary statement to clean up two-possibility
statements:

bool is_empty ( ) const { if (llsize) return false; else return true;  }
bool is_empty ( ) const { return ( llsize > 0 ? false : true ); }

Both are equivalently the same, but at first glance, the first mixes
English-ized tokens where they aren't needed.  In this simple context,
it's hard to make this case, but there are plenty of examples in the
real world.

I'll let you chew on these for a bit before someone answers your actual
question.

Kevin



More information about the TriLUG mailing list