Personal computing discussed

Moderators: SecretSquirrel, just brew it!

 
derFunkenstein
Gerbil God
Topic Author
Posts: 24372
Joined: Fri Feb 21, 2003 9:13 pm
Location: Comin' to you directly from the Mothership

Re: Better to throw exceptions or return null?

Fri Mar 02, 2018 11:07 am

I really appreciate all the different responses. It looks like you can really go too far in either direction. As long as I stick to corporate convention (which I outlined earlier) I'm probably fine, and it's probably just easier for me to do that when doing homework.

This week has been especially trying (nothing to do with school, just work garbage I can't get into) and this has made me feel a little better about myself, weirdly enough. So thanks, all. :D
I do not understand what I do. For what I want to do I do not do, but what I hate I do.
 
Buub
Maximum Gerbil
Posts: 4713
Joined: Sat Nov 09, 2002 11:59 pm
Location: Seattle, WA
Contact:

Re: Better to throw exceptions or return null?

Fri Mar 02, 2018 11:22 am

SecretSquirrel wrote:
Here is another way to look at it, that lines up with what the "exceptions are exceptional" folks are getting at. If you are throwing an exception in your code, the expectation should be that the execution thread terminates. The purpose here is to log as much state and information as possible and give a good traceback, as well as to (maybe) try and clean up.

If a library you are calling throws an exception, whatever thing that library handles should be "terminated". For example, if you have a database library that throws an exception, it should be expected that you cannot cleanly close the database connection, commit transactions, etc. At that point, you should assume any attempt to access that database will fail, and/or make things worse. The library is signaling that it has encountered an situation that it cannot handle, either literally, or figurative in that the library designer cannot chose the correct recovery path and leaves it to you the application writer.

--SS

I think this may be overkill. There are certainly paradigms where this may be a workable model. But there are also very valid frameworks where exceptions simply mean something failed or an error occurred, and it can be dealt with cleanly. In fact, the C++ standard deals quite explicitly with the state of objects after things like exceptions. Leaving things in an indeterminate state is actually poor design, IMHO.
 
SecretSquirrel
Minister of Gerbil Affairs
Posts: 2362
Joined: Tue Jan 01, 2002 7:00 pm
Location: North DFW suburb...
Contact:

Re: Better to throw exceptions or return null?

Sat Mar 03, 2018 12:13 pm

Buub wrote:
SecretSquirrel wrote:
Here is another way to look at it, that lines up with what the "exceptions are exceptional" folks are getting at. If you are throwing an exception in your code, the expectation should be that the execution thread terminates. The purpose here is to log as much state and information as possible and give a good traceback, as well as to (maybe) try and clean up.

If a library you are calling throws an exception, whatever thing that library handles should be "terminated". For example, if you have a database library that throws an exception, it should be expected that you cannot cleanly close the database connection, commit transactions, etc. At that point, you should assume any attempt to access that database will fail, and/or make things worse. The library is signaling that it has encountered an situation that it cannot handle, either literally, or figurative in that the library designer cannot chose the correct recovery path and leaves it to you the application writer.

--SS

I think this may be overkill. There are certainly paradigms where this may be a workable model. But there are also very valid frameworks where exceptions simply mean something failed or an error occurred, and it can be dealt with cleanly. In fact, the C++ standard deals quite explicitly with the state of objects after things like exceptions. Leaving things in an indeterminate state is actually poor design, IMHO.


I don't disagree that leaving things in an indeterminate state is bad. I don't see exceptions as necessarily leaving indeterminate state, though they certainly can if dealing with hardware, databases, or other such things, more about indeterminate actions. And I know there are many libraries and frameworks that use exceptions for simple error handling/reporting. I happen to disagree with that paradigm. It tends to lead to lazy and/or poor programming practices, in my opinion (ALWAYS check return codes).

Fundamentally, exceptions are a more streamlined method of implementing the old C errno construct where the return code signified an error and a separate global variable was used to signify the type of error, in cases where there could be more error conditions than could be communicated in a single return variable. Exceptions also add in the implicit GOTO that is occasionally used to exit a complex block of code in case of an error -- usually to drastically reduce the number of times the same cleanup code would have to be duplicated.

A try/catch block effectively implements this C code:
ret=functiion(arg1, arg2, arg3);
if(!ret) {
  switch(errno) {
    case err1:
      goto EXIT_ERR1;
      break;
    case err2:
      goto EXIT_ERR2;
      break;
    case err3:
      goto EXIT_ERR3;
      break;
    default:
      goto EXIT_DEFAULT;
      break;
  }
}


No arguments that try/catch is cleaner than the above. However, the fact that the catch (goto target) is global in program scope is problematic from a program control flow point of view. I also come from the "GOTOs shall not be used except in exceptional circumstances camp. Like so many other things, when used by intelligent and mindful programmers, exceptions provide a useful construct to handle certain conditions in a clean manner. Unfortunately they also enable lazy programmers to write crappy code. Even more unfortunately there are way more of the latter than the former.

--SS
 
UberGerbil
Grand Admiral Gerbil
Posts: 10318
Joined: Thu Jun 19, 2003 3:11 pm

Re: Better to throw exceptions or return null?

Sun Mar 04, 2018 11:13 pm

The discussion of checked exceptions in Wikipedia might be worth a read. That's a particular kind of exception that Java provides, and few other languages do (and some that did got rid of it) -- an aspect of coding-by-contract that sounded good in theory but ended up being a pain in practice.
Kiniry also writes that "As any Java programmer knows, the volume of try catch code in a typical Java application is sometimes larger than the comparable code necessary for explicit formal parameter and return value checking in other languages that do not have checked exceptions. In fact, the general consensus among in-the-trenches Java programmers is that dealing with checked exceptions is nearly as unpleasant a task as writing documentation. Thus, many programmers report that they “resent” checked exceptions. This leads to an abundance of checked-but-ignored exceptions".

And while that applies to this particular feature in Java, the larger discussion touches on the use (and over-use) of exceptions in languages in general.

Having grown up programming before structured error handling was even a thing (I can recall running into "ONERR GOTO" for the first time in AppleSoft BASIC back in the early 80s, and having an argument about it "But GOTO is unstructured!" "But handling an arbitrary error is inherently unstructured!"), I'm both happy it exists and sometimes resentful when I'm forced to use it.

My attitude generally is that library routines should always tell you when there's a problem, but should do so in a way that you can ignore (at your peril) without convoluted code. Some language designs encourage that, some discourage it, and I tend to dislike the latter (though that constitutes a tiny part of my overall opinion of a language).
 
derFunkenstein
Gerbil God
Topic Author
Posts: 24372
Joined: Fri Feb 21, 2003 9:13 pm
Location: Comin' to you directly from the Mothership

Re: Better to throw exceptions or return null?

Sun Mar 04, 2018 11:38 pm

UberGerbil wrote:
My attitude generally is that library routines should always tell you when there's a problem, but should do so in a way that you can ignore (at your peril) without convoluted code. Some language designs encourage that, some discourage it, and I tend to dislike the latter (though that constitutes a tiny part of my overall opinion of a language).

Seems like that's exactly what I wanted to do. Like, this is a weird state to be in, but it isn't going to turn out the lights on you.

Ryhadar wrote:
Microsoft wrote:
Remarks

The First<TSource>(IEnumerable<TSource>) method throws an exception if source contains no elements. To instead return a default value when the source sequence is empty, use the FirstOrDefault<TSource> method.


For what it's worth, I almost always use .FirstOrDefault() and almost never .First(). So, if I were using your LinkedList library I'd probably prefer your convention, derFunkenstein.

As it turns out, I exclusively used FirstOrDefault. There's probably a performance penalty if nothing is found, but it's completely safe as long as you check nulls after calling it. The project I'm on uses a ton of web services (that's where all the data is exclusively) and so you can always get params in a state where you get back an empty JSON string. Calling First() is just suicide unless you try/catch it, and that's just silly. I started off calling First() when I first started on this thing, but quickly changed it everywhere when the application was crash-happy.
I do not understand what I do. For what I want to do I do not do, but what I hate I do.
 
NovusBogus
Silver subscriber
Graphmaster Gerbil
Posts: 1270
Joined: Sun Jan 06, 2013 12:37 am

Re: Better to throw exceptions or return null?

Mon Mar 05, 2018 12:23 am

Java and particularly .NET love exceptions and exception handling, so in those environments I would say that exceptions should be thrown for both unexpected/unusable results and nonsensical input that fails basic validation, e.g. asking for element -1 in a zero indexed array. It's how a function tells whatever called it that they're doing it wrong. Performance concerns in interpreted languages like these are typically limited to thread safety and avoiding obvious algorithmic pitfalls; if performance really matters they wouldn't be using an interpreted language.

C++ is a bit different given the wildly different implementations and library support, and the fact that C++ is typically what you use when you *do* care about performance. For this I'd say search the existing code base for a similar example and do whatever was done there, for consistency. Both approaches have advantages and disadvantages, highly dependent on context.
 
derFunkenstein
Gerbil God
Topic Author
Posts: 24372
Joined: Fri Feb 21, 2003 9:13 pm
Location: Comin' to you directly from the Mothership

Re: Better to throw exceptions or return null?

Mon Mar 05, 2018 7:50 am

NovusBogus wrote:
For this I'd say search the existing code base for a similar example and do whatever was done there, for consistency. Both approaches have advantages and disadvantages, highly dependent on context.

I wrote the C# project's codebase from scratch. What do I do then? :lol:
I do not understand what I do. For what I want to do I do not do, but what I hate I do.
 
FlamingSpaceJunk
Gerbil
Posts: 39
Joined: Thu Nov 09, 2017 4:21 pm

Re: Better to throw exceptions or return null?

Mon Mar 05, 2018 10:08 pm

derFunkenstein wrote:
NovusBogus wrote:
For this I'd say search the existing code base for a similar example and do whatever was done there, for consistency. Both approaches have advantages and disadvantages, highly dependent on context.

I wrote the C# project's codebase from scratch. What do I do then? :lol:


Decide if you're going to camp in the fail quickly space or the fail gracefully space. :) If you're going to fail quickly, set asserts and throw exceptions. Otherwise, set checks and handle things. Each has their place. It just depends on the situation. If you're writing a service which spawns lots of processes, let the process die quickly, and the client can deal with resending the data. If you're writing a client facing application, it probably shouldn't abort at the slightest problem.

Really, if it's your own code, you should be able to handle any problems, and exceptions should only be thrown when accessing external resources, dealing with external input, or executing potentially dangerous operations (Anything where a lock, semaphore, or mutex should be set, but it isn't going to happen for various reasons).
 
derFunkenstein
Gerbil God
Topic Author
Posts: 24372
Joined: Fri Feb 21, 2003 9:13 pm
Location: Comin' to you directly from the Mothership

Re: Better to throw exceptions or return null?

Mon Mar 05, 2018 10:30 pm

FlamingSpaceJunk wrote:
Really, if it's your own code, you should be able to handle any problems, and exceptions should only be thrown when accessing external resources, dealing with external input, or executing potentially dangerous operations (Anything where a lock, semaphore, or mutex should be set, but it isn't going to happen for various reasons).

I decided early on that the app should absolutely not ever crash. So I handle null checks everywhere and show messages - we're already supposed to show a message when there's nothing to display on a screen and it made zero sense to n00b me to throw up an alert in a try/catch block. Much better to look and see if there's any data in the first place.

And that's why, more or less, the only try/catch blocks anywhere are network access, local storage access, SQLite read/write, and certain NuGet packages that will throw exceptions, like serialization/deserialization with JSON.NET.
I do not understand what I do. For what I want to do I do not do, but what I hate I do.
 
NovusBogus
Silver subscriber
Graphmaster Gerbil
Posts: 1270
Joined: Sun Jan 06, 2013 12:37 am

Re: Better to throw exceptions or return null?

Tue Mar 06, 2018 10:13 pm

derFunkenstein wrote:
NovusBogus wrote:
For this I'd say search the existing code base for a similar example and do whatever was done there, for consistency. Both approaches have advantages and disadvantages, highly dependent on context.

I wrote the C# project's codebase from scratch. What do I do then? :lol:


NovusBogus wrote:
Java and particularly .NET love exceptions and exception handling, so in those environments I would say that exceptions should be thrown for both unexpected/unusable results and nonsensical input that fails basic validation


^that :)

You typically want to fail gracefully at the top levels of the application, and fail explicitly and decisively further down in the function calls and libraries. Otherwise what happens is that each layer of the application starts creatively interpreting the results of its function calls ("We got back -1, but is that the error-code -1 or the integer -1? And if it's an error code, which of the 93 error code enums are we supposed to look it up in? Better check the phases of the moon for guidance!") and everything goes to hell in a handbasket when someone tries to add new functionality to one of those functions in the future. I work with an extreme example of such a code base right now, and it is not pretty. Hilarious, in a Gilbert Gottfried dead baby comedy kind of way, but not pretty.

Incidentally, if you're not already doing it I suggest that you always separate your UI code and 'core' logic into separate classes and code files. Separating a software application into distinct layers like this is common practice in industry, and one of those things I wish I'd gotten into the habit of when I was still learning basic coding techniques.
 
derFunkenstein
Gerbil God
Topic Author
Posts: 24372
Joined: Fri Feb 21, 2003 9:13 pm
Location: Comin' to you directly from the Mothership

Re: Better to throw exceptions or return null?

Tue Mar 06, 2018 11:13 pm

NovusBogus wrote:
You typically want to fail gracefully at the top levels of the application, and fail explicitly and decisively further down in the function calls and libraries. Otherwise what happens is that each layer of the application starts creatively interpreting the results of its function calls ("We got back -1, but is that the error-code -1 or the integer -1? And if it's an error code, which of the 93 error code enums are we supposed to look it up in? Better check the phases of the moon for guidance!") and everything goes to hell in a handbasket when someone tries to add new functionality to one of those functions in the future. I work with an extreme example of such a code base right now, and it is not pretty. Hilarious, in a Gilbert Gottfried dead baby comedy kind of way, but not pretty.

This particular project is all top levels. It's a phone app that uses a bunch of web services to get data. Sometimes the web services will return empty JSON. I trap those exceptions and log them when they get deserialized, but otherwise everything I'm doing right now is user interface. This is probably kid's stuff compared to what most people here are writing, but it's putting food on the table. :D

NovusBogus wrote:
Incidentally, if you're not already doing it I suggest that you always separate your UI code and 'core' logic into separate classes and code files. Separating a software application into distinct layers like this is common practice in industry, and one of those things I wish I'd gotten into the habit of when I was still learning basic coding techniques.

Definitely. It loosely uses MVVM as the design pattern, but there are other (organized) bits of business logic stored outside of the ViewModels, too, like a web services class that handles all the network access, for example. The VMs are all plain ol' CRL objects that know nothing about the page, just what to feed it.
I do not understand what I do. For what I want to do I do not do, but what I hate I do.
 
NovusBogus
Silver subscriber
Graphmaster Gerbil
Posts: 1270
Joined: Sun Jan 06, 2013 12:37 am

Re: Better to throw exceptions or return null?

Tue Mar 06, 2018 11:20 pm

So what I would do for your linked list program, if it was me doing it, is set the project up as follows (assuming C# but Java would look similar with different extensions):

MyLittleProject (top level solution/project/whatever stuff)
MyLittleProject/ui (directory)
MyLIttleProject/ui/WpfApplicationForm1.cs (WPF, Winform, console, whatever--this is your frontend code)
MyLittleProject/ProgramMain.cs (main program that loads values and does stuff--UI makes calls into this thing)
MyLittleProject/lib (directory)
MyLittleProject/lib/LinkedList.cs (linked list class--ProgramMain instantiates one or more of them and does whatever with them)

LinkedList functions would always throw exceptions for failed validation and whatnot. This is just a class function call, and its caller is as a rule going to be better informed and equipped to make decisions on a bad return than the function. The caller has to try-catch anyway because it has no way of knowing whether LinkedList is in turn making calls into the standard libraries that could return all sorts of goofy exceptions that don't get handled by the LinkedList function. This is the gist of object oriented encapsulation: something that calls something else doesn't know or care what happens inside that function, only that its inputs and outputs are well defined and highly deterministic. The code is also totally reusable by doing this, indeed whatever class you're taking will probably try to bring linked list into another assignment.

ProgramMain would try-catchy the calls to LinkedList and just about anything else that goes beyond its own class members. This could be in the form of try-catching just the call(s) itself, or putting one around the whole function with generic error handling at the end to fail gracefully and log it, send it up to the UI layer, whatever. The latter approach is what I've seen the most of in both Java(script) and C# code because it's cheap and reasonably well informed on what to do in case of failure. Remember that not all program fails are bad: user actions should be kept safe but mistakes or misunderstandings on the coder's part should yield useful, descriptive debugging information. For real software projects this normally includes writing your own custom exception classes, but that's far beyond the scope of a simple college project.

WpfApplicationForm1.cs contains very little code, and just passes stuff down to ProgramMain.cs. This way I can chop off the UI and replace it with something else, like a web service, and not have to redo a bunch of system code. Plus mixing UI and system behavior never ends well, because one starts to rely too much on the other.
 
derFunkenstein
Gerbil God
Topic Author
Posts: 24372
Joined: Fri Feb 21, 2003 9:13 pm
Location: Comin' to you directly from the Mothership

Re: Better to throw exceptions or return null?

Wed Mar 07, 2018 12:24 pm

It's probably too late for me to change lanes mid-stream, but this guide (plus read-only access to some code from another team doing the same thing on another product) is what I followed. Each page has like 6 parts:

    -XAML layout with a code-behind that is totally blank aside from InitializeComponent();
    -A ViewModel with all the public properties/data, which is teh BindingContext in XAML
    -One or more IValueConverters that translate things into stuff (for example booleans into strings that says "this thing does this other thing")
    -The models associated with the form
    -A static class with some business logic (one for each page, not one monolithic .cs file)
    -Access to a web service library - here's where I have try/catch for every web service.

The exception handling is basically two steps: Try the service; catch sends back and empty list. Try to deserialize into an object or collection; catch also sends back an empty list. If everything succeeds, send back the populated data.

These aren't the only try/catch blocks in the app, but I'd say it's 80 to 85% of them. The views themselves are just binding to properties so as long as the property gets initialized (which happens at instantiation) there's nothing to catch. The business logic just checks for "List?.Count() > 0" before proceeding.

Eventually, we'll stop calling Forms.Init() so the ViewModel and View groups will get cut off. Someone else's job will be to replace the whole UI with totally native UI through the platform-specific projects. There is a performance penalty associated with Xamarin Forms, particularly on Android, and we want that to go away. iOS may not ever get fully re-done, but I know Android will. At this point it's going to take a while. There's about 50 total pages in this little mobile app.
I do not understand what I do. For what I want to do I do not do, but what I hate I do.
 
derFunkenstein
Gerbil God
Topic Author
Posts: 24372
Joined: Fri Feb 21, 2003 9:13 pm
Location: Comin' to you directly from the Mothership

Re: Better to throw exceptions or return null?

Wed Mar 07, 2018 8:42 pm

Well, I did it. I threw an exception.

In the Java midterm tonight, the programming part of the exam was to re-implement a Node class and create a LinkedList class that at least adds first, adds last, and adds at index i. That last one can throw an exception.

if (index >= size || index < 0) {
    throw new IndexOutOfBoundsException();
}


My lab partner would shed a tear of pride.
I do not understand what I do. For what I want to do I do not do, but what I hate I do.
 
SecretSquirrel
Minister of Gerbil Affairs
Posts: 2362
Joined: Tue Jan 01, 2002 7:00 pm
Location: North DFW suburb...
Contact:

Re: Better to throw exceptions or return null?

Thu Mar 08, 2018 7:43 am

derFunkenstein wrote:
Well, I did it. I threw an exception.

In the Java midterm tonight, the programming part of the exam was to re-implement a Node class and create a LinkedList class that at least adds first, adds last, and adds at index i. That last one can throw an exception.

if (index >= size || index < 0) {
    throw new IndexOutOfBoundsException();
}


My lab partner would shed a tear of pride.


So I have to ask, why does a linked list have an index? I know, because that's what the assignment said.... just seems to just ask for code that runs very slow because the developer doesn't know the implementation details.

--SS
 
derFunkenstein
Gerbil God
Topic Author
Posts: 24372
Joined: Fri Feb 21, 2003 9:13 pm
Location: Comin' to you directly from the Mothership

Re: Better to throw exceptions or return null?

Thu Mar 08, 2018 7:57 am

You're right. It would make more sense to send two nodes to that method with one of them being a reference to either the "after".

But he wanted us to pass in a number and insert at that position, which is weird. So I started at the head and counted to the index - 1 and adjusted the references.
I do not understand what I do. For what I want to do I do not do, but what I hate I do.
 
just brew it!
Gold subscriber
Administrator
Posts: 51206
Joined: Tue Aug 20, 2002 10:51 pm
Location: Somewhere, having a beer

Re: Better to throw exceptions or return null?

Thu Mar 08, 2018 8:12 am

derFunkenstein wrote:
You're right. It would make more sense to send two nodes to that method with one of them being a reference to either the "after". But he wanted us to pass in a number and insert at that position, which is weird.

Kudos to you for understanding why it is weird.

If you find yourself needing to do an "insert at position n" on a linked list, it's a red flag indicating that a linked list may be the wrong data structure to use in this situation. For a list which is guaranteed to be short it is no big deal, but it doesn't scale -- as the list gets large, the amount of CPU time needed to locate position n increases proportionally, and you thrash the data cache by looking at every single item in the list up to the insertion point.

Or to put it more generally, unless you know that the size of the data set you are dealing with has a low upper bound, you should choose data structures and algorithms which have better than linear scaling. If you're not paying attention to scaling behavior, it is easy to fall into a trap where your implementation actually has worse than linear scaling; the bubblesort algorithm for sorting arrays (which has exponential cost WRT dataset size) is a classic example.

Aside: For lists where ability to perform insertion/deletion before/after an arbitrary item is legitimately needed, you would typically use a doubly-linked list where each item has both a "next" and "previous" link. That way you don't need to pass two node references to the insertion routine (one is sufficient), or deal with the potential exception where the passed references are not neighbors in the list. Then you have "insert before" and "insert after" methods, which take a reference to a single existing node.
Nostalgia isn't what it used to be.
 
geniekid
Gold subscriber
Gerbil In Training
Posts: 8
Joined: Thu Sep 17, 2015 8:32 am

Re: Better to throw exceptions or return null?

Thu Mar 08, 2018 8:37 am

After reading this thread, I want to add a couple of points.

1) The assignment should really be answering this question for you. Whether you throw a checked/unchecked exception versus an error value is part of the method's interface, not it's implementation. If the format of the test/assignment is "here is the interface, give us the implementation", you shouldn't have to worry about this.

