php Laravel - given a certain argument, call different function

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












I am building a simple calendar with recurring events.



CalendarEvent.php



id
start_date


CalendarRecurringPattern.php



parent_id
pattern_type // daily, weekly, monthly, yearly ...


Using pattern_type i build each following occurrence starting from start_date, using a recursive function and Carbon::class. What bugs me is the function getNextOccurrence(), I'd like to refactor the if/else block because it's not very clean. Here it is:




use CarbonCarbon;
....

public function getNextOccurrence(Carbon $startDate)

$pattern_type = $this->getPatternType() // daily, weekly...

if ($pattern_type == 'daily')
$startDate->addDay();
else if ($pattern_type == 'weekly')
$startDate->addWeek();
else if ($pattern_type == 'monthly')
$startDate->addMonth();
else if ($pattern_type == 'yearly')
$startDate->addYear();





Thanks!







share|improve this question















  • 2




    the commonplace suggestion would be to use switch, but honestly I don't see what's wrong with a lot of nested if statements. Once I was eager to refactor this kind of code, but now I learned to value its verbosity and clean meaning, so I wouldn't change it into something more "elegant" but less readable
    – Your Common Sense
    Jun 20 at 13:04











  • Thanks. I'm still growing as a developer and I'm doing my best to avoid bad habits. Recently I have been reading a lot about unit testing, a field in which I have no experience, and that function seemed not very clean from a testing perspective.
    – Enrico
    Jun 20 at 15:01
















up vote
2
down vote

favorite












I am building a simple calendar with recurring events.



CalendarEvent.php



id
start_date


CalendarRecurringPattern.php



parent_id
pattern_type // daily, weekly, monthly, yearly ...


Using pattern_type i build each following occurrence starting from start_date, using a recursive function and Carbon::class. What bugs me is the function getNextOccurrence(), I'd like to refactor the if/else block because it's not very clean. Here it is:




use CarbonCarbon;
....

public function getNextOccurrence(Carbon $startDate)

$pattern_type = $this->getPatternType() // daily, weekly...

if ($pattern_type == 'daily')
$startDate->addDay();
else if ($pattern_type == 'weekly')
$startDate->addWeek();
else if ($pattern_type == 'monthly')
$startDate->addMonth();
else if ($pattern_type == 'yearly')
$startDate->addYear();





Thanks!







share|improve this question















  • 2




    the commonplace suggestion would be to use switch, but honestly I don't see what's wrong with a lot of nested if statements. Once I was eager to refactor this kind of code, but now I learned to value its verbosity and clean meaning, so I wouldn't change it into something more "elegant" but less readable
    – Your Common Sense
    Jun 20 at 13:04











  • Thanks. I'm still growing as a developer and I'm doing my best to avoid bad habits. Recently I have been reading a lot about unit testing, a field in which I have no experience, and that function seemed not very clean from a testing perspective.
    – Enrico
    Jun 20 at 15:01












up vote
2
down vote

favorite









up vote
2
down vote

favorite











I am building a simple calendar with recurring events.



CalendarEvent.php



id
start_date


CalendarRecurringPattern.php



parent_id
pattern_type // daily, weekly, monthly, yearly ...


Using pattern_type i build each following occurrence starting from start_date, using a recursive function and Carbon::class. What bugs me is the function getNextOccurrence(), I'd like to refactor the if/else block because it's not very clean. Here it is:




use CarbonCarbon;
....

public function getNextOccurrence(Carbon $startDate)

$pattern_type = $this->getPatternType() // daily, weekly...

if ($pattern_type == 'daily')
$startDate->addDay();
else if ($pattern_type == 'weekly')
$startDate->addWeek();
else if ($pattern_type == 'monthly')
$startDate->addMonth();
else if ($pattern_type == 'yearly')
$startDate->addYear();





Thanks!







share|improve this question











I am building a simple calendar with recurring events.



CalendarEvent.php



id
start_date


CalendarRecurringPattern.php



parent_id
pattern_type // daily, weekly, monthly, yearly ...


Using pattern_type i build each following occurrence starting from start_date, using a recursive function and Carbon::class. What bugs me is the function getNextOccurrence(), I'd like to refactor the if/else block because it's not very clean. Here it is:




use CarbonCarbon;
....

public function getNextOccurrence(Carbon $startDate)

$pattern_type = $this->getPatternType() // daily, weekly...

