code_junkie

Best Practices for Performing Sequential Operations

Nov 11th, 2011
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. try {
  2. if (!SendEmail()) {
  3. throw "Could not send e-mail";
  4. }
  5.  
  6. if (!ArchiveReportsInDatabase()) {
  7. throw "Could not archive reports in database";
  8. }
  9.  
  10. if (!CreateAFile()) {
  11. throw "Could not create file";
  12. }
  13.  
  14. ...
  15.  
  16. } catch (Exception) {
  17. LogError(Exception);
  18. ...
  19. }
  20.  
  21. try {
  22. SendEmail();
  23. ArchiveReportsInDatabase();
  24. CreateAFile();
  25. ...
  26.  
  27. } catch (Exception) {
  28. LogError(Exception);
  29. ...
  30. }
  31.  
  32. class Compensator {
  33. Action Action { get; set; }
  34. Action Compensate { get; set; }
  35. }
  36.  
  37. Queue<Compensator> actions = new Queue<Compensator>(new Compensator[] {
  38. new Compensator(SendEmail, UndoSendEmail),
  39. new Compensator(ArchiveReportsInDatabase, UndoArchiveReportsInDatabase),
  40. new Compensator(CreateAFile, UndoCreateAFile)
  41. });
  42.  
  43. Queue<Compensator> doneActions = new Queue<Compensator>();
  44. while (var c = actions.Dequeue() != null) {
  45. try {
  46. c.Action();
  47. doneActions.Add(c);
  48. } catch {
  49. try {
  50. doneActions.Each(d => d.Compensate());
  51. } catch (EXception ex) {
  52. throw new OhCrapException("Couldn't rollback", doneActions, ex);
  53. }
  54. throw;
  55. }
  56. }
  57.  
  58. try {
  59. task1();
  60. task2();
  61. task3();
  62. ...
  63. taskN();
  64. }
  65. catch (TaskFailureException e) {
  66. dealWith(e);
  67. }
  68.  
  69. try:
  70. SendEmail()
  71. try:
  72. ArchiveReportsInDatabase()
  73. try:
  74. CreateAFile()
  75. except:
  76. UndoArchiveReportsInDatabase()
  77. raise
  78. except:
  79. UndoSendEmail()
  80. raise
  81. except:
  82. // handle failure
  83.  
  84. SendEmail () {
  85. # ...
  86. }
  87. ArchiveReportsInDatabase () {
  88. # ...
  89. }
  90. CreateAFile () {
  91. # ...
  92. }
  93.  
  94. SendEmail && ArchiveReportsInDatabase && CreateAFile
  95.  
  96. return SendEmail() && ArchiveResportsInDatabase() && CreateAFile();
Add Comment
Please, Sign In to add comment