|
Lord Of Texas posted:Here's a design question. It has members of my development team on opposite sides, so I thought I'd get the opinions of the thread. 1 is a terrible thing because very few people check for null, especially in Java. This leads to a NullPointerException. 3 is terrible because it requires you to test all of ThingBean 2 is the best choice, although people will often just write try{ } catch (Exception e) rather then the specific exception.
|
# ? Aug 30, 2012 17:47 |
|
|
# ? Jun 2, 2024 21:42 |
|
Aleksei Vasiliev posted:Option 3 is the solution I'd go with if I was asked to come up with the worst solution. The people who argue "return null" state that a null is a part of the method's contract, so the burden is on the client to check for null. If the client fails to check for null, they argue that's a runtime NPE caused by the client not holding up it's part of the contract. Where a checked exception has advantages is it forces the client to handle the "no resource" case - idiot-proof, basically. The opposing camp argues that "thing not found" is a valid use case, so throwing a checked exception would be a violation of "don't use exceptions for flow control". I guess it boils down to whether the resource not being found is a valid use case or not. I still hate returning nulls though - it results in weak contracts and easily introduces hard-to-debug defects if a client neglects to check for null.
|
# ? Aug 30, 2012 17:52 |
|
quote:1 is a terrible thing because very few people check for null, especially in Java. This leads to a NullPointerException. Yeah, this is basically exactly how I feel, glad to know I'm not alone. The principal devs on my project prefer using null as a valid response and putting the onus on the client to check for null. Since clients can just catch(Exception){do nothing} at some point you do have to trust the client to not be terrible, but I feel like a checked exception in this case gives the client less leeway to gently caress up.
|
# ? Aug 30, 2012 17:57 |
|
Option 4: use Optional from Guava or something like it to indicate an intended absence of a value.
|
# ? Aug 30, 2012 18:02 |
|
Lord Of Texas posted:Yeah, this is basically exactly how I feel, glad to know I'm not alone. The principal devs on my project prefer using null as a valid response and putting the onus on the client to check for null. I'm with your devs. If you throw an Exception, you make the client do more boilerplate try/catch and flow control than simply checking for null or allowing the NPE to happen and be caught. There are many cases where you don't want the wrapper method to crash out entirely if an object can't be retrieved. To think about it on another level, do you really want HashMap to throw an exception if it doesn't have a key?
|
# ? Aug 30, 2012 18:19 |
|
Doctor w-rw-rw- posted:Option 4: use Optional from Guava or something like it to indicate an intended absence of a value. Yeah, I've considered some variation of Null/Missing Object, i.e. returning this guy when Thing isn't found: code:
1) The client is not forced to check for what instance he has 2) if the client doesn't check for the instance, the MissingThingBean gets propagated up to some other layer that may or may not handle it gracefully. Optional looks like a solid choice though - thanks for the recommendation!
|
# ? Aug 30, 2012 18:20 |
|
quote:I'm with your devs. If you throw an Exception, you make the client do more boilerplate try/catch and flow control than simply checking for null or allowing the NPE to happen and be caught. This has been brought up in our team discussion too. My thoughts are: Is this: code:
code:
quote:There are many cases where you don't want the wrapper method to crash out entirely if an object can't be retrieved. To think about it on another level, do you really want HashMap to throw an exception if it doesn't have a key? If you are talking about getThing(), let's assume that getThing() doesn't have any reason to continue once it has determined that the requested Thing doesn't exist. Lord Of Texas fucked around with this message at 18:43 on Aug 30, 2012 |
# ? Aug 30, 2012 18:33 |
|
Lord Of Texas posted:Is this: In isolation, it's nearly identical. But what if we want to get a few different thing objects and then work with whatever set we have? code:
code:
quote:If you are talking about getThing(), let's assume that getThing() doesn't have any reason to continue once it has determined that the requested Thing doesn't exist. No, I was just talking the wrapper/called function. baquerd fucked around with this message at 19:00 on Aug 30, 2012 |
# ? Aug 30, 2012 18:54 |
|
Thanks for the response, I get what you are saying now with the HashSet example. One of our team's problems is we don't use FindBugs or any other sort of code analysis tool, and our QA is... not great, so if another dev decides to use my getThing() method, I'm very wary about giving them any slack lest we cause some killer bug. Maybe some sort of NullThing object is the way to go, but either way thank you for the explanation.
|
# ? Aug 30, 2012 19:13 |
|
Well Java 7 will fix that stupid issue:code:
|
# ? Aug 30, 2012 19:14 |
|
Lord Of Texas posted:Yeah, I've considered some variation of Null/Missing Object, i.e. returning this guy when Thing isn't found: It makes code a little more verbose, but it's almost single-handedly responsible for reducing the exceptions in the Android app I develop to virtually nil. It's super-useful, and if you ever get an IllegalStateException from .get()'ing it when you shouldn't it can help reveal logical flaws in assumptions about the nullity of a value. Another tip - don't feel afraid to *not* check if its value is present if you have a strong reason to expect that it is not going to be null, because that is an exceptional circumstance that should indeed be detected by an exception. Also, the extending approach loses type-safety, and delays error handling, whereas the wrapper approach retains it (mostly - thanks, type erasure). It lets you fail faster and more explicitly, because your assumptions about the presence of the object must be explicit tests. Doctor w-rw-rw- fucked around with this message at 19:23 on Aug 30, 2012 |
# ? Aug 30, 2012 19:18 |
|
Doctor w-rw-rw- posted:Another tip - don't feel afraid to *not* check if its value is present if you have a strong reason to expect that it is not going to be null, because that is an exceptional circumstance that should indeed be detected by an exception. Maybe I'm misunderstanding, but in that case wouldn't you just not use Optional? An Optional return value means the contract is "This can be empty and you should account for that", but if null is not a valid response, that contract says "This cannot be empty, don't worry about accounting for that".
|
# ? Aug 30, 2012 19:27 |
|
Lord Of Texas posted:Maybe I'm misunderstanding, but in that case wouldn't you just not use Optional? An Optional return value means the contract is "This can be empty and you should account for that", but if null is not a valid response, that contract says "This cannot be empty, don't worry about accounting for that". Almost but not quite. Since you have to call .get() rather than passing it through to even get the value, you don't run the risk of a logic error propagating a null and erroring wherever-the-gently caress eventually actually needs it. It basically forces a pre-emptive null check before even passing it along. That's at its most minimal usage. In other cases, it's also useful for reducing a setter and getter for some persistent preference storage, for example, to one which doesn't need to have a check for whether it's set or not, and instead just returns a wrapped object if it is, and an absent value if it's not (i.e. instead of set/get/isNull, it's set and get with set accepting a null or empty value and get returning an optional or absent value). Put another way, if you just pass the Optional everywhere and only get it at the last possible moment (not the greatest way to use it IMO, but it comes down to taste and experience), then you're functionally equivalent to just passing the variable around and substituting the NPE with an IllegalStateException. On the other hand, using it and considering when to unwrap the value lets you create logical borders in your code in which you are uncertain that a value is there, or you must be certain a value is there. The way I'd characterize it is that it adds discipline and explicitness at the price of a little bit of verbosity with no major disadvantage (unless you've created a very complex type system for yourself in which case you need to add a little bit more verbosity on top of that). Doctor w-rw-rw- fucked around with this message at 19:43 on Aug 30, 2012 |
# ? Aug 30, 2012 19:36 |
|
I personally believe that the contract should be something like this: 1. If the method returns a collection, then it should never return null. Return an empty collection if there are no things there. 2. If the method returns a single object, it returns null if there are no objects that satisfy the condition (find(id) for example). The best solution is the one provided by Scala with the Optional support, but in Java an implementation of that would only lead to more verbose code for what otherwise should be a simple check. The worst solution is throwing a runtime exception (like JPA for createQuery(...).getSingleResult()). Of course, to any solution there are exception cases, and there could indeed be times where returning new Thing("i don't have any") may be valid and preferred, but i personally think this should not be the normal way of doing things.
|
# ? Aug 31, 2012 13:40 |
|
rhag posted:I personally believe that the contract should be something like this: This is what I do unless I have Option types.
|
# ? Aug 31, 2012 15:05 |
|
rhag posted:I personally believe that the contract should be something like this:
|
# ? Aug 31, 2012 16:14 |
|
rhag posted:I personally believe that the contract should be something like this: The getSingleResult() case in an interesting one. I think it throwing the non-checked NoResultException and NonUniqueResultException is appropriate, because the word "single" implies a very strict contract. If there was another method named getFirstResult(), it would be natural to specify it in terms of getResultList() leading it to not throwing those exceptions. Instead of Optional, using one of the NotNull annotations and an IDE with an well-integrated static analysis for them would be better if you can make it work in your organization. I don't like tweaking the return type or wrapping the value. A variable holding the return value of a method has several properties: formal coming from its type, some that are promised by the name of the variable, informal that are inferred from the method's name. Adding more properties by adding annotations scales easily; changing types much less so.
|
# ? Aug 31, 2012 18:54 |
|
Win8 Hetro Experie posted:Instead of Optional, using one of the NotNull annotations and an IDE with an well-integrated static analysis for them would be better if you can make it work in your organization. I see where you're coming from, but I have the opposite opinion - I prefer wrappers to annotations. It's easy to go hog-wild with null-checking even where it's not necessary, and I'd rather be able to see at a glance in the debugger which variables are optional and which ones aren't. Put another way, I like types and I use them to provide incentives to myself to write code a particular way with the end-goal of having a mostly consistent codebase with clear and recognizable patterns. YMMV and your way of checking is just as valid.
|
# ? Aug 31, 2012 20:48 |
|
I posted not too long ago but I have another unit testing question. Still sorta new to it and trying to push myself in learning new techniques. I have this class that I kinda shortend (for this example) that I need to test. code:
Right now, I have stuff set up to to do a createInstance(); but nothing seem to make any sense to me in how to fall into this. The added variable and interfaces are making me hella confused here. It seems simple to test and is a very, very short class- but not being exposed to this (Java isn't even my first language) is kind of a hard wall for me to get over). Any help on how to set up either a standard JUnit or Mockito (doesn't matter really) on how to set all this up? Also the fact that's protected is making me even more clueless since proper standard is to have Unit Tests in another package.
|
# ? Sep 6, 2012 21:15 |
|
notMordecai posted:I posted not too long ago but I have another unit testing question. Still sorta new to it and trying to push myself in learning new techniques. The unit tests should be in the same package as the class they're testing. Another source folder, sure, but the same package. At that point you can make things (members, methods, etc.) package private and call them,assign them, etc. If you really cannot make that protected method package private, you can do things like subclassing HandlerFactory in your unit test, that can have a method that calls createSomethingByKey . But really, that's a slippery slope, since then you end up testing the subclassed class not the class you want to actually test. But in some cases it may be the only thing you can do.
|
# ? Sep 7, 2012 13:15 |
|
Is there any significant difference betweencode:
code:
|
# ? Sep 7, 2012 16:41 |
|
rhag posted:The unit tests should be in the same package as the class they're testing. Another source folder, sure, but the same package. At that point you can make things (members, methods, etc.) package private and call them,assign them, etc. Yeah I figured I would have to do that. I ended up figuring out the proper syntax last night. Unit Testing is hard when you barely know important Java syntax. :\ Thanks for your help though!
|
# ? Sep 7, 2012 16:41 |
|
ManlyWeevil posted:Is there any significant difference between It's a faux pas
|
# ? Sep 7, 2012 18:52 |
|
ManlyWeevil posted:Is there any significant difference between This Java code:
Java code:
|
# ? Sep 7, 2012 19:06 |
|
The first will catch *all* exceptions silently except the one it checks for. The second, which is more proper, will only catch those two types and their subclasses. Unless you're wrapping a library you think might be unreliable (and have planned accordingly), it is my opinion that you should NOT use a catch-all for exceptions. If you need something to be run no matter what, like a close() call to a stream or something, then put it in a finally block. e: beaten to the punch.
|
# ? Sep 7, 2012 19:18 |
|
Doctor w-rw-rw- posted:The first will catch *all* exceptions silently except the one it checks for. The second, which is more proper, will only catch those two types and their subclasses. Apologies, ignoring the catch all (pretend any unchecked exception is simply rethrown), is there any difference between catch(SomeException e) and if (e instanceof SomeException) ?
|
# ? Sep 7, 2012 20:18 |
|
ManlyWeevil posted:Apologies, ignoring the catch all (pretend any unchecked exception is simply rethrown), is there any difference between catch(SomeException e) and if (e instanceof SomeException) ? Yes. Exceptions are matched to catch-blocks based on their type at runtime. Checked exceptions are checked only at compile-time and it is possible to circumvent this check, leading to a checked exception being propagated like an unchecked exception at runtime. So this means that in principle it is possible for a wider catch-block to catch some unanticipated exceptions that arguably shouldn't have been thrown in the first place. Java 7 has multi-catch-blocks, which I'm going to guess do the right thing so you can write: Java code:
|
# ? Sep 7, 2012 20:51 |
|
ManlyWeevil posted:
If it had else { throw e; } then it would be the same as proper catch blocks, I think.
|
# ? Sep 8, 2012 03:07 |
|
Anyone know of a free library for PDF > JPEG conversion? I can't find anything that isn't paid software and I'm really not interested in having to pay for it
|
# ? Sep 11, 2012 14:05 |
|
I just used the command-line convert tool from ImageMagick to convert a PDF to JPEGs with no fuss whatsoever (it gave me one image for each page of the document). It would be quick and dirty, but you could conceivably call convert from your Java app. It might be a better idea to use the JNI wrapper around the ImageMagick API (JMagick), and it's your call as to whether the increased complexity is worth it. It all depends on how hacky a solution you're willing to accept. This quote from the JMagick page doesn't inspire me with much confidence, either: quote:JMagick does not attempt to make the ImageMagick API object-oriented. It is merely a thin interface layer into the ImageMagick API.
|
# ? Sep 11, 2012 14:32 |
|
The whole program's hacky as gently caress, so that should be fine. I can't use plain convert calls since I have to embed this whole steaming pile of poo poo inside of Apple Filemaker () but JMagick looks perfect, thanks!
|
# ? Sep 11, 2012 14:42 |
|
PDFBox seems to support page -> image conversions. http://pdfbox.apache.org/apidocs/org/apache/pdfbox/pdmodel/PDPage.html#convertToImage()
|
# ? Sep 11, 2012 14:53 |
|
Oh poo poo that's perfect and dirt easy, thank you so much
|
# ? Sep 11, 2012 14:55 |
|
MrTheDevious posted:Anyone know of a free library for PDF > JPEG conversion? I can't find anything that isn't paid software and I'm really not interested in having to pay for it (why JPG instead of PNG?) The current release is only two months old, so it even looks like it's maintained! I have obviously not tested this myself, so this might be worthless. edit: gently caress did I not refresh or something Malloc Voidstar fucked around with this message at 15:10 on Sep 11, 2012 |
# ? Sep 11, 2012 15:03 |
|
I have a pretty solid Swing application that I inherited and has been in use for a couple years by a large handful of people. Every once in awhile, an exception will occur of one nature or another (it's never reproducible) and a javaw.exe will be left in their processes even though the application closed. The original programmer set up an uncaught exception handler in the main class to handle uncaught exceptions. I'm assuming that this fires each time that the issue is experienced, but we do not always get the best information from the user. Thread.setDefaultUncaughtExceptionHandler(new FooBarExceptionHandler()); Does anyone have an advice or articles I could check out? This is sort of a new realm for me, huge codebase, and kind of a vague subject.
|
# ? Sep 11, 2012 20:44 |
For programming we've been given the task of creating a method that performs the following expression (which is the definition of cosine) : Now I thought this was pretty straight forward, but I'm not getting the intended return values. This is my code: code:
Any kind of help would be appreciated, as long as it allows me to learn what I did wrong. EDIT: I should note; the intended outcome of the method is that it takes an arc length, x, and a number of times to recurse the expression, k, and it should return cos(x). E2: Also; this is not a hand-in so I don't get credit for it. I just want to understand it. Joda fucked around with this message at 18:12 on Sep 18, 2012 |
|
# ? Sep 18, 2012 17:30 |
|
Joda posted:
There's no recursion in your post.
|
# ? Sep 18, 2012 17:42 |
Nippashish posted:There's no recursion in your post. That might've been me misunderstanding things, though, but I thought a sum was recursive because it uses its own return values in its definition (I.e. you can't necessarily express a sum like a traditional function, but need to use the return value of a previous generation.) These are all new terms to me, however, so I could be wrong. That said I'm talking about the mathematical definition of recursion and not the programming definition, if that's what you mean.
|
|
# ? Sep 18, 2012 18:00 |
|
How much have you played around with this? Try some smaller values for your input 'k' and see what you get. Something likecode:
Newf fucked around with this message at 20:28 on Sep 18, 2012 |
# ? Sep 18, 2012 20:24 |
|
|
# ? Jun 2, 2024 21:42 |
Newf posted:How much have you played around with this? Try some smaller values for your input 'k' and see what you get. Something like Output: code:
Thanks a lot for that. That's a mistake I'm not going to make again. EDIT: Wait, shouldn't it return NaN if I've broken the limit of a data type? Joda fucked around with this message at 21:09 on Sep 18, 2012 |
|
# ? Sep 18, 2012 20:38 |