if ($pattern_type == 'daily')
$startDate->addDay();
else if ($pattern_type == 'weekly')
$startDate->addWeek();
else if ($pattern_type == 'monthly')
$startDate->addMonth();
else if ($pattern_type == 'yearly')
$startDate->addYear();





Thanks!









share|improve this question










share|improve this question




share|improve this question









asked Jun 20 at 12:40









Enrico

1134




1134







  • 2




    the commonplace suggestion would be to use switch, but honestly I don't see what's wrong with a lot of nested if statements. Once I was eager to refactor this kind of code, but now I learned to value its verbosity and clean meaning, so I wouldn't change it into something more "elegant" but less readable
    – Your Common Sense
    Jun 20 at 13:04











  • Thanks. I'm still growing as a developer and I'm doing my best to avoid bad habits. Recently I have been reading a lot about unit testing, a field in which I have no experience, and that function seemed not very clean from a testing perspective.
    – Enrico
    Jun 20 at 15:01












  • 2




    the commonplace suggestion would be to use switch, but honestly I don't see what's wrong with a lot of nested if statements. Once I was eager to refactor this kind of code, but now I learned to value its verbosity and clean meaning, so I wouldn't change it into something more "elegant" but less readable
    – Your Common Sense
    Jun 20 at 13:04











  • Thanks. I'm still growing as a developer and I'm doing my best to avoid bad habits. Recently I have been reading a lot about unit testing, a field in which I have no experience, and that function seemed not very clean from a testing perspective.
    – Enrico
    Jun 20 at 15:01







2




2




the commonplace suggestion would be to use switch, but honestly I don't see what's wrong with a lot of nested if statements. Once I was eager to refactor this kind of code, but now I learned to value its verbosity and clean meaning, so I wouldn't change it into something more "elegant" but less readable
– Your Common Sense
Jun 20 at 13:04





the commonplace suggestion would be to use switch, but honestly I don't see what's wrong with a lot of nested if statements. Once I was eager to refactor this kind of code, but now I learned to value its verbosity and clean meaning, so I wouldn't change it into something more "elegant" but less readable
– Your Common Sense
Jun 20 at 13:04













Thanks. I'm still growing as a developer and I'm doing my best to avoid bad habits. Recently I have been reading a lot about unit testing, a field in which I have no experience, and that function seemed not very clean from a testing perspective.
– Enrico
Jun 20 at 15:01




Thanks. I'm still growing as a developer and I'm doing my best to avoid bad habits. Recently I have been reading a lot about unit testing, a field in which I have no experience, and that function seemed not very clean from a testing perspective.
– Enrico
Jun 20 at 15:01










1 Answer
1






active

oldest

votes

















up vote
3
down vote



accepted










I don't personally see a problem with the way its currently structured as there aren't that many options, but you could do it a couple of other ways;



Option 1



Array function name mapping (hacky name I just came up with), you could do the following;



$functionMap = [
"daily" => "addDay",
"weekly" => "addWeek",
"monthly" => "addMonth",
"yearly" => "addYear"
];

if(!isset($functionMap[$pattern_type]))
throw new Exception("Can't find patern type $pattern_type", 1);


$startDate->$functionMap[$pattern_type]();


This might be seen as a sin by the PHP community but it works none the less



Option 2



You could use a switch which probably isn't a sin by the community.



switch ($pattern_type) 
case "daily":
// Do the daily task
break;
case "weekly":
// Do the weekly task
break;
case "monthly":
// Do the monthly task
break;
case "yearly":
// Do the yearly task
break;
default:
throw new Exception("Can't find pattern type $pattern_type", 1);



Conclusion



I would add some exception / error that can be picked up if a non matched pattern_type is passed.



I would also convert the "magic strings" E.G "daily" to constants in case you need to re-use, change or update them in the future!



In terms of line count;



  • your way 10 lines of code

  • option 1 11 lines of code

  • option 2 15 lines of code

The switch & if statements may have some advantages when doing code analysis aswel where the expected required input values can be picked up.






share|improve this answer





















  • Thanks for this. I'm wondering, why should the option n.1 be seen as a sin by the community? I find myself using the same concept many times with javascript.
    – Enrico
    Jun 20 at 15:04






  • 1




    For example unit testing, unit testing would show this code as 100% tested even if you only tested one $pattern_type because there is only one path the code can take
    – Dan
    Jun 20 at 17:07











  • That's interesting. Thanks!
    – Enrico
    Jun 26 at 9:01










