I am working on modeling a business domain object in a class and wondering what would be the best way to properly encapsulate private fields that apply only to a few methods.
When I started, my code initially looked like this:
public class DiscountEngine { public Cart As Cart { get; set;} public Discount As Discount { get; set;} public void ApplySKUGroupDiscountToCart() { ... } }
However, ApplySKUGroupDiscountToCart() starting to get ugly, so I decided to refactor the code into smaller private methods that are called from ApplySKUGroupDiscountToCart() . I started by passing a large number of local variables to a helper method, but then decided to pull out the variables common to both routines and make them private modular variables. The new code is as follows:
public class DiscountEngine { public Cart As Cart { get; set;} public Discount As Discount { get; set;} private int _SKUGroupItemDiscountsApplied = 0 private int _SKUGroupTotalDiscounts = 0 private int _SKUGroupID = 0 public void ApplySKUGroupDiscountToCart() { ... } private void ApplyDiscountToSingleCartItem(ref CartItem cartI, ref DiscountItem discountI) { ... } }
On the one hand, three private integer fields are useful for allowing related methods to use shared variables without having to pass them back and forth as parameters. However, these variables only apply to these related methods, and any other methods that I could add should not be visible to them.
Is there a way to encapsulate private fields and their associated methods while remaining part of the DiscountEngine class? Is there a better way to solve this problem?
source share