Let’s say you have a JSON file with an array of IP address strings, and you want to reload this file every 3 seconds, and then doSomething with every IP that’s new. And in case the file doesn’t exist, or contains invalid JSON, you want to retry in 3 seconds as well: Contrived example: The code above should get the job done, but it’s a little annoying that we need to repeat the sleep statement all over the place. So here is a pattern I’ve started to use in situations like this as of late, I’m calling it the “ ”: sleepy for loop I’m probably not the first one to (ab)use the post statement of a for loop like this, but I haven’t seen this pattern used much before, so I’m sharing it in the hope it will be interesting and useful to some of you out there. With some small modifications, it can also be used for finite loops. E.g. if we just wanted to load our IPs once, with 2 retries on error: Anyway, even though I’m quite happy with the , the same code can obviously be written without it as well. In fact my co-worker wasn’t a fan of it this morning, so we ended up settling for something like this: sleepy for loop I definitely prefer the , but I don’t feel strongly enough about it to recommend forcing it on people who think it’s weird :). sleepy for loop Anyway what do you think? Please share your feedback and alternative ideas. is how hackers start their afternoons. We’re a part of the family. We are now and happy to opportunities. Hacker Noon @AMI accepting submissions discuss advertising & sponsorship To learn more, , , or simply, read our about page like/message us on Facebook tweet/DM @HackerNoon. If you enjoyed this story, we recommend reading our and . Until next time, don’t take the realities of the world for granted! latest tech stories trending tech stories
Share Your Thoughts