Looping code or recursive method calling?
I am working on project where we have to work out delivery times based on rules in the database. The same day can have a few possibilities (same day deliveries) but also Fridays, Saturdays don't have rules so we have to look ahead and find the Monday rule.
Sorry for long winded explanation ...
To add to complexity we also calculate when the item can be collected at the delivery point so we calculate the pick up time based on AM / PM guarantees and make sure the place is open and its not holiday...
When I initially wrote up the logic I made a method that takes a date and calculates all these values and returns our Calculated Model. Just before the end I put in a test to make sure the model is populated otherwise there was no match made for that date and time and I increment the day by 1 and call my method again, with the incremented datetime and the rule until I hit the return and everything bubbles back to the original stack call. For me that worked like a charm, single level if statements and no complicated and and or's
Basically that code was shot down because other test and bug developers did not understand how to debug it, or what it was doing.
The new proposal is a single method that does the same thing but enclosed in a while statement until the condition is met. Then within the while there is a foreach that validates the deliveries can be met and a line of conditional if and nested conditional or's and then returns the Calculated model.
Is it bad to recall the same method from within it self until the ultimate condition is met with adjusted values?
Both code fragments work fine I just find having nested for each in while and conditionals if more difficult to decipher than a flat set of rules.
Although recursion can lead to some elegant solutions it can also lead to difficult to follow code and stack overflows, as each recursive calls allocates a new stack frame. By default each thread has a 1MB stack, so it doesn't take long to run out of space.
Tail recursion can fix this, as long as your actually doing a tail recursive call, and the compiler can spot this. At the IL level there is support for tail recursion with the TailCall instruction, but the C# compiler doesn't generate code that uses it.
链接地址: http://www.djcxy.com/p/80624.html上一篇: 这些变量是垃圾吗?
下一篇: 循环代码或递归方法调用?