February 26, 2012

Best way to loop through an MboSet

This entry is part of the Maximo Java Development series.

In this article I will describe some common ways of iterating through an MboSet and what is the best approach.
In the following examples mboSet is the already holding the MboSetRemote that you need to traverse.

Example 1 (worst solution)

for(int i=0; i<mboSet.count(); i++;)
{
    MboRemote currMbo=mboSet.getMbo(i);
    ...
}

The MboSet.count() method will issue a SELECT COUNT(*) query to the database for each loop. This will seriously affect the looping performances with an unnecessary workload on the database server too.

Example 2 (good solution)

MboRemote currMbo=null;
for(int i=0; (currMbo=mboSet.getMbo(i))!=null; i++)
{
    ...
}

This is a good approach from a performance point of view. However, I'm a Java-purist so I'm still not fully satisfied in terms of code style.

Example 3 (best solution)

for(MboRemote currMbo=mboSet.moveFirst(); currMbo!=null; currMbo=mboSet.moveNext())
{
    ...
}

Very concise syntax. Inline declaration of MboRemote object. Iterator style. Index variable i no longer needed. Perfect :-)

6 comments:

  1. Hi,

    How can i do it with automation script??
    Please assist

    ReplyDelete
  2. There is another option:

    MboSetEnumeration mboIter = new MboSetEnumeration(mboSet);

    for (MboRemote currMbo = mboIter.nextMbo(); mboIter.hasMoreElements(); currMbo = mboIter.nextMbo()) {
    ...
    }

    ReplyDelete
    Replies
    1. Nice alternative!
      I still prefer the MboSet.moveNext() approach because is shorter and does not rely on the additional class MboSetEnumeration.
      But we are just talking of 'aesthetics' here :-)
      Thank you David.

      Delete
  3. for(MboRemote currMbo=mboSet.moveFirst(); currMbo!=null; currMbo=mboSet.moveNext())
    {
    ...
    }

    how can you do this in an Automation Script python or jython?

    ReplyDelete
    Replies
    1. This is a way to do it in Jython:

      currMbo = mboSet.moveFirst()
      while currMbo:
      # the code inside the loop here
      currMbo = mboSet.moveNext()

      The Blogspot platform is removing leading spaces at each line you need to add 1 blank space before the 2 last lines.

      Delete