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

标签 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);
    }
}

Customer、Order 和 Position 类已经从 XSD 模式自动生成,我认为更改它们并不好。

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

谢谢。

最佳答案

我会推荐提取一些方法:

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 循环执行相同的操作,为方法提供足够描述性的名称并确保它们返回正确的值,然后您将获得一个漂亮、干净的代码。这些仍然是嵌套循环,但至少当你看到它们时你的眼睛不会受伤。

关于java - 如何避免嵌套的 for-each 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30134686/

相关文章:

android - Android 是否需要 JAXB 实现?

java - 我是否仍然应该在生产代码中使用 JAXB 对象中的枚举?

java - 3 项 IllegalAnnotationExceptions

java - 重新排序 GridLayout SWT

java - 使用 Jackson 序列化 xml 使用不带注释的属性

java - 如何模拟私有(private) setter/getter ?

java - 仅使用 Android View.onDraw() 进行绘图更改

xml - 如何创建要在 OpenCV 中使用的 Haar Cascade(.xml 文件)?

java - Android 条形 Activity 指示器

python - Python 2.6.2 中的 ElementTree 处理指令支持吗?