0

I know there are countless ways to implement either adding or subtracting based on a flag and I have listed three of them. My last example is the most concise, however, I was surprised I didn't come up with a more semantic approach. If "best" is defined by being the most concise, intuitive and readable, what is the best approach to do this?

public function fromDaySeconds(bool $add=true):int
{
    if ($add) {
        return $this->getTimestamp() + $this->getDay()->getTimestamp();
    }
    else {
        return $this->getTimestamp() - $this->getDay()->getTimestamp();
    }
}

public function fromDaySeconds(bool $add=true):int
{
    return $add
    ?$this->getTimestamp() + $this->getDay()->getTimestamp()
    :$this->getTimestamp() - $this->getDay()->getTimestamp();
}

public function fromDaySeconds(bool $add=true):int
{
    return $this->getTimestamp() + $this->getDay()->getTimestamp()*($add?1:-1);
}
user1032531
  • 24,767
  • 68
  • 217
  • 387
  • The last is the most difficult to read - and this is where it becomes difficult to provide a *correct* answer (IMHO) – Nigel Ren Jan 25 '20 at 15:12
  • @NigelRen I agree with you regarding the last being the most difficult to read, and wanted to make sure I am not missing some other approach. – user1032531 Jan 25 '20 at 15:21
  • IMO the function name is hard to understand you are returning a number and it does two thing add or retreive so SRP is not respected in my opinion you should have two functions (a , b) and based on that flag call the right fonction so this gives flexibilty and not link the function to a flag but the flag decide wich one to call – Youssef Saoubou Jan 25 '20 at 16:51
  • @YoussefSaoubou And also agree with you. Before even posting this question, I decided to handle this differently (method at end of comment). Was still curious why I couldn't find cleaner approach to posted question. Maybe no use as you say? Thanks. `public function fromDaySeconds(bool $previous=true):int {return $this->getTimestamp() + $this->getDay($previous)->getTimestamp();}` – user1032531 Jan 25 '20 at 18:48

0 Answers0