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?

42

u/nutterontheloose Apr 05 '22

I understand the usefulness of overloading, but static functions... I just make it static when the IDE tells me to without really understanding why. So, thank you, you taught me something today.

6

u/Longjumping_Round_46 Apr 05 '22

Without static functions, (in C# atleast) to use a function you have to instantiate a class.

Car myCar = new Car("Honda", "Jazz", 2014);

myCar.driveSomewhere();

But with static functions, you don't need to instantiate a class. This can be used very well in say, logging.

Car myCar = new Car("Honda", "Jazz", 2014);

myCar.driveSomewhere();

CarLogger.LogMiles(myCar, 100);

You don't need to do this:

CarLogger logger = new CarLogger();

logger.LogMiles(myCar, 100);

Anywhere in your code you can access that class, you can access that function without creating a new instance of that class.

If you understand the concept, this static functions/classes can be a very useful too, for logging, checking something, hashing, etc.