2) If you're trying to mimic the standard Java Collections framework, an IndexOutOfBoundsException is conventional for your use-case. Note that IndexOutOfBoundsExceptions are RuntimeExceptions, which means they are unchecked. This is nice because a) if you know have control over the code that calls the method you don't need to write any exception handling code and b) if you don't have control, and someone calls the method with an invalid index, they'll have access to a stack trace that tells them pretty much exactly where things went wrong. Whereas a -1 or null return value could propagate further down the code and obfuscate the bug.

3) Kudos for thinking about interface design! There are so many ways to implement something poorly, but if your interface is good it's so, so, so much easier to fix bugs/performance issues down the road.
 
derFunkenstein
Gerbil God
Topic Author
Posts: 24372
Joined: Fri Feb 21, 2003 9:13 pm
Location: Comin' to you directly from the Mothership

Re: Better to throw exceptions or return null?

Thu Mar 08, 2018 8:59 am

In the "exam" part of the midterm, there were questions like, A is a LinkedList and B is an ArrayList, and then two for loops to cycle through, and he asked which would be more efficient. So it hit me from the beginning that what he was asking for was weird. It was also the extra credit piece of the programming part, so it was secondary to the goal.
I do not understand what I do. For what I want to do I do not do, but what I hate I do.
 
Waco
Gold subscriber
Minister of Gerbil Affairs
Posts: 2371
Joined: Tue Jan 20, 2009 4:14 pm
Location: Los Alamos, NM

