Is it good to declare a class with many methods ?
Or, is it better to use flags ?
Which one performs faster ?

Example

class Filter {
public function filterspecialchar($input){;}
public function filterurl($input){;}
public function filteremail($input){;}
}

class Filter {
CONST SPECIALCHAR = 1;
CONST URL = 2;
CONST EMAIL = 3;
public function filter($input, $flags) {;}
}
Member Avatar for diafol

How is the client (could be you) going to use this code?

Are you going to remember all the integers and what they mean? Flags are beautiful, but you need to keep referring to the manual - or your class code if you don't document!

Perhaps static methods would serve as well? Do you need to create an object for checking an url?

Imagine we have the following class constants...

const TRIAL1 = 1;
const TRIAL2 = 2;
const TRIAL4 = 4;

As they are binary in nature, we can add them together to pass "combined actions to perform".

echo Filter::filter($input, 5); //this would equate to TRIAL1 and TRIAL4

Equally you could use the non-static equivalent):

$f = new Filter;
echo $f->filter($input, 5);

For named flags you'd do this...

echo Filter::filter($input, Filter::TRIAL1|Filter::TRIAL4);

echo $f->filter($input, Filter::TRIAL1|Filter::TRIAL4);

If your constants are defined outside the class, then no problem...

echo Filter::filter($input, TRIAL1|TRIAL4);

echo $f->filter($input, TRIAL1|TRIAL4);

Using named constants as flags is a bit slower than integers in my tests. There was no discernable difference in time between simple static and non-static methods.

If you can make your flags memorable and accessible, then they may make it easier for the client. If you don't need to run multiple operations (multiple flag values), then individual methods may well serve you better. After all, your flagged methods would only pass off the operation to other methods in your class using a conditional if or even a switch block.

$cleanUrl = Filter::clean_url($url);

May be easier than...

$cleanUrl = Filter::filter($url, 2);

Or

$cleanUrl = Filter::filter($url, Filter::CLEAN_URL);

Or even if you fill define outside the class...

$cleanUrl = Filter::filter($url, CLEAN_URL);

Sorry starting to ramble...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.