I am wondering how are you guys handling an optional class properties.
Let’s say I have a product that can bud doesn’t have to have a color
property. Is that really the best way of doing that? Should I use null object pattern? Should I use strategy pattern maybe? Should I maybe use a decorator pattern here so I’ll have Product
and ProductWithColor
? What if another property will be added and become optional?
<?php
class Product
{
private $id;
private $title;
/**
* @var string|null
*/
private $color;
function __construct($id, $title, array $color = null)
{
$this->id = $id;
$this->title = $title;
$this->color = $color;
}
}
3
What if another property will be added and become optional?
I have done precisely this when I needed to inject some new functionality into that method. This does not break existing code; you gotta love that! In my case I bypass the new thing if the parameter is null.
I generally prefer to use a more meaningfully named value/enum. For example, “Unassigned/Unknown/NotSet”.
I strongly disagree with this (quote from a comment). Doing this with a string is a big hassle – typos, casing, lack of type checking (I do C#). However if this was an enum
then absolutely, have a “undefined” enum value (in C# I would have this correspond to zero because that’s the default for enums).
Should I use null object pattern?
Not exactly. We’re dealing with a single property, but the idea is the same. Make the optional/default method parameters behave benignly. For example, I set my optional string parameters to string.Empty
(C#) so calling members on it does not blow up.
Should I use strategy pattern maybe? Should I maybe …
No. Strategy is for polymorphic behavior – i.e. functions/methods with the same parameters (signature) on different types.
Optional parameters is a technique for creating concise method overloads.
I’ll have Product and ProductWithColor
Well, if your design calls for that but I suspect not. Why are you letting a single optional parameter for a single function drive your design? null
has “special handling required”, sure, but so would any property with any value that had special meaning. Here it is just a mechanism for allowing client code to ignore color for the call. How is this a whole different class?
4