CodeSOD: The Forest of Trees |
Sallys co-worker wanted to turn some data into HTML. It would flow from his application into client-side JavaScript which would build the DOM. He decided that it made sense to use a tree to represent the data as its translated.
The C# declaration of his tree looked something like this:
Dictionary>> treeOBJMODEL;
Isnt it fantastic how Generics can make your code more readable and type-safe? I mean, thats not whats happening in this example, but…
To traverse the tree, he used a terse, readable block like this :
Dictionary>> treeOBJMODEL = (Dictionary>>)Application["ProductTypesTree"];
foreach (int level in treeOBJMODEL.Keys)
{
Dictionary> levelNodes = treeOBJMODEL[level];
if (level == 1)
{
foreach (List rootNodeL in levelNodes.Values)
{
foreach (CatalogLoader_Helper.CatalogNode rootNode in rootNodeL)
{
if(this.IsLeaf(rootNode, level))
{
// ...
}
// ...
}
}
}
else
{
foreach (CatalogLoader_Helper.CatalogNode parentNode in levelNodes.Keys)
{
List childSiblingNodesOf1AndTheSameParent = levelNodes[parentNode];
foreach (CatalogLoader_Helper.CatalogNode leafNodeToAdd in childSiblingNodesOf1AndTheSameParent)
{
if(this.IsLeaf(leafNodeToAdd, level))
{
// ...
}
// ...
}
}
}
}
Thanks to the super-powerful (ab)use of Generics, Sallys co-worker was able to write even more streamlined code for normally challenging functions, like IsLeaf
:
private bool IsLeaf(CatalogLoader_Helper.CatalogNode node, int nodeLevel)
{
//It enters the collection and checks:
//If the nodeLevel is the highest (we are on the last level)
//then it immediately returns true: it is definitely a leaf;
//Otherwise:
//It procures itself the level mapping for the next level
//and checks if it finds itself in its keys
//if yes, then it immediately returns false and exits;
//otherwise it returns true.
int nextLevel = nodeLevel + 1;
if (!treeOBJMODEL.ContainsKey(nextLevel))
{
return true;
}
else
{
string thisNodeNumRef = node.numRef;
Dictionary> levelMapping = treeOBJMODEL[nextLevel];
foreach (CatalogLoader_Helper.CatalogNode parentsForNextLevel in levelMapping.Keys)
{
if (parentsForNextLevel.numRef.Equals(thisNodeNumRef)) return false;
}
return true;
}
}
Комментировать | « Пред. запись — К дневнику — След. запись » | Страницы: [1] [Новые] |