1
0
mirror of https://github.com/jupeter/clean-code-php.git synced 2025-09-26 05:59:04 +02:00

Merge pull request #35 from peter-gribanov/avoid_type_checking1

Avoid type-checking (part 1)
This commit is contained in:
Tomáš Votruba
2017-08-31 19:51:07 +02:00
committed by GitHub

View File

@@ -684,28 +684,34 @@ class Cessna extends Airplane {
**[⬆ back to top](#table-of-contents)** **[⬆ back to top](#table-of-contents)**
### Avoid type-checking (part 1) ### Avoid type-checking (part 1)
PHP is untyped, which means your functions can take any type of argument. PHP is untyped, which means your functions can take any type of argument.
Sometimes you are bitten by this freedom and it becomes tempting to do Sometimes you are bitten by this freedom and it becomes tempting to do
type-checking in your functions. There are many ways to avoid having to do this. type-checking in your functions. There are many ways to avoid having to do this.
The first thing to consider is consistent APIs. The first thing to consider is consistent APIs.
**Bad:** **Bad:**
```php ```php
function travelToTexas($vehicle) { function travelToTexas($vehicle)
{
if ($vehicle instanceof Bicycle) { if ($vehicle instanceof Bicycle) {
$vehicle->peddle($this->currentLocation, new Location('texas')); $vehicle->peddleTo(new Location('texas'));
} else if ($vehicle instanceof Car) { } elseif ($vehicle instanceof Car) {
$vehicle->drive($this->currentLocation, new Location('texas')); $vehicle->driveTo(new Location('texas'));
} }
} }
``` ```
**Good**: **Good**:
```php ```php
function travelToTexas($vehicle) { function travelToTexas(Traveler $vehicle)
$vehicle->move($this->currentLocation, new Location('texas')); {
$vehicle->travelTo(new Location('texas'));
} }
``` ```
**[⬆ back to top](#table-of-contents)** **[⬆ back to top](#table-of-contents)**
### Avoid type-checking (part 2) ### Avoid type-checking (part 2)