I’m working on implementing come business logic in my C# application.
I’m having trouble fitting the logic into a sane piece of code.
The logic to implement goes like this:
There is a tree of elements, let’s say: Project, Country, Region, City. A single Project contains Countries. Countries contains Regions, Region contains Cities and Cities contain data entries. We’ll be populating the elements with data entries based on what information is available.
- if Country, Region, and City information is available, push the data to the project and use the info to know where to insert the data entries.
- if Country info is not available, create a new Country and use Region and City info to insert the data entries.
- if only city info is available, create a new Region inside a new Country and use City info to put data there.
- if no info is available, create a new City inside a new Region inside a new Country and put the data there.
- if any info is not available out of order (for example Country and Region are available but not City) we have to fall back to the more general case (creating new Country, Region and City in this case).
Additionally:
- when you create a leaf class, you have to provide the parent in the constructor.
- querying about what info is available is expensive.
- I would like to avoid repeating the code that creates new classes.
- I cannot change the implementation of classes
Country,Region,City.
My solution below works, but it’s ugly and using an integer to control app flow gives me shivers.
How can I improve the code snippet below?
Country country = null;
Region region = null;
City city = null;
int level;
if (!IsCityInfoAvailable())
{
// we have to make a new country, region and city
level = 3;
}
else if (!IsRegionInfoAvailable())
{
// we have to make a new country and region
level = 2;
}
else if (!IsCountryRegionAvailable())
{
// we have to make a new country
level = 1;
}
else
{
// we have all the info we need
level = 0;
}
IDataEntryTarget target;
if (level > 0)
{
country = new Country(Project, "Unnamed Country");
target = country;
}
if (level > 1)
{
region = new Region(country, "Unnamed Region", Region.DefaultRegionSettings);
target = region;
}
if (level > 2)
{
city = new City(region, "Unnamed City", 0);
target = city;
}
// ... proceed with data entry code using `target`...
Edited: try it like this: The only question I have is where are city, region & country initialized? In the Is() methods?