Pages

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 :-)

8 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
  4. The moveNext loop can have an issue if some action being done in the loop also triggers logic that changes the current record for the set. This could lead to an infinite loop or some other unexpected behavior. moveNext would be OK with a simple loop that doesn't trigger any other actions, but safer loop is option 2, so no other logic that gets triggered in the middle of the loop that can change your current record.

    ReplyDelete
  5. You can also use the fetchNext() method to iterate through a MboSet. Such as:
    while ((currMbo = mboSet.fetchNext()) != null) {
    ...
    }

    ReplyDelete

Note: Only a member of this blog may post a comment.