When excessive complexity is not excessive

I had an interesting assignment recently, having received a multi-dimensional PHP array (about 4 levels deep) and was supposed to enable editing it - so what might seem obvious is starting like:

I decided to come up with an Object model for it looking like:

And I also created some other classes, representing the sub-nodes of the original data.

But what is most important in that kind of approach:

  • When the original structure changes - I only need to modify the getters/setters in my Object Model!
  • The code is clean and readable, as $element->getName() is much easier to comprehend than $array[”elements”][0][”element”],
  • The rest of your code doesn’t care about the data structure,
  • The OO flexibility allows you to abstract the “data” handling to be compatible with other data sources, e.g. XML files or relational databases,
  • You avoid “offset errors”, when you try to do calculations on a node which comes from different level of the array than you expect it to,
  • No repetition - you define only once “what comes from where”, later on you just user your definitions,

Of course the above sample also needs proper “usage” abstraction, which basically means objects are used according to the business rules, not the “byte manipulation”, e.g.

setFrom($data);
$MainNode->getName();
$Addresses = $MainNode->getAllAddresses();
foreach ($Addresses as $address) {
$address->sendNotification();
}
// and we continue in this matter
?>

The key point of that is to make your code readable - when your method names are obvious you don’t really need many comments in the code - it all seems self-explanatory.

Of corse you should still document any unexpected behaviour and quick hacks - but it’s better not to introduce them in the first place.

Leave a Comment

You must be logged in to post a comment.