如何避免嵌套for-each循环?

时间:2015-05-09 00:27:03

标签: java xml jaxb

我有一个应该解析XML文件的类,如下所示:

<customers>
        ...
        <customer>
            <id>123456</id>
            <name>Mike</name>
            <orders>
                ...
                <order>
                    <id>233658</id>
                    <positions>
                        ...
                        <position>
                            <id>12345</id>
                            <price>10.0</price>
                            <count>5</count>
                        </position>
                        ...
                    </positions>
                </order>
                ...
            </orders>
        </customer>
<customers>

我要用JAXB取消它,而不是处理结果对象来获取统计数据(如最大订单金额,总订单金额等)

在这种情况下使用3级foreach循环是不好的做法?

public void getStatistics() {
    for (Customer customer: this.customers.getCustomer()) {

        BigDecimal customerTotalAmount = new BigDecimal(0);
        for (Order order : customer.getOrders().getOrder()) {

            BigDecimal orderAmount = new BigDecimal(0);
            for (Position position : order.getPositions().getPosition()) {
                orderAmount = orderAmount.add( position.getPrice().multiply(new BigDecimal(position.getCount())) );
            }

            customerTotalAmount = customerTotalAmount.add(orderAmount);
            this.totalOrders++;
        }

        this.totalAmount = this.totalAmount.add(customerTotalAmount);
    }
}

客户,订单和职位类已从XSD架构自动生成,我认为更改它们并不好。

我做错了什么?我怎样才能避免那些嵌套循环?

谢谢。

1 个答案:

答案 0 :(得分:4)

我建议提取一些方法:

public void getStatistics() {
    for (Customer customer: this.customers.getCustomer()) {
        BigDecimal customerTotalAmount = processCustomer(customer);
        this.totalAmount = this.totalAmount.add(customerTotalAmount);
    }
}

private void processCustomer(Customer customer){
    BigDecimal customerTotalAmount = new BigDecimal(0);
    for (Order order : customer.getOrders().getOrder()) {
        BigDecimal orderAmount = new BigDecimal(0);
        for (Position position : order.getPositions().getPosition()) {
            orderAmount = orderAmount.add( position.getPrice().multiply(new BigDecimal(position.getCount())) );
        }

        customerTotalAmount = customerTotalAmount.add(orderAmount);
        this.totalOrders++;
    }
    return customerTotalAmount;
}

为Order和Position循环执行相同的操作,为方法提供足够的描述名称,并确保它们返回正确的值,并获得一个漂亮,干净的代码。这些仍然是嵌套的循环,但是当你看到它们时,至少你的眼睛不会受伤。