richelbilderbeek / djog_unos_2018

Project by the Uno's at DJOG 2018-2019: Nature Zen
GNU General Public License v3.0
6 stars 2 forks source link

Simplify to_tile #541

Closed richelbilderbeek closed 5 years ago

richelbilderbeek commented 5 years ago

Is your feature request related to a problem? Please describe.

Currently, to_tile is too complex (OCLint is right):

tile_type to_tile(std::string str) //!OCLINT NPath Complexity Number 256 exceeds limit of 200
{
  if (str == "arctic") return tile_type::arctic;
  if (str == "beach") return tile_type::beach;
  if (str == "desert") return tile_type::desert;
  if (str == "dunes") return tile_type::dunes;
  if (str == "grassland") return tile_type::grassland;
  if (str == "hills") return tile_type::hills;
  if (str == "mangrove") return tile_type::mangrove;
  if (str == "mountains") return tile_type::mountains;
  if (str == "rainforest") return tile_type::rainforest;
  if (str == "savannah") return tile_type::savannah;
  if (str == "swamp") return tile_type::swamp;
  if (str == "tundra") return tile_type::tundra;
  if (str == "water") return tile_type::water;
  assert(str == "woods");
  return tile_type::woods;
}

This can and should be simplified using a lookup table: a std::map.

A std::map is like a BINAS table: you map one piece of data to another, for example, the name of an atomic element (a std::string) and its mass (a double).

Describe the solution you'd like

#include <map>
#include <map>

tile_type to_tile(std::string str)
{
  const std::map<std::string, tile_type> m{
    { "arctic", tile_type::arctic},
    { "zzz", tile_type::zzz} //Other tile types here
  };
  //This assert will fail if the string is not in the map
  assert(m.find(str) != std::end(m));
  return m.find(str)->second;
}

All tests should still pass. This should be an easy Issue!

Describe alternatives you've considered

None.

Additional context

None.

richelbilderbeek commented 5 years ago

Well done! Closing this Issue :+1: