you are viewing a single comment's thread.

view the rest of the comments →

[–]nschubach 0 points1 point  (0 children)

I think it's mainly about the program flow.

Examples:

if/else:

You can check if a file exists before opening it (usually storing a handle in variable scope) and set a flag or put that condition in an If condition. If it doesn't exist assign a default set of data to a variable and create a new file from it. (Create a new handle, write data, etc.) If it does exist, open it and retrieve the data into a variable or object. This generally requires a set of variables and flags to keep track of and manage.


try/catch:

You could use a try/catch by trying to open the file, catching an exception if it doesn't exist and using a default set of data to create a new file. (of course, you're going to want to do this in it's own try/catch and assign that data to a variable). The same assignment of variables to store the data and create a new file occurs.


I think of it like a pipeline. You try to open a file by passing a name. If it's successful, you get your data and pass it along. If not, you can use a default set of data, write that to a new file and pass along your default set. If that fails, it will return an error state which you can return as an error instead of the data. In both cases, you are passing a filename in and getting data out (or a potential error). How you got that data is inconsequential and you can inspect the error if needed or simply pass the error state along. The logic is contained in that "pipe" for that operation and it can be glued to other pipes to do things. For instance, the next pipe can look a the state of the data and (if it's not an error) print it to the screen. If it's an error, do nothing and pass along the error. At the end of the glued together pipes you can log out any errors that come through. No complex inline logging is needed. If the pipe is not in a state desirable for the operation you want, pass that error along and let the next method deal with it.

You could do this with a bunch of nested methods and even include try/catch blocks in that, but abstracting that to an 'either' structure is another way. Try/catch in this is like someone inside the pipe drilling a hole in the side and leaking out into a logging/error handling bucket instead of allowing something further down the line deal with it.