Place Methods In/Outside of Constructor?

I was reading a script and realized that they created the api in the constructor. The only thing that is outside of the constructor is a metamethod called function Mouse:__tostring(). The way that I learned it is to create the methods outside of the constructor.

Since I found this, I have been questioning which way is better. To me, having the methods outside seems better because it would make it easier to read, but there must be a reason why the other person decided to put it in the constructor.

There might be a functional purpose for this but I am a big oop noob so idk.

The script is a mouse module by @Crazyman32

2 Likes

It is objectively better to place your methods outside of your constructor. The post you linked to is pretty old so it probably more-so reflects the style of the era.

If you place your methods in the constructor, you miss out on the benefits of object oriented design while taking on all the bad parts still.

If your method can be factored out of your class and instead of having its object instance in scope it could use the self parameter then it’s a good idea to factor it out.

To visualize what this style is doing in maybe a different language, I’ll bring out my probably slightly wrong recollection of C# syntax.
Method in constructor:

class MyClass {
    delegate void Del();
    Del method;
    MyClass() {
        this->method = () => do_something_here;
    }
}

Method outside constructor:

class MyClass {
    void method() {
        do_something_here;
    }
    MyClass() {}
}

One of these doesn’t look quite right, does it.

2 Likes

Yeah, that code was by me. It was early on before proper OOP styles were solidified across Roblox’s dev community.

As @Autterfly said, it’s better to use them outside of the constructor. For instance, check out my Gamepad module.

Another reason to use them outside is for memory. When you create 100,000 instances of your object, there will only be one copy of the methods. They’re all shared. It just passes the self parameter to denote the actual instance within the method. If you were to put the methods inside the constructor, you would create 100,000 copies of those methods too.

2 Likes