1.4.12 How to Avoid Using Hardcoded Values

Hardcoded means anything that has a value assigned to it that is permanent.

For example, in the method below, the 2 that is being added to the Employee's Weight is hardcoded. No matter what, whenever an Employee eats, they will gain 2 lbs and nothing else. But what if they only eat a handful of Skittles as a snack? Or what if they eat a four course meal? That's not representative of the human condition. Being able to make things dynamic solves those questions.

An example of how to do this is to use parameters. As it is right now, the Eat method has a parameter of type int named amount. In the MainWindow, the value being passed in is 2.

What we can do, then, is replace the hardcoded 2 in the Eat method with the amount parameter.

What that allows us to do is change the value being passed in to the Eat method and the method will change based on that value. Now, Sam can eat once and gain 2lbs and then we can make him eat again and he will gain 5lbs.

While doing that solves how the Eat method functions, we are still hardcoding the amount passed in. What we really want to pass in is the weight of whatever food Sam is eating. And sometimes we don't have that information. So instead what we can do is pass in a reference to the food's weight.

Now if Sam finishes the Monkey Tail and wants to eat something else...

...the weight of the food will be passed in and assigned to the amount parameter and he will gain the 5lbs.