Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function vs Objects Best Practice

I am wondering whats the best practices regarding functions and objects. For example I want to perform an action called tidy. It will take my data as input and tidy it and return it.

Now I can do this in two ways. One using a simple function and the other using a class.

Function: $data = tidy($data);
Class:
$tidy = new Tidy();
$data = $tidy->clean($tidy);

Now the advantage in making it a class is that I do not have to load the class before. I can simply use the autoload feature of php to do so.

Another example is the database class. Now everyone seems to be using a separate class for db connectivity. But we usually have a single object of that class only. Isn't this kind of contrary to the definition of class and objects in a sense that we are using the class only to intantiate a single object?

I kind of dont understand when to use a function and when to use a class. What is the best practice regarding the same? Any guidelines?

Thank you, Alec

like image 631
Alec Smart Avatar asked Jan 30 '09 04:01

Alec Smart


People also ask

What is the difference between functions and objects?

An object is a collection of functions and data. A function is a collection of commands and data.

Is every function an object?

Every function is an object. Objects can contain functions (methods) but an object is not necessary a function.

Can a function be an object?

Values can be passed to a function, and the function will return a value. In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

What is a function when is it good practice to use a function in JavaScript?

JavaScript functions are essential when writing JavaScript programs if you want to execute a block of code as many times as you want without having to write the same block of code repeatedly in your program. We can simply say the function is a saved algorithm given to a program to work with when called upon.


2 Answers

For something that does one thing, and only one thing, I'd just use a function. Anything more complex, and I'd consider using an object.

I took the time to poke through some piles of (arguably ugly and horrible) PHP code and, really, some things could have been done as objects, but were left as functions. Time conversions and string replacements.

like image 92
hydrapheetz Avatar answered Sep 27 '22 19:09

hydrapheetz


  • Functions typically do one specific task.

  • Objects represent something that have tasks associated with it. (methods)

Use a function for tidy. Plain and simple. ;-)

like image 39
Evan Fosmark Avatar answered Sep 27 '22 19:09

Evan Fosmark