Homework 3 Notes
1. Instructions
This assignment is about code modernization. We are tasked with refactoring the codebase to use modern C++ features, then writing unit tests to ensure that the code still works as expected.
2. Examples of Code Modernization
2.1 Almost always auto
for variable declarations:
// Before
int caveId = pCave->GetCaveId();
// After
auto caveId = pCave->GetCaveId();
2.2 Use range-based for loops:
// Before
for (auto it = m_denizens.begin(); it != m_denizens.end(); ++it)
{
if ((*it)->ObserveCaveEntrance(newDenizen))
{
// Stop if that denizen affected things.
break;
}
}
// After
for (auto&& denizen : m_denizens)
{
if (denizen->ObserveCaveEntrance(newDenizen))
{
// Stop if that denizen affected things.
break;
}
}
2.3 Use STL algorithms:
// Before
void Cave::RemoveDenizen(const DenizenIdentifier& identifier)
{
std::set<std::shared_ptr<Denizen>>::const_iterator itr;
for (itr = m_denizens.begin(); itr != m_denizens.end(); ++itr)
{
std::shared_ptr<Denizen> denizen = *itr;
const DenizenIdentifier& id = denizen->GetIdentifier();
if (id.m_category == identifier.m_category &&
id.m_instance == identifier.m_instance)
{
break;
}
}
if (itr != m_denizens.end())
{
m_denizens.erase(itr);
}
}
// After
void Cave::RemoveDenizen(const DenizenIdentifier& identifier)
{
m_denizens.erase(std::ranges::find_if(m_denizens,
[&](const auto& thing)
{
return thing->GetIdentifier() <=> identifier == std::strong_ordering::equal;
}));
}
// Before
bool Cave::HasDenizen(const DenizenIdentifier& identifier) const
{
std::set<std::shared_ptr<Denizen>>::const_iterator itr;
for(itr = m_denizens.begin(); itr != m_denizens.end(); ++itr)
{
std::shared_ptr<Denizen> denizen = *itr;
const DenizenIdentifier &id = denizen->GetIdentifier();
if(id.m_category == identifier.m_category)
{
break;
}
}
return itr != m_denizens.end();
}
// After
bool Cave::HasDenizen(const DenizenIdentifier& identifier) const
{
return std::ranges::find_if(m_denizens, [&](const auto& denizen)
{
return denizen->GetIdentifier().m_category == identifier.m_category;
}) != m_denizens.end();
}