Encapsulate collection

We have the following code:

function Order() {
         this.orderLines = [];
         this.orderTotal = 0;
}
Order.prototype.getOrderLines = function() {
         return this.orderLines;
};
Order.prototype.addOrderLine = function(orderLine) {
         this.orderTotal += orderLine.total;
         this.orderLines.push(orderLine);
};
Order.prototype.removeOrderLine = function(orderLineItem) {
         var orderTotal, orderLine;
         orderLine = this.orderLines.map(function(order) {
                  return order === orderLineItem;
         })[0];

         if(typeof orderLine === 'undefined' || orderLine === null) {
                  return;
         }
         this.orderTotal -= orderLine.total;
         this.orderLines.splice(this.orderTotal, 1);
};

The problem with this code is that anyone could get access to orderLines and add or modify values without increasing or decreasing orderTotal.

Modify the code to encapsulate the collection to avoid this issue.

Last updated

Was this helpful?