Free mag vol1 | Page 260

CHAPTER 5  UNDERSTANDING ENCAPSULATION public Employee(string name, int id, float pay) :this(name, 0, id, pay){} public Employee(string name, int age, int id, float pay) { empName = name; empID = id; empAge = age; currPay = pay; } // Updated DisplayStats() method now accounts for age. public void DisplayStats() { Console.WriteLine("Name: {0}", empName); Console.WriteLine("ID: {0}", empID); Console.WriteLine("Age: {0}", empAge); Console.WriteLine("Pay: {0}", currPay); } } Now assume you have created an Employee object named joe. On his birthday, you want to increment the age by one. Using traditional accessor and mutator methods, you would need to write code such as the following: Employee joe = new Employee(); joe.SetAge(joe.GetAge() + 1); However, if you encapsulate empAge using a property named Age, you are able to simply write Employee joe = new Employee(); joe.Age++; Using Properties Within a Class Definition Properties, specifically the “set” portion of a property, are common places to package up the business rules of your class. Currently, the Employee class has a Name property that ensures the name is no more than 15 characters. The remaining properties (ID, Pay, and Age) could also be updated with any relevant logic. While this is well and good, also consider what a class constructor typically does internally. It will take the incoming parameters, check for valid data, and then make assignments to the internal private fields. Currently, your master constructor does not test the incoming string data for a valid range, so you could update this member as so: public Employee(string name, int age, int id, float pay) { // Humm, this seems like a problem... if (name.Length > 15) Console.WriteLine("Error! Name must be less than 16 characters!"); else empName = name; empID = id; empAge = age; 196