mercredi 22 juillet 2015

Is a good design that use inner class in the class?

I have a class called SalesOrder (SO), that allows users to buy several items in a single order. SO has an order number.

class SalesOrder {
   public String orderNumber;
}

Each SO has many items in it, so I have created a new class OrderItem which has the item name and price.

class OrderItem {
    public String name;

    public double price;
}

Each SO has a order header, include user name and address. It also has a field called total price, which hold the sum of all items prices

class OrderHeader {
    public String username;

    public String address;

    public double totalPrice;
}

After that, I added two fields to SO:

class SalesOrder {
    ...

    public List<OrderItem> items;

    public OrderHeader header;
}

Because OrderItem and OrderHeader are always used with SalesOrder and the header should return all items prices, I converted them to be be inner classes of SalesOrder.

class SalesOrder {


    ...

    public  SalesOrder() {
        this.items = new ArrayList<>();
        this.header = new OrderHeader();
    }   

    public class OrderItem {
       ...
    }

    public class OrderHeader {
        ...

        public double getTotalPrice() {
             double total = 0.0;
             // loop SalesOrder.items
             total += items[i].price;          
             return total;
        }
    }
}

My question is whether using inner classes like this is good OOP design? If not, how should they be designed?

Aucun commentaire:

Enregistrer un commentaire