Get the latest tech news
Parse, Don’t Validate – Some C Safety Tips
“A good programmer is someone who looks both ways before crossing a one-way street.” – Doug Linder If you’ve read the original post on “Parse, Don’t Validate” you may have noticed that it focuses primarily on conceptual correctness. Here, I’ll build on that by showing how this technique can be used outside of niche academic languages by demonstrating it in a language that is as practical as it is dangerous - C.
Sure, it isn’t as enforceable as (for example) Rust… and, sure, if you are willing to do extra work you can bypass it, but, at the end of the day, the compiler will still warn you if you try to add a number to a string and assign the result to a function. By leveraging the typing guarantees in C, you can ensure that the system won’t compile even if some heretic decides that they want to pass a char * to a function expecting an email_t. With Parse, Don’t Validate, you will never run into the situation of accidentally swapping parameters around in a function call, because the compiler will error out even though those two types are identical under the hood!
Or read this on Hacker News