Guard Block

Is there a reason we are not learning about Guard Blocks for functions specifically tied to one object? In this lecture, the perfect function would be “void LoadTask()” which provides more legible function body.

void LoadTasks()
{
     tastListSO = savedTasksObjectField.value as TaskListSO;

     if(taskListSO == null) 
          return;
    
     taskListScrollView.Clear();
     List<string> tasks = taskListSO.GetTasks();
     foreach(string task in tasks)
     {
           taskListScrollView.Add(CreateTask(task));
     }
}

In this case, it was simply the way the Gary wrote the method. Functionally, both a guard block (exiting if a condition is not satisfied) or wrapping functionality in an if statement block (executing code only if a condition is satisfied) are interchangeable. In a case like this, which pattern you use is a matter of personal preference.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms