I’ve discussed lately with one fellow a example of code where person uses nesting of arrays. And we started to discuss about use of nested arrays in code in general.
When we pass parameters to generators etc. it’s sometimes easier to use nested arrays. I think this is ok to use nested arrays in these situations but it’s better to use classes and good validation.
And second is that when we have XML, HTML, JSON or other parser they often return nested arrays also. I think that it’s also ok to use nested arrays in these scenarios.
So when it’s not ok to use nested arrays?
I think that it’s when we use them with no connection with above scenarios. Especially when we use hardcoded nested arrays in source code like in this example:
$data = array(array('cat', 12),
array('dog', 15),
array('turtle', 4));
I think that this can be cansidered as a like-to-be antipattern of programming when you use nested arrays hardcoded often. You have no validation, messed code, likely to have bugs. And my fellow is not like this and tells that it’s not antipattern, because it’s ok to use nested arrays in programming and no reason to tell other that’s not ok.
Could you please help us decide if it can be treated like a antipattern to use hardcoded nested arrays or not?
All pros and cons would be apprieciated!
It depends.
There are situations where nested arrays fit well. There are other situations where you don’t want to explicitly create an object, and it will be quicker and shorter to use nested arrays.
Of course, by using arrays instead of objects, the meaning of the array items is lost. In your example, someone who reads the code has no idea if the second item in a nested array is an age of an animal, or maybe its weight, or an identifier of the pet’s owner from a database. On the other hand, if you provide an array of objects like this:
the meaning of the second item becomes much easier to understand.
This does not mean that “validation” will be easier to do, but it’s rather the problem with the language. For example, nothing forbids to do:
Nested arrays can be a bad thing in strongly typed languages. For example, in C#, having
Collection<object>is probably not a best thing to do: you don’t know what are the properties of each object, what are those objects, etc. When you haveCollection<Animal>:Animal.Animalhas a propertyAgeof typeint, you know that every item in a collection has this property, and its value is an integer. (Note: separate items may have additional properties, ifAnimalobject is inherited by another objects which extend it, but in all cases,Ageproperty will be available).The same thing does work only partially in PHP. For example, you cannot be sure that the type of the same property is always the same among objects in the array, thus validation is required.
My personal opinion: in languages like PHP, I would rather use nested arrays when it’s quicker and easier to use nested arrays, and objects when there is a reason to use objects.