Your Answer




StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");

StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: false,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);








 

draft saved


draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f196886%2fphp-laravel-given-a-certain-argument-call-different-function%23new-answer', 'question_page');

);

Post as a guest






























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
3
down vote



accepted










I don't personally see a problem with the way its currently structured as there aren't that many options, but you could do it a couple of other ways;



Option 1



Array function name mapping (hacky name I just came up with), you could do the following;



$functionMap = [
"daily" => "addDay",
"weekly" => "addWeek",
"monthly" => "addMonth",
"yearly" => "addYear"
];

if(!isset($functionMap[$pattern_type]))
throw new Exception("Can't find patern type $pattern_type", 1);


$startDate->$functionMap[$pattern_type]();


This might be seen as a sin by the PHP community but it works none the less



Option 2



You could use a switch which probably isn't a sin by the community.



switch ($pattern_type) 
case "daily":
// Do the daily task
break;
case "weekly":
// Do the weekly task
break;
case "monthly":
// Do the monthly task
break;
case "yearly":
// Do the yearly task
break;
default:
throw new Exception("Can't find pattern type $pattern_type", 1);



Conclusion



I would add some exception / error that can be picked up if a non matched pattern_type is passed.



I would also convert the "magic strings" E.G "daily" to constants in case you need to re-use, change or update them in the future!



In terms of line count;



  • your way 10 lines of code

  • option 1 11 lines of code

  • option 2 15 lines of code

The switch & if statements may have some advantages when doing code analysis aswel where the expected required input values can be picked up.






share|improve this answer





















  • Thanks for this. I'm wondering, why should the option n.1 be seen as a sin by the community? I find myself using the same concept many times with javascript.
    – Enrico
    Jun 20 at 15:04






  • 1




    For example unit testing, unit testing would show this code as 100% tested even if you only tested one $pattern_type because there is only one path the code can take
    – Dan
    Jun 20 at 17:07











  • That's interesting. Thanks!
    – Enrico
    Jun 26 at 9:01














up vote
3
down vote



accepted










I don't personally see a problem with the way its currently structured as there aren't that many options, but you could do it a couple of other ways;



Option 1



Array function name mapping (hacky name I just came up with), you could do the following;



$functionMap = [
"daily" => "addDay",
"weekly" => "addWeek",
"monthly" => "addMonth",
"yearly" => "addYear"
];

if(!isset($functionMap[$pattern_type]))
throw new Exception("Can't find patern type $pattern_type", 1);


$startDate->$functionMap[$pattern_type]();


This might be seen as a sin by the PHP community but it works none the less



Option 2



You could use a switch which probably isn't a sin by the community.



switch ($pattern_type) 
case "daily":
// Do the daily task
break;
case "weekly":
// Do the weekly task
break;
case "monthly":
// Do the monthly task
break;
case "yearly":
// Do the yearly task
break;
default:
throw new Exception("Can't find pattern type $pattern_type", 1);



Conclusion



I would add some exception / error that can be picked up if a non matched pattern_type is passed.



I would also convert the "magic strings" E.G "daily" to constants in case you need to re-use, change or update them in the future!



In terms of line count;



  • your way 10 lines of code

  • option 1 11 lines of code

  • option 2 15 lines of code

The switch & if statements may have some advantages when doing code analysis aswel where the expected required input values can be picked up.






share|improve this answer





















  • Thanks for this. I'm wondering, why should the option n.1 be seen as a sin by the community? I find myself using the same concept many times with javascript.
    – Enrico
    Jun 20 at 15:04






  • 1




    For example unit testing, unit testing would show this code as 100% tested even if you only tested one $pattern_type because there is only one path the code can take
    – Dan
    Jun 20 at 17:07











  • That's interesting. Thanks!
    – Enrico
    Jun 26 at 9:01












up vote
3
down vote



accepted







up vote
3
down vote



accepted






I don't personally see a problem with the way its currently structured as there aren't that many options, but you could do it a couple of other ways;



Option 1



Array function name mapping (hacky name I just came up with), you could do the following;



$functionMap = [
"daily" => "addDay",
"weekly" => "addWeek",
"monthly" => "addMonth",
"yearly" => "addYear"
];

if(!isset($functionMap[$pattern_type]))
throw new Exception("Can't find patern type $pattern_type", 1);


