Greetings zperryz.
The criticism that your code violates encapsulation is a bit nit-picking, but it is correct.
What you are doing (in Main) is saying, "Okay invoice, tell me where your data (the list of invoice lines) is. Right, now that I know where it is, I will manipulate it (by adding lines)."
What you should be doing is saying, "Okay invioce, here are some lines. Please add them to your data." That is, outside of the invoice class, you should not care how an invoice stores and retrieves its data - it could be in a List, an array, a fixed set of properties, whatever - as long as you can request that it add, delete, print and so on. Then, should the need arise, you can change the internal workings of the invoice class and the outside world need never know. As it stands, if you were to change the list of lines to, say, an array, then the lines in Main would have to be changed to match.
Add a method to the invoice class like this...
// I would call this method just "AddLine", but we should follow your instructions I suppose.
AddLineItem(InvoiceLine line)
{
invoiceline.Add(line);
}
Then change Main to use the new method like this...
static void Main(string[] args)
{
Invoice BHinv = new Invoice(5,4,0.35m); // passes value to Invoice Amount, Days Due, Number of Items and Terms Percentage
BHinv.AddLineItem(new InvoiceLine { linenumber = "10", lineamount = 10 });
BHinv.AddLineItem(new InvoiceLine { linenumber = "20", lineamount = 20 });
Console.WriteLine("invoice amount {0}: invoice date {1}: days due {2}: Due Date {3}: Number of Items {4}: Terms percentage {5}: Average $$ amount {6}: terms amount {7}: ", BHinv.GetAmount, BHinv.invdte, BHinv.daysdue, BHinv.duedate, BHinv.numofitms, BHinv.termspercnt, BHinv.avedollamnt, BHinv.termsamount);
Console.ReadLine();
}
Finally, instantiate the list inside the class, not in Main.
public Invoice(int daysdue, int numofitms, decimal termspercnt)
{
days_due = daysdue;
number_of_items = numofitms;
terms_percent = termspercnt;
invoiceline = new List<InvoiceLine>();
}
No comments:
Post a Comment