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

Show parent comments

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.

21

u/EvolvedCookies Apr 05 '22

If its called on an object of that class it should not be static. Of the method has nothing to do with the class object then it should be static.

8

u/CozyRedBear Apr 05 '22

Static functions and static variables, when made public, are granted a sort of super-scope. They're decentralized. They transcend attachment to any individual objects instances. They effectively become a shared variable, without ownership to a specific object instance like how it is with most variables and functions. You can create 20 object instances and data can vary among them, but a static variable is the same across all of them. Static functions work similarly in that they can execute code without having to go through an object reference.

I use public static variables often when creating singletons and collections in game design. Every time I spawn a projectile, I add it to a static list so I can iterate over them as needed.

There exist use-cases for protected or private static variables, but it's harder to give simple examples of why you'd want to do that.

3

u/Fear_UnOwn Apr 06 '22

Pretty quick use case for a private static variable, a getter for a static variable!

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.

4

u/SurfingOnNapras Apr 05 '22 edited Apr 05 '22

Static means that something doesn’t change regardless of where or in what context an object is created.

Static functions, therefore take up less space because your computer wouldn’t have to allocate new memory for every instance of Character to have a getName() or getHealth() or getAttack(). They can just all call the class defined getName() on its own properties. Hopefully this example highlights a real performance benefit in where many things of class NPC or Players that extend Character need to be instantiated.

Static methods are also protected from being overridden, which can make things generally less buggy.

3

u/TheTomato2 Apr 05 '22

People are just answering without talking language semantics lol. Static depends on the language. In C++ it means like 5 different things. However for most OOP languages static members in classes make that a global thing. So say you have a static int in class foo, that means that int independent of any instantiated foo. It shouldn't be very hard to connect the dots on why that is useful.

→ More replies (1)

3

u/sufyspeed Apr 05 '22

You explained this so nicely!

1

u/[deleted] Apr 05 '22

[removed] — view removed comment

19

u/plastikmissile Apr 05 '22

import implies that it's a static method. See here.

3

u/[deleted] Apr 05 '22

[removed] — view removed comment

12

u/TheEpicSock Apr 05 '22

In languages like Java where everything is an object, you straight up can’t do the second one.

→ More replies (1)

5

u/plastikmissile Apr 05 '22

The second one is local to that bit of code. If you want to use it somewhere else then you'll want to have it in a class so everybody can have access to it.

2

u/[deleted] Apr 05 '22

[removed] — view removed comment

2

u/plastikmissile Apr 05 '22

Oh I think I misunderstood your question. So basically, if I understand your question correctly, it's whether you should have your method in a class or in a module. As far as I know they are functionally the same. Whether you want your method to be a static one in a class depends on if it makes sense for it to be part of the class.

1

u/rasmustrew Apr 05 '22

I'm not sure that there are any programming languages that allow both of those, but if there are i would certainly prefer the second form, it reads much more clearly.

→ More replies (3)
→ More replies (5)

2

u/[deleted] Apr 05 '22

Depends on language.

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.

→ More replies (1)

1

u/[deleted] Apr 05 '22

[removed] — view removed comment

4

u/plastikmissile Apr 05 '22

I'm going to use C# syntax (because my C++ is rusty) but I'm sure it will be clear enough.

First let's do things without static.

public class Math
{
    public int Add(int x, int y)
    {
        return x+y;
    }
}

public class Main
{
    public void DoSomething()
    {
        var mathInstance = new Math();
        var result = mathInstance.Add(10,20);
    }
}

As you see, to use Add we have to create a new instance of Math which we called mathInstance and then used that to access Add. Looking at the code for method Add you'll see that it only uses its inputs and nothing else. For all intents and purposes to Add the class Math may as well not exist.

So now let's do it the better way, and use static.

public class Math
{
    public static int Add(int x, int y)
    {
        return x+y;
    }
}

public class Main
{
    public void DoSomething()
    {            
        var result = Math.Add(10,20);
    }
}    

Note how we didn't need to instantiate Math at all, and just used Add directly. This only works because Add doesn't need access to any information in the instance.

If for instance the class Math looked like this instead:

public class Math
{
    private int z;

    public int Add(int x, int y)
    {
        return x + y + z;
    }
}

We wouldn't be able to make Add static, since it also uses z which is part of the instance. Unless you make z static as well.

ETA: Don't copy/paste while you are learning. It's OK to look up code, but type it in yourself. This way you force your brain to think about what it's doing, and thus learn.

1

u/gabrielsfarias Apr 05 '22

So overloading is just having the 2 or more functions with repeated arguments? Can I even have 2 functions with the same name?

If I have a function

sayMyName(name)
  { return name }

and another exact same function with (name, age), is this overloading?

→ More replies (3)