简体   繁体   中英

What really makes this code bad

At my company I came across the following 2 code snippets, which I found thoroughly unpleasant at first sight, but in the spirit of offering constructive feedback to the engineer who wrote that, I'm trying to come up with technical arguments why this code is bad:

FileTableEntry * FilerManager::GetFileTableEntry(uint32_t i) const {
  return &(GetFileTable()[i]);
}

…
for (uint32_t i = 0; i < container_.size(); ++i) {
   *GetFileTableEntry(i) = FileTableEntry();
   // GetFileTableEntry ultimately accesses a std::vector in FileManager
}

My main arguments are :

  1. This code is very indirect and misleading, it should not use a getter to initiliaze (part of the FileManager), but at least a setter: being more direct makes the code easier to understand.
  2. The getter completely leaks the internal state of the FileManager, so encapsulation for FileManager means nothing at this point. Even worse, the getter promises to be applicable to const objects, but is merrily used to mutate the internal state of FileManager. Breaking encapsultion is a sure path to making refactorings harder.

Are there other arguments for not writing code like this that I would be missing??

Another argument against this code is that the signature of GetFileTableEntry returns a pointer in situations when the object is always present. This calls for a reference, not a pointer:

FileTableEntry& FilerManager::GetFileTableEntry(uint32_t i) const {
    return GetFileTable()[i];
}

This should address your first point. Your second point can be addressed by making the reference const :

const FileTableEntry& FilerManager::GetFileTableEntry(uint32_t i) const {
    return GetFileTable()[i];
}

This prohibits the callers from modifying the internal state returned by GetFileTableEntry .

Note: To make the GetFileTableEntry function useful, one should add a bounds check of the index passed in to catch errors early.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM