This discussion is archived
1 2 Previous Next 19 Replies Latest reply: Dec 13, 2012 1:18 AM by TPD-Opitz-Consulting-com RSS

how to optimize this code + is design proper

814889 Newbie
Currently Being Moderated
Well I have to implement tree programming here , what i mean by tree
programming is i have data stored in tree format i,e I have parent
object which will have child objects of same type the level of depth can
go any long:

I am able to store objects in tree format and also able to display properly Here
is code but I am facing problems when i have to filter some child nodes based on some conditions:

I have two question is this code fine is there anything wrong with desin Plus how to handle removing child node in tree scenation where child can be in any place.Below is code
 

package menu;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.chartis.gp.support.util.BrokerSupportUtil;
import com.chartis.gp.support.vo.Links;
import com.chartis.kernel.user.UserVO;
import com.chartis.kernel.utils.Utils;

public class Utility{
     
     /* IN this class NavModel,CModel,CNode are some dummy classes
      * which help us read contents form some resources which are stored in dummy format
      * as Example of tree format stored data below is the example 
      *    tree
      *       child1
      *       child2
      *       child3 
      *              child3-1
      *                       child:q
      *                       child:r
      *                               child:a
      *              child3-2
      *              
      *       child4 
     */
     
     
     private static void populateChildLinks(NavModel navModel, Object objectNode, Links parent ){
          try{
               List<Links> childLinks = new ArrayList<Links>();
               Iterator it = navModel.getChildren( objectNode );
               while( it.hasNext() ){
                    NavNode node = (NavNode) it.next();
                    CNode contentNode = node.getContentNode();

                    Links links = new Links();

                    links.setNodeName( contentNode.getNodeName() );

                    childLinks.add( links );

                    if( navModel.hasChildren( node ) ){
                         populateChildLinks( node, links );
                    }
               }
               parent.setChildren( childLinks );

          }
          catch( Exception e ){

          }

     }

     private static Links createCategoryLinks(String categoryLinkName){
          Links categoryLinks = new Links();
          categoryLinks.setNodeName( categoryLinkName );
          return categoryLinks;
     }

     public static Links setupLinks(String categoryLinkName,String name) {
          Links categoryLinks=null;
          CModel contentModel = new CModel();
          NavModel navModel = new NavModel();
          categoryLinks = Utility.createCategoryLinks( categoryLinkName);
          Object objectNode = contentModel.getLocator().findByUniqueName(name);
          if( objectNode != null ){
               if( navModel.hasChildren( objectNode ) ){
                    populateChildLinks( navModel,objectNode, categoryLinks );
               }
          }
     }
     
              // This is where i am facing issue once i get list of links of childs 
          // i have to delete how can i find that particular child in the list
          // do i have to iterate through all the links and delete or  which 
          // way is better
     private static void filterLinks( Links parentNode,
               List<Links> childNodeList ){
          List<Links> filteredResourceList = new ArrayList<Links>();
          if(  childNodeList!=null ){
               Iterator<Links> childNodeIt = childNodeList.iterator();
               while( childNodeIt.hasNext() ){
                    Links childNode = (Links) childNodeIt.next();
                    if(childNode.getChildren().size() >0 ){
                       filterLinks( childNode, childNode.getChildren() );
                    }
                    
                    boolean removeNode = filterContents( childNode);
                    if(! removeNode ){
                         filteredResourceList.add( childNode );
                    }
                    
               }
          }
          Iterator<Links> filteredResourceIt = filteredResourceList.iterator();
          while( filteredResourceIt.hasNext() ){
               Links childNode = (Links) filteredResourceIt.next();
               parentNode.getChildren().remove( childNode );
          }
     }

     // Let us consider this as some dummy method which returns true or false based on some conditions
     private static boolean filterContents( menu.Links childNode ){

          return false;
     }
}


  package menu;

import java.util.List;

public class Links{
      private String nodeName;
     private List<Links> children;

     public List<Links> getChildren(){
          return children;
     }

     public void setChildren( List<Links> children ){
          this.children = children;
     }

     public String getNodeName(){
          return nodeName;
     }

     public void setNodeName( String nodeName ){
          this.nodeName = nodeName;
     }
}

package menu;

public class TreeDisplay{
     public static void main( String[] args ){
      Links link = Utility.setupLinks( "SomeName", "ResiyrbceBane");
       Utility.filterLinks( link, link.getChildren() );
     }
}
Is the utility class with so many static class is ok?
  • 1. Re: how to optimize this code + is design proper
    979025 Newbie
    Currently Being Moderated
    Well putting a number of static classes inside another class is just fine. Any number of static methods is ok, so that wont be an issue. As for your design, it is a matter of choice. It seems you are treating this as if a utility class is operating on a data set that you pass it rather than the class having the characteristics you are trying to build into it. It is a bit procedural in nature, not object oriented design. The user could pass you any list and you would have to handle it. A more object oriented way to do it would be to wrap the list in the class and make it a new data structure. In that manner you have control over what goes in and how things are arranged.

    As for filtering, I would declare an interface that has a single method that returns a boolean and gets a node in the data set. That way you dont constrain the nature of the filter. The user can pass you any implementation of the interface.
  • 2. Re: how to optimize this code + is design proper
    Kayaman Guru
    Currently Being Moderated
    Vicky wrote:
    I have two question is this code fine is there anything wrong with desin Plus how to handle removing child node in tree scenation where child can be in any place.
    See below for my comments about the design.
    As for removing child nodes, naturally you need to find the place in the tree where it resides and detach it from its parent node.
    Recursion works nicely for going through the tree.
    Is the utility class with so many static class is ok?
    The Utility class doesn't have any static (inner) classes. I assume you mean static methods, which by itself is fine. Your design is a bit peculiar though, since the usual way would be to have some sort of Tree class which would contain instance methods to work on the class, and TreeNode class which would then handle the actual structure.
  • 3. Re: how to optimize this code + is design proper
    814889 Newbie
    Currently Being Moderated
    Thanks Kraythe and kayaman.

    Well i thought about both of your comments on Utility class.You both seem to say it fine , but it is more of procedural oriented but if could guide me by modifying the same example from OO point of view it would be of great help for me.
  • 4. Re: how to optimize this code + is design proper
    Kayaman Guru
    Currently Being Moderated
    Vicky wrote:
    if you could guide me by modifying the same example from OO point of view it would be of great help for me.
    A simple and obvious way would be to rename the Utility class to something like "MyTree", introduce a "Link rootNode;" variable to denote the tree's root and make the methods non-static.
    Then the non-static methods would operate on the rootNode, instead of accepting it as a parameter like you're doing now.
  • 5. Re: how to optimize this code + is design proper
    814889 Newbie
    Currently Being Moderated
    Can you please let me know why would that be better than utiltiy class , I am just curious to know.
  • 6. Re: how to optimize this code + is design proper
    TPD-Opitz-Consulting-com Expert
    Currently Being Moderated
    Your utility class stresses the separation of concerns pattern. I filters and prints the tree.

    I'd create a filter interface:
    interface Filter<E> { boolean accept(E object); }
    This could be used to actually filter the tree (createing a new tree containig only nodes matched by the filter).
    For printing this tree I'd create another class:
    interface NodePrinter {
       void print(Node node);
       static final NodePrinter CONSOLE = new  NodePrinter() {
           void print(Node node){
              System.out.print(getInsets(node.getLevel())); // how many spaces or '|' before the node...
              System.out.println(node.toString());
           }
      }
    }
    and pass each of the filtered nodes to it.
    In case the print target changes to some kind of structured file (possibly XML) I'd simply create another <tt>NodePrinter</tt> constant...

    bye
    TPD
  • 7. Re: how to optimize this code + is design proper
    Kayaman Guru
    Currently Being Moderated
    Vicky wrote:
    Can you please let me know why would that be better than utiltiy class , I am just curious to know.
    It would be more object oriented. A Tree class knows how to handle itself, now you have this TreeUtility class that handles the operations and then the separate Link class which handles the data.
    Why not bundle them together in a nice tidy package?

    Basically the difference is as follows:
    Utility.addNode(tree, node);
    vs.
    myTree.addNode(node);
  • 8. Re: how to optimize this code + is design proper
    814889 Newbie
    Currently Being Moderated
    Thanks TPD

    If you could write more on it , it will be great i rarely find ocasations of using interfaces , however i don't think creating a new tree with valid node could be better solution as you have to create a new tree keeping the same hierarchy .

    Kayaman,

    This code is acutally used in J2ee application so does this fit in j2ee application which used jsf.there will be object created every time user hits, we have about 40k users still do you feel converting utiltiy class to a oops class is it better.



    The real test of Design patter and oops comes in this scenario.Please let me know your thougths
    Which Design Pattern and how to design using OOP this scenario
  • 9. Re: how to optimize this code + is design proper
    Kayaman Guru
    Currently Being Moderated
    Vicky wrote:
    i rarely find ocasations of using interfaces
    That's worrying. Means that you should brush up on the basics.
    This code is acutally used in J2ee application so does this fit in j2ee application which used jsf.
    That has nothing to do with anything.
    there will be object created every time user hits, we have about 40k users still do you feel converting utiltiy class to a oops class is it better.
    It's more object oriented and it's the way practically all the Java objects you use are designed. If you think it's somehow more efficient to have a class
    with static methods, instead of an instance with instance methods, you're wrong.

    What is your position? Are you a junior developer?
  • 10. Re: how to optimize this code + is design proper
    gimbal2 Guru
    Currently Being Moderated
    Kayaman wrote:
    Vicky wrote:
    i rarely find ocasations of using interfaces
    That's worrying. Means that you should brush up on the basics.
    Oh? Compared to the amount of classes I create, I too rarely create an interface. Good thing too because otherwise you're just over-abstracting things. I apply plenty of them of course and mostly those in the standard JDK, but to actually create one myself is only when the design calls for it; which is not too often.
  • 11. Re: how to optimize this code + is design proper
    TPD-Opitz-Consulting-com Expert
    Currently Being Moderated
    Vicky wrote:
    Thanks TPD

    If you could write more on it , it will be great i rarely find ocasations of using interfaces , however i don't think creating a new tree with valid node could be better solution as you have to create a new tree keeping the same hierarchy .
    The advantage is that all other components do not need to know that they work with a filtered tree.
    Certainly you can do it the other way around bye passing the tree and the filter to eg. the <tt>NotePrinter</tt> Object, but than all components working with the tree meight neet to know that ther are Node filters.

    I just came up with the Idea to give the nodes themselfes knowlege of the Filter via <tt>setFilter(Filter<Links> myFilter)</tt>. You would call this on the root node and in the <tt>getChildren()</tt> method you would check if the child apllies to the filter and pass that filter to the eliable childs before putting them into a new collection which is returned to the caller. Ofcause you should initialise the <tt>this.filter</tt> property in <tt>Links</tt> with a <tt>ALL_NODES</tt> constant.

    Also you should resist the tamptation to make the <tt>this.filter</tt> property in <tt>Links</tt> static. This would save you one line of code in the <tt>getCildren()</tt> method by the cost that you cannot have different trees with different filters in the same JVM.
    This kind of interference between threads is pretty hard to find later in production environments...

    bye
    TPD
  • 12. Re: how to optimize this code + is design proper
    Kayaman Guru
    Currently Being Moderated
    gimbal2 wrote:
    Oh? Compared to the amount of classes I create, I too rarely create an interface.
    I should hope so. I don't know what kind of code you work on usually, but even Java EE doesn't require those superfluous interfaces everywhere anymore.
    I was basing my answer mainly on what information I discerned from the OP. Even if you wouldn't use an interface, it still shouldn't be too hard to find places where they could be used.
    but to actually create one myself is only when the design calls for it;
    Well, I think Vicky's design might benefit from an interface or two. Then again there seems to be a lot space for improvement in any case.
    which is not too often.
    Hear hear. I inherited a project that was designed by an "abstract generalist". Dozens of unnecessary mechanisms and abstractions just to do simple things.
  • 13. Re: how to optimize this code + is design proper
    814889 Newbie
    Currently Being Moderated
    Thanks TPD

    But a full fleged code might have been better to understand.


    KayaMan ,
    I am little above junior developer , that is why i am asking help from u senior folks to help me understand object oriented programming better.

    Edited by: Vicky on Dec 12, 2012 3:31 AM
  • 14. Re: how to optimize this code + is design proper
    gimbal2 Guru
    Currently Being Moderated
    Vicky wrote:
    KayaMan ,
    I am little above junior developer , that is why i am asking help from u senior folks to help me understand object oriented programming better.
    Unfortunately that cannot be instructed, you need to learn it by doing and by thinking until you understand the material through and through. Most people take 10 years to get to a point where they apply OOP effectively without making design mistakes in between, lots of people never really get it.

    Practice, make lots of mistakes and take the time to learn from those mistakes. That last part is what lots of people nowadays don't have the patience for anymore.
1 2 Previous Next

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points