r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

53

u/[deleted] Apr 05 '22

[removed] — view removed comment

142

u/plastikmissile Apr 05 '22

Overloading functions

Say we have two functions. One adds only two numbers, while the other one adds three. Sure you can name them AddTwo(x,y) and AddThree(x,y,z), but they do the same thing with slightly different arguments. So we it's better to just name them Add(x,y) and Add(x,y,z). Not only we do we avoid the confusion inherent in having two (or more) names for the same functionality, IDEs can pick those different signatures up so that when you type in Add it gives you the option to pick between the two versions for auto completion.

Static functions

Let's go with that Add function we talked about. Let's say it's in class Math. Being a function that adds the numbers in the arguments, it doesn't really care about the state of the class it's in, since it uses nothing from there. So you should be able to call Add without going through the trouble of instantiating the class. Instead of doing:

var mathInstance = new Math();
var result = mathInstance.Add(33,55);

You can just declare Add static and go:

var result = Math.Add(33,55);

Much neater, no?

1

u/[deleted] Apr 05 '22 edited Apr 05 '22

So question about static objects/methods. I read that you should try not to use them if you don’t need to. I have been struggling on whether or not to implement them.

For example, I have a FileHandler class that deals with reading and writing to text files to deal with saved data. Is it better practice to always create a new object whenever these tasks are needed and set up the object in it’s constructor, or just make the object or methods static so they can always be called upon elsewhere in the program?

3

u/plastikmissile Apr 05 '22

This will be a matter of opinion, but generally speaking I use static whenever a method is something of a "utility" function that I want to use outside of the context of the class hosting it. So a bunch of math functions would be a perfect candidate for static.

As for the file handler, generally speaking you want to spend as less time as you can doing I/O since it's a bottleneck. That means grabbing resources when needed and immediately releasing them when finished. So if the method does all of this inside of it, without needing any outside resources, then yeah you can make it static.