-Поиск по дневнику

Поиск сообщений в rss_thedaily_wtf

 -Подписка по e-mail

 

 -Постоянные читатели

 -Статистика

Статистика LiveInternet.ru: показано количество хитов и посетителей
Создан: 06.04.2008
Записей:
Комментариев:
Написано: 0


CodeSOD: The Forest of Trees

Четверг, 07 Мая 2015 г. 14:00 + в цитатник

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;
        }
}
[Advertisement] Use NuGet or npm? Check out ProGet, the easy-to-use package repository that lets you host and manage your own personal or enterprise-wide NuGet feeds and npm repositories. It's got an impressively-featured free edition, too!

http://thedailywtf.com/articles/the-forest-of-trees

Метки:  

 

Добавить комментарий:
Текст комментария: смайлики

Проверка орфографии: (найти ошибки)

Прикрепить картинку:

 Переводить URL в ссылку
 Подписаться на комментарии
 Подписать картинку