From the course: Refactoring with GitHub Copilot

Optimizing conditionals and loops - Github Copilot Tutorial

From the course: Refactoring with GitHub Copilot

Optimizing conditionals and loops

Two areas ripe for refactoring are conditionals and loops. And, of course, Copilot can help guide the way. Here's an example of a function that calculates a discount. Some initial thoughts on line 4, 16, and 22, it's checking the customer type. Could that logic be related to customer type, specific functions? Actually, slowing down a bit. This is three levels deep. And yikes, the isHoliday bool causes that, but it's also checked quite a few times, six, 12, 18, 20, 23. I have opinions on how to refactor this function, and I'm sure you do as well. I'm going to see what Copilot thinks. Refactor the conditionals. When I was writing this course, I tested and Copilot completely dropped logic around the VIP customer post type. Let's see if it does that again. Yes, interesting. It suggests the regular and premium and creates wrapper functions, which seems logical, but VIP is gone again. Maybe instead of asking for a refactor, I should ask to simplify it. Copilot does like switch statements. Let's see if that's what it comes up with. Yes. Finally, I'll ask, are there other ways to simplify this? And this is interesting. This results in a discount rates object that has customer types and high and low pricing based on if there's holiday. One other common area to refactor is conditionals with multiple conditions. This is a super simple example. If the user is logged in and user is admin. In your head, I want you to see this as two nested conditionals like this. That's a good way to identify how complex a conditional is and whether or not to refactor. Also, a simple sample here. If I highlight this and I ask Copilot, I'm just going to say simplify. And it goes back to the version that I had previously. Moving on to loops. All right. This function generates a CSV from a very ugly array. Before I go on with this, I want to flag that to build the CSV, all of the data will need to be accessed. So refactoring isn't actually going to eliminate loops, it's going to make it easier to understand. I'll ask, how would I simplify this so it is not three nested loops? In testing, I had to explicitly say, I do not want to see three nested foreach loops, and then Copilot created some helper function's foreach loops. I do not want to see three nested foreach. And it still doesn't really get it. So here's what I recommend: if possible, limit each function or method to one loop, even if that means calling a helper function. The benefit is traceability and the ability to surgically fix and refactor going forward. Copilot will cover just the basics of refactoring conditionals and loops. You will likely be able to take it quite a bit further.

Contents