SimplePHPEasyPlus icon indicating copy to clipboard operation
SimplePHPEasyPlus copied to clipboard

This library needs a factory

Open Nemoden opened this issue 13 years ago • 2 comments

This isn't the actual issue - it's more like a "feature request".

Every good programmer who cares about structure of the application know that there is no way in modern software libraries development to omit factory design pattern.

I do understand the purpose of all the classes and they are really useful - I and my team were facing an issue addressing calculation of sum of two integers and as a special case calculation the sum of 1 and 1. Now, we can get over this issue using your library which is following the best OOP practices making it easier to both test and use.

The problem with your code comes if you want to calculate 1 + 1 in binary. The code we use is, well, pretty ugly since we still follow procedural paradigm in programming:

sum_one_plus_one($is_bin=false) {
    if ($is_bin) {
        return "10"; // ugly, huh? but we found no other way before we've found your lib
    }
    ... 
    // sorry, I can not reveal the rest of the code since it's a company's secret 
    // and I was allowed just to show the part with binary calculation of 1 + 1
}

What I suggest here is, we create a NumberFactory like so:

class NumberFactory implements NumberFactoryInterface {
    public function __construct($number, $t='simple') {
        $class = ucfirst($t)  . 'Number';
        return new $class($number); // either SimpleNumber or BinaryNumber
    }
}

and of course we need BinaryNumber class (the actual code of this class is pretty much alike code of SimpleNumber, so I don't think my help is necessary here).

$numberFactory = new NumberFactory();
$firstNumber = new NumberFactory($firstParsedNumber, 'binary');

Now it look a lot better, right?

If you could implement this, I and my team would deeply appreciate it so as the rest of PHP programmers would do as well, I think.

Thank you. Great job.

Nemoden avatar Dec 06 '12 04:12 Nemoden

Incautious introduction of BinaryNumber could easily break the "Don't Repeat Yourself" (DRY) principle since it would naturally require implementing factory and specifying yet another interface that look just like SimpleNumber's. Instead of doing it that way, I'd remove SimpleNumber and BinaryNumber altogether in favor of number serialization strategies. That way we could represent our numbers in any way we want: be it decimal, binary, octal or hexadecimal number system. The benefit is that we could also easily adapt this mechanism to serialize the numbers to output Roman numbers or even natural text. (If one, however, needs to serialize the numbers to languages other than English, it might need some additional thinking as to how specify the language and its grammar without hardcoding it, which is popular beginner's mistake.)

rr- avatar May 09 '14 18:05 rr-

take a stab

cordoval avatar May 09 '14 18:05 cordoval