Re: Better to throw exceptions or return null?

Thu Mar 08, 2018 10:04 am

I don't like delving into the actual order of many operations - but when determining the right algorithm to use it's often quite helpful to plug in expected average bounds, upper limit bounds, and "the guy using this is using it in crazy ways" bounds to determine how many iterations it takes to do that operation. It's not exact but it's extremely easy and it can quickly highlight poor choices in data structures and search methods.
Z170A Gaming Pro Carbon | 6700K @ 4.4 | 16 GB | GTX Titan Xm | Seasonic Gold 850 | XSPC RX360 | Heatkiller R3 | D5 + RP-452X2 | Cosmos II | Samsung 4K 40" | 2048 + 240 + LSI 9207-8i (128x8) SSDs
 
just brew it!
Gold subscriber
Administrator
Posts: 51206
Joined: Tue Aug 20, 2002 10:51 pm
Location: Somewhere, having a beer

Re: Better to throw exceptions or return null?

Thu Mar 08, 2018 10:14 am

Waco wrote:
I don't like delving into the actual order of many operations - but when determining the right algorithm to use it's often quite helpful to plug in expected average bounds, upper limit bounds, and "the guy using this is using it in crazy ways" bounds to determine how many iterations it takes to do that operation. It's not exact but it's extremely easy and it can quickly highlight poor choices in data structures and search methods.

Yeah, I rarely bother with a detailed analysis of what order an algorithm is; if you can just eyeball it and make an educated guess as to whether it is better than, equivalent to, or worse than linear, that's generally good enough. And if the upper bound on data set size is small and each operation is cheap, you don't even need to take it that far; just use whatever is simplest/easiest. Part of being a productive developer is knowing when to spend time worrying about stuff like that, and when to realize that any potential effects are going to be "lost in the noise".
Nostalgia isn't what it used to be.
 
Waco
Gold subscriber
Minister of Gerbil Affairs
Posts: 2371
Joined: Tue Jan 20, 2009 4:14 pm
Location: Los Alamos, NM

Re: Better to throw exceptions or return null?

Thu Mar 08, 2018 10:18 pm

Talk about coincidence. I ended up rewriting a queue insert today because someone decided that a linked list of a few million items could be used the dumb way...iterating the whole damn thing to insert at the end.

It's amazing how changing 5 lines and adding an extra pointer can save a few million iterations and memory accesses... :P
Z170A Gaming Pro Carbon | 6700K @ 4.4 | 16 GB | GTX Titan Xm | Seasonic Gold 850 | XSPC RX360 | Heatkiller R3 | D5 + RP-452X2 | Cosmos II | Samsung 4K 40" | 2048 + 240 + LSI 9207-8i (128x8) SSDs
 
