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
An object is a collection of functions and data. A function is a collection of commands and data.
Every function is an object. Objects can contain functions (methods) but an object is not necessary a function.
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.
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.
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.
Functions typically do one specific task.
Objects represent something that have tasks associated with it. (methods)
Use a function for tidy
. Plain and simple. ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With