Cleanest way to write retry logic?

前端 未结 29 3131
旧巷少年郎
旧巷少年郎 2020-11-22 03:01

Occasionally I have a need to retry an operation several times before giving up. My code is like:

int retries = 3;
while(true) {
  try {
    DoSomething();
         


        
29条回答
  •  萌比男神i
    2020-11-22 03:17

    Or how about doing it a bit neater....

    int retries = 3;
    while (retries > 0)
    {
      if (DoSomething())
      {
        retries = 0;
      }
      else
      {
        retries--;
      }
    }
    

    I believe throwing exceptions should generally be avoided as a mechanism unless your a passing them between boundaries (such as building a library other people can use). Why not just have the DoSomething() command return true if it was successful and false otherwise?

    EDIT: And this can be encapsulated inside a function like others have suggested as well. Only problem is if you are not writing the DoSomething() function yourself

提交回复
热议问题