1

Which solution is most logical? The value can be null, but when not null it must be a string.

This (First):

function setValue(string $value = null);

To me this is bad; since we can now call the method without anything:

$dependency->setValue(): 

Or this (Second)?

function setValue($value)
{
    if(is_string($value) OR $value == null)
    {
        //allow value
    } else {
        //throw error
    }
}

Or this (Third)?

function setValue(string $value)
{
    $this->value = $value;
}

//client
function client()
{
    $value = "test";
    if($value)
    {
        $this->dependency->setValue($value);
    }
}

This solution does not allow null to be set.

I prefer the Second solution. To only downside is the interface does not clearly show what values are accepted.

4

With PHP 7.1 it's actually quite simple:

public function setValue(?string $value)
{
    $this->value = $value;
}

or when you want it to default to null when calling it $object->setValue();

public function setValue(string $value = null)
{
    $this->value = $value;
}
1

To my mind, all of your solutions suffer the same problem: you are using one method for two purposes: set a value and reset a value to null.

So have two distinct methods to achieve these two things:

function setValue(string $value)
{
    $this->value = $value;
}

function resetValueToNull()
{
    $this->value = null;
}
-1

What's the function of a setter? To set a value, correct? Then the simplest thing that can possibly work is this:

function setValue(string $value)
{
    $this->value = $value
}

If it is an error for $value to be null, then simply do a null check:

function setValue(string $value)
{
    if ($value == null)
    {
        // throw error
    }

    $this->value = $value;
}

Anything more than that is unnecessarily complicated. You have to decide, based on the design work that you've done, whether null is an acceptable value. If it is not, check for it. You also have to decide, based on your design, what type $value is, and only accept that type. If you need to, you can provide conversion functions for convenience.

This is what is known as the Single Responsibility Principle (SRP). Because the null check (if necessary) is included in the setter, you don't have to duplicate that logic all over your code. (that's a bad thing).

  • Any reason for the downvote? I'm not wrong. – Berin Loritsch Jul 9 '18 at 13:15
  • The code I provided is PHP, where it is not possible to set null, when the method asks for a string. If not PHP, but Java, I probably would not have a problem I guess. – Stefan Jul 9 '18 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.