DEV Community

Discussion on: When do you create a function or method?

Collapse
 
revskill10 profile image
Truong Hoang Dung • Edited

Please always use function as possible, and outsource the this.
I mean, instead of

class AwesomeClass

  def hello_world
    this.variable = other_method();
  end

end

use this


def hello_world(this)
  this.variable = other_method();
  return this;
end
Collapse
 
codevault profile image
Sergiu Mureşan

Which language is this?

Collapse
 
revskill10 profile image
Truong Hoang Dung

It's just a pseudocode based on Ruby.

Thread Thread
 
codevault profile image
Sergiu Mureşan

Interesting. Few languages have this feature. So does that make the function an actual method but outside the class?

Thread Thread
 
revskill10 profile image
Truong Hoang Dung

I edited by replacing function with def keyword.
Basically, instead of making class as global, use more functions as global primitives.

Thread Thread
 
codevault profile image
Sergiu Mureşan

And where do you put these functions?

Thread Thread
 
revskill10 profile image
Truong Hoang Dung

Put those right in Ruby files. Then when you require that file, you can use your functions.

Thread Thread
 
codevault profile image
Sergiu Mureşan

So just one extra file where you put all functions (or methods in this case) related to that class?

Thread Thread
 
revskill10 profile image
Truong Hoang Dung

my_modules.rb

def function1
end

def function2
end
Collapse
 
bbasile profile image
Basile B.

Yes this is based on the fact that member functions should only be added if they use private or protected declarations. Member functions that use only the public declarations of an aggregate are just bloating the aggregate. This can even, in some rare cases, have a performance penalty, for example if the language has virtual by default (yes this exists !) however most of the time it's just a matter of readability (especially for languages that don't separate the declarations from the implementation).