derFunkenstein
Gerbil God
Topic Author
Posts: 24372
Joined: Fri Feb 21, 2003 9:13 pm
Location: Comin' to you directly from the Mothership

Re: Better to throw exceptions or return null?

Fri Mar 09, 2018 11:50 am

Waco wrote:
Talk about coincidence. I ended up rewriting a queue insert today because someone decided that a linked list of a few million items could be used the dumb way...iterating the whole damn thing to insert at the end.

It's amazing how changing 5 lines and adding an extra pointer can save a few million iterations and memory accesses... :P

Wait...to add to the *end* of the queue? Wouldn't they just keep track of the tail and use that? :lol:

I suppose that's what you did...
I do not understand what I do. For what I want to do I do not do, but what I hate I do.
 
just brew it!
Gold subscriber
Administrator
Posts: 51206
Joined: Tue Aug 20, 2002 10:51 pm
Location: Somewhere, having a beer

Re: Better to throw exceptions or return null?

Fri Mar 09, 2018 12:02 pm

derFunkenstein wrote:
Waco wrote:
Talk about coincidence. I ended up rewriting a queue insert today because someone decided that a linked list of a few million items could be used the dumb way...iterating the whole damn thing to insert at the end.

It's amazing how changing 5 lines and adding an extra pointer can save a few million iterations and memory accesses... :P

Wait...to add to the *end* of the queue? Wouldn't they just keep track of the tail and use that? :lol:

I suppose that's what you did...

Yeah, sounds like it.

There's no shortage of crappy developers out there. Many are merely inexperienced, and will get better over time. But some are just terminally hopeless.
Nostalgia isn't what it used to be.
 
derFunkenstein
Gerbil God
Topic Author
Posts: 24372
Joined: Fri Feb 21, 2003 9:13 pm
Location: Comin' to you directly from the Mothership

Re: Better to throw exceptions or return null?

Fri Mar 09, 2018 12:04 pm

I suppose so. I mean, you don't get much more inexperienced (with experience > 0) than me. :lol:
I do not understand what I do. For what I want to do I do not do, but what I hate I do.
 
morphine
Gold subscriber
TR Staff
Posts: 11461
Joined: Fri Dec 27, 2002 8:51 pm
Location: Portugal (that's next to Spain)

Re: Better to throw exceptions or return null?

Fri Mar 09, 2018 12:21 pm

just brew it! wrote:
Yeah, I rarely bother with a detailed analysis of what order an algorithm is; if you can just eyeball it and make an educated guess as to whether it is better than, equivalent to, or worse than linear, that's generally good enough.

Thank the maker. Although it's important to know the order, the math behind that is a total and complete PITA. Glad to see that a Real Professional (tm) looks at algorithm performance roughly the same way I do.
There is a fixed amount of intelligence on the planet, and the population keeps growing :(
 
Waco
Gold subscriber
Minister of Gerbil Affairs
Posts: 2371
Joined: Tue Jan 20, 2009 4:14 pm
Location: Los Alamos, NM

Re: Better to throw exceptions or return null?

Fri Mar 09, 2018 4:54 pm

derFunkenstein wrote:
Wait...to add to the *end* of the queue? Wouldn't they just keep track of the tail and use that? :lol:

I suppose that's what you did...

:) That's exactly it. Instead of an O(n) insert it's O(1) effectively.

The use in question routinely had north of a few million entries in it...so you can imagine insertion speeds are quite good in comparison now. :P
Z170A Gaming Pro Carbon | 6700K @ 4.4 | 16 GB | GTX Titan Xm | Seasonic Gold 850 | XSPC RX360 | Heatkiller R3 | D5 + RP-452X2 | Cosmos II | Samsung 4K 40" | 2048 + 240 + LSI 9207-8i (128x8) SSDs

Who is online

Users browsing this forum: No registered users and 1 guest