Let’s talk Functions

I think two of the biggest things I struggled with learning programming was understanding functions. On the surface they seem simple enough, you stick something in and something comes out. However, a poorly written function can have strange behaviors. Not to mention it is not always easy to determine when a function requires a return value when you’re new to programming. Personally, I am not the most consistent and I think it is up to personal choice. It is probably more straightforward for other programmers to include a return statement, but your overall result may be more readable if the function itself outputs a value directly. I also struggled with passing values in functions in some languages.

In some languages such as C++ there are two ways to pass a value into a function: by value and by reference. A simple way of thinking of these is to think of pass by reference being a copy-paste operation. The original value will remain unaffected, but a copied version will change based on function operations. On the other hand, pass by value means that the original value will be altered. In other words, pass by value is destructive and pass by reference maintains the original value. I typically favor pass by value unless I feel like I absolutely need the original value somewhere else.

An example of pass-by-value would be an application I made for Visual Basic class. It was meant to be an employee form that output data into a CSV file. One of the changes we needed to make was ensure it could correct someone’s name and capitalize names correctly. By working on the original value I was able to minimize the amount of memory required, and work through the string just as quickly as normal. However, there are times you may want access to the original value.

An example of when you would want the original value and a new value is my Harry Potter app. Now the way I do things is that I use a return statement to output the new value. However passing by reference in hindsight may have made it more straightforward. The functions would effectively have had local copies of the variable to work with instead of the original value. This is also worth considering as an approach in languages that are pass-by-value only if you need a reference. You can play with return statements or variable scope to get around that restriction. In languages such as C++ I also recommend spending a little time with getters and setters. The difference is effectively that getters will return the value they are getting, and setters will use their arguments to set a class member’s value. Hopefully this helps.

If you make a purchase at Amazon using the link below I may receive a commission.
Tech Best Sellers

Leave a comment

Your email address will not be published. Required fields are marked *