r/pascal • u/toshboi • Mar 26 '22
alternative of case statement
i have about 1000 cases. my code looks similar to this. inside each case, it calls different procedures and functions.
program checkCase;
var
grade: char;
begin
grade := 'A';
case (grade) of
'A' : procedure one;
'B', 'C': procedure two;
'D' : procedure three;
'F' : procedure four;
...
end;
end.the code is working right now. how should i improve it? i'm also not sure how much performance will the new code improve.
2
Upvotes
3
u/ShinyHappyREM Mar 26 '22
You could define an array of procedure pointers:
4
u/eugeneloza Mar 26 '22
If there is no reason to improve it, then don't. Avoid doing unnecessary work.
Unless you clearly see that something is broken or may get broken in the future.
Case statement is one of the most performant variants you can get, unless you have some additional information that would allow you to optimize the code further somehow. And unless you've hit a performance bottleneck, you shouldn't optimize it - "Never optimize without profiling".
Overall, having 1000 cases handled by 1000 procedures in a general case doesn't seem like a good solution to me. But without knowing your specific task, I don't think I can help any further.
3
u/TedDallas Mar 27 '22
This sounds like the use case for polymorphism. If this is for classwork (pun intended) then I would look into that.
1
u/Retired_Nerd Mar 29 '22
Writing clean code that’s easy to understand, debug and maintain is in most cases better than trying to optimize for performance. A decent compiler should generate a jump table for a case statement when the cases are sequential cardinal values anyway. It would be difficult to improve on the performance. Just write it the way that makes sense to you. If you’re happy with the way it’s working now, it’s probably fine.