$startDate->$functionMap[$pattern_type]();


This might be seen as a sin by the PHP community but it works none the less



Option 2



You could use a switch which probably isn't a sin by the community.



switch ($pattern_type) 
case "daily":
// Do the daily task
break;
case "weekly":
// Do the weekly task
break;
case "monthly":
// Do the monthly task
break;
case "yearly":
// Do the yearly task
break;
default:
throw new Exception("Can't find pattern type $pattern_type", 1);



Conclusion



I would add some exception / error that can be picked up if a non matched pattern_type is passed.



I would also convert the "magic strings" E.G "daily" to constants in case you need to re-use, change or update them in the future!



In terms of line count;



  • your way 10 lines of code

  • option 1 11 lines of code

  • option 2 15 lines of code

The switch & if statements may have some advantages when doing code analysis aswel where the expected required input values can be picked up.






share|improve this answer













I don't personally see a problem with the way its currently structured as there aren't that many options, but you could do it a couple of other ways;



Option 1



Array function name mapping (hacky name I just came up with), you could do the following;



$functionMap = [
"daily" => "addDay",
"weekly" => "addWeek",
"monthly" => "addMonth",
"yearly" => "addYear"
];

if(!isset($functionMap[$pattern_type]))
throw new Exception("Can't find patern type $pattern_type", 1);


$startDate->$functionMap[$pattern_type]();


This might be seen as a sin by the PHP community but it works none the less



Option 2



You could use a switch which probably isn't a sin by the community.



switch ($pattern_type) 
case "daily":
// Do the daily task
break;
case "weekly":
// Do the weekly task
break;
case "monthly":
// Do the monthly task
break;
case "yearly":
// Do the yearly task
break;
default:
throw new Exception("Can't find pattern type $pattern_type", 1);



Conclusion



I would add some exception / error that can be picked up if a non matched pattern_type is passed.



I would also convert the "magic strings" E.G "daily" to constants in case you need to re-use, change or update them in the future!



In terms of line count;



  • your way 10 lines of code

  • option 1 11 lines of code

  • option 2 15 lines of code

The switch & if statements may have some advantages when doing code analysis aswel where the expected required input values can be picked up.







share|improve this answer













share|improve this answer



share|improve this answer











answered Jun 20 at 13:07









Dan

373211




373211











  • Thanks for this. I'm wondering, why should the option n.1 be seen as a sin by the community? I find myself using the same concept many times with javascript.
    – Enrico
    Jun 20 at 15:04






  • 1




    For example unit testing, unit testing would show this code as 100% tested even if you only tested one $pattern_type because there is only one path the code can take
    – Dan
    Jun 20 at 17:07











  • That's interesting. Thanks!
    – Enrico
    Jun 26 at 9:01
















  • Thanks for this. I'm wondering, why should the option n.1 be seen as a sin by the community? I find myself using the same concept many times with javascript.
    – Enrico
    Jun 20 at 15:04






  • 1




    For example unit testing, unit testing would show this code as 100% tested even if you only tested one $pattern_type because there is only one path the code can take
    – Dan
    Jun 20 at 17:07











  • That's interesting. Thanks!
    – Enrico
    Jun 26 at 9:01















Thanks for this. I'm wondering, why should the option n.1 be seen as a sin by the community? I find myself using the same concept many times with javascript.
– Enrico
Jun 20 at 15:04




Thanks for this. I'm wondering, why should the option n.1 be seen as a sin by the community? I find myself using the same concept many times with javascript.
– Enrico
Jun 20 at 15:04




1




1




For example unit testing, unit testing would show this code as 100% tested even if you only tested one $pattern_type because there is only one path the code can take
– Dan
Jun 20 at 17:07





For example unit testing, unit testing would show this code as 100% tested even if you only tested one $pattern_type because there is only one path the code can take
– Dan
Jun 20 at 17:07













That's interesting. Thanks!
– Enrico
Jun 26 at 9:01




That's interesting. Thanks!
– Enrico
Jun 26 at 9:01












 

draft saved


draft discarded


























 


draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f196886%2fphp-laravel-given-a-certain-argument-call-different-function%23new-answer', 'question_page');

);

Post as a guest













































































Popular posts from this blog

Greedy Best First Search implementation in Rust

Function to Return a JSON Like Objects Using VBA Collections and Arrays

C++11 CLH Lock Implementation