[Key, values], magic, fast, malleable and error prone.
TL;DR: Use arrays for rapid prototyping, use object for serious business.
-
Coupling
-
Information Hiding
-
Code Duplication
-
Fail Fast
-
Integrity
-
Reify objects
-
Create cohesive small objects
-
Don't leave them anaemic, find their cohesive relations.
<?
$coordinate = array('latitude'=>1000, 'longitude'=>2000);
// They are just arrays. A Bunch of raw data
<?
final class GeographicCoordinate {
function __construct($latitudeInDegrees, $longitudeInDegrees) {
$this->longitude = $longitudeInDegress;
$this->latitude = $latitudeInDegress;
}
}
$coordinate = new GeographicCoordinate(1000, 2000);
// Should throw an error since these values don't exist on Earth
<?
final class GeographicCoordinate {
function __construct($latitudeInDegrees, $longitudeInDegrees) {
if (!$this->isValidLatitude($latitudeInDegrees)) {
throw new InvalidLatitudeException($latitudeInDegrees);
// ...
$this->longitude = $longitudeInDegrees;
$this->latitude = $latitudeInDegrees;
}
}
}
$coordinate = new GeographicCoordinate(1000, 2000);
// throws an error since these values don't exist on Earth
<?
final class Latitude {
function __construct($degrees) {
if (!$degrees->between(-90, 90)) {
throw new InvalidLatitudeException($degrees);
}
// ...
}
}
Many people suffer from primitive obsession and believe this is over design. Designing software is about making decisions and comparing trade-offs. The performance argument is not valid nowadays since modern virtual machines can efficiently deal with small short-lived objects.
<?
final class GeographicCoordinate {
function distanceTo(GeographicCoordinate $coordinate) { }
function pointInPolygon(Polygon $polygon) { }
}
// Now you are in geometry world (and not in the world of arrays anymore).
// You can safely do many exciting things.
We cannot forbid Associative Arrays since they are very good as a first approach.
They will be fine for exporting data, serialization, persistence and other accidental implementation issues.
We should avoid them on our systems.
- Primitive
When creating objects, we must not think of them as data. This is a common misconception.
We should stay loyal to our Bijection and discover real-world objects.
Most associative arrays have cohesion and represent real-world entities, and we must treat them as first class objects.
Refactoring 012 - Reify Associative Arrays
Photo by Melissa Askew on Unsplash
There’s nothing more permanent than a temporary hack.
Kyle Simpson
Software Engineering Great Quotes
This article is part of the CodeSmell Series.