Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
HFX
Nov 29, 2004

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.
-----

Say you're calling a method that returns some business resource from an external service.

code:
public ThingBean getThingBean(params){}
The requirements state that if the requested resource is not found, the application should recover (i.e. throwing an unchecked exception is out).

Your options when the resource is not found are:

1) return null
2) throw a checked exception for the client code to handle
3) return an empty ThingBean with no fields populated

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.

Adbot
ADBOT LOVES YOU

Lord Of Texas
Dec 26, 2006

Aleksei Vasiliev posted:

Option 3 is the solution I'd go with if I was asked to come up with the worst solution.

If throwing an unchecked exception is out, then so is returning null, as they can fail to handle that (and cause a NPE).

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.

Lord Of Texas
Dec 26, 2006

quote:

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.

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.

Doctor w-rw-rw-
Jun 24, 2008
Option 4: use Optional from Guava or something like it to indicate an intended absence of a value.

baquerd
Jul 2, 2007

by FactsAreUseless

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.

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.

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?

Lord Of Texas
Dec 26, 2006

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:
MissingThingBean extends ThingBean{

	@Override
	public ThingCode getThingCode(){
		return new ThingCode("The requested Thing was not found");
	}
}
But that means
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!

Lord Of Texas
Dec 26, 2006

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:
try{
Thing thing = getThing();
}catch(MissingThingException e){

}
//forced to handle missing thing by compiler, no matter how much the dev doesn't want to read the contract
Really that much more boilerplate than:

code:
Thing thing = getThing();
if (thing==null){

}
//handle "null" thing - could be missing, or could have accidentally returned an //empty reference to a Thing. Depends on method contract which the dev may or may //not have paid attention to
Sure "throws" clauses could be considered boilerplate as well, but at the very least they are self-documenting.

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

baquerd
Jul 2, 2007

by FactsAreUseless

Lord Of Texas posted:

Is this:
code:
try{
Thing thing = getThing();
}catch(MissingThingException e){

}
Really that much more boilerplate than:

code:
Thing thing = getThing();
if (thing==null){

}

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:
HashSet<Thing> set = new HashSet<Thing>();
try{
  Thing thing = getThing(param1);
  set.add(thing);
}catch(MissingThingException e){ }

try{
  Thing thing = getThing(param2);
  set.add(thing);
}catch(MissingThingException e){ }
//...
for (Thing thing : set) { //... }
code:
HashSet<Thing> set = new HashSet<Thing>();
set.add(getThing(param1));
set.add(getThing(param2));
set.remove(null);
for (Thing thing : set) { //... }

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

Lord Of Texas
Dec 26, 2006

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.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
Well Java 7 will fix that stupid issue:

code:
catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

Doctor w-rw-rw-
Jun 24, 2008

Lord Of Texas posted:

Yeah, I've considered some variation of Null/Missing Object, i.e. returning this guy when Thing isn't found:
code:
MissingThingBean extends ThingBean{

	@Override
	public ThingCode getThingCode(){
		return new ThingCode("The requested Thing was not found");
	}
}
But that means
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!

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

Lord Of Texas
Dec 26, 2006

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".

Doctor w-rw-rw-
Jun 24, 2008

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

Volguus
Mar 3, 2009
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.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

rhag posted:

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.

This is what I do unless I have Option types.

Doctor w-rw-rw-
Jun 24, 2008

rhag posted:

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.
It's only a little more verbose. Optional.of(foo) is only slightly more than Some(foo). It's worked out very nicely for me, anyway. Good enough that I prefer it to the above null convention. YMMV I guess.

Max Facetime
Apr 18, 2009

rhag posted:

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()).

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.

Doctor w-rw-rw-
Jun 24, 2008

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 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.

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.

notMordecai
Mar 4, 2007

Gay Boy Suicide Pact?
Sucking Dick For Satan??

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:
public class HandlerFactory extends SecondHandlerFactory
{
	//To hold singleton of this class.
	private static SecondHandler factoryInstance = null;

	private HandlerFactory() throws HandlerCreationException
	{
                super();
	}

	protected InterfaceExample createSomethingByKey(String key) throws HandlerCreationException
	{
		InterfaceExample myNewHandler = null;
		
		if (StringFunctions.isEqualIgnoreCase(key, "Phone"))
		{
			myNewHandler = new PhoneHandler();
		}
	}
}
I'm having major trouble figuring out to set up this test to even fall into the createSomethingByKey(). Even then, I can't even figure out how I would do my assertEquals() method correctly.

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.

Volguus
Mar 3, 2009

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.

I have this class that I kinda shortend (for this example) that I need to test.

code:
public class HandlerFactory extends SecondHandlerFactory
{
	//To hold singleton of this class.
	private static SecondHandler factoryInstance = null;

	private HandlerFactory() throws HandlerCreationException
	{
                super();
	}

	protected InterfaceExample createSomethingByKey(String key) throws HandlerCreationException
	{
		InterfaceExample myNewHandler = null;
		
		if (StringFunctions.isEqualIgnoreCase(key, "Phone"))
		{
			myNewHandler = new PhoneHandler();
		}
	}
}
I'm having major trouble figuring out to set up this test to even fall into the createSomethingByKey(). Even then, I can't even figure out how I would do my assertEquals() method correctly.

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.

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.

Drape Culture
Feb 9, 2010

But it was all right, everything was all right, the struggle was finished. He had won the victory over himself. He loved Big Brother.

The End.
Is there any significant difference between

code:
try {
...
} catch (Exception e) {
    if (e instanceof SomeException) {
        doSomething(e);
    } else if (e instanceof SomeOtherException) {
        doSomethingElse(e);
    }
}
And the usual

code:
try {
...
} catch (SomeException e) {
    doSomething(e);
} catch (SomeOtherException e) {
    doSomethingElse(e);
}

notMordecai
Mar 4, 2007

Gay Boy Suicide Pact?
Sucking Dick For Satan??

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.

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.

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!

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

ManlyWeevil posted:

Is there any significant difference between

code:
try {
...
} catch (Exception e) {
    if (e instanceof SomeException) {
        doSomething(e);
    } else if (e instanceof SomeOtherException) {
        doSomethingElse(e);
    }
}
And the usual

code:
try {
...
} catch (SomeException e) {
    doSomething(e);
} catch (SomeOtherException e) {
    doSomethingElse(e);
}

It's a faux pas

Shaggar
Apr 26, 2006
Probation
Can't post for 4 hours!

ManlyWeevil posted:

Is there any significant difference between

code:
try {
...
} catch (Exception e) {
    if (e instanceof SomeException) {
        doSomething(e);
    } else if (e instanceof SomeOtherException) {
        doSomethingElse(e);
    }
}
And the usual

code:
try {
...
} catch (SomeException e) {
    doSomething(e);
} catch (SomeOtherException e) {
    doSomethingElse(e);
}

This
Java code:
catch(Exception e)
will eat all exceptions including RuntimeExceptions. You probably dont want to do that. What might make a little more sense is if you have SomeRootException which is a parent of SomeException and SomeOtherException so you do like:

Java code:
try
{
	...
}
catch(SomeRootException e)
{
	doSomeCommonStuff();
	if(e instanceof SomeException)
	{
		doSomeSpecificStuff();
	}
	else if(e instanceof SomeOtherException)
	{
		doSomeOtherSpecificStuff();
	}
}
which maybe lets you handle stuff for all types of SomeRootException but then do specific things if its a specific child of SomeRootException.

Doctor w-rw-rw-
Jun 24, 2008

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.

Drape Culture
Feb 9, 2010

But it was all right, everything was all right, the struggle was finished. He had won the victory over himself. He loved Big Brother.

The End.

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.

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.

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) ?

Max Facetime
Apr 18, 2009

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:
try {
  // stuff
} catch(SomeException | SomeOtherException e) {
  // handling
}

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

ManlyWeevil posted:

code:
try {
...
} catch (Exception e) {
    if (e instanceof SomeException) {
        doSomething(e);
    } else if (e instanceof SomeOtherException) {
        doSomethingElse(e);
    }
}
This catches every exception and if it is not in the instanceof checks silently ignores it.
If it had else { throw e; } then it would be the same as proper catch blocks, I think.

MrTheDevious
May 7, 2006

Ahh nostalgia, you cruel bitch
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

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
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.

JMagick currently only implements a subset of ImageMagick APIs.
I'd guess that JMagick is worth it iff you don't have to initialize and manage the library's memory yourself (along the lines of PHP's asinine curl_init function).

MrTheDevious
May 7, 2006

Ahh nostalgia, you cruel bitch
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 (:suicide:) but JMagick looks perfect, thanks!

IMlemon
Dec 29, 2008
PDFBox seems to support page -> image conversions.

http://pdfbox.apache.org/apidocs/org/apache/pdfbox/pdmodel/PDPage.html#convertToImage()

MrTheDevious
May 7, 2006

Ahh nostalgia, you cruel bitch
Oh poo poo that's perfect and dirt easy, thank you so much

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

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
Quick search: Have you tried Apache PDFBox? It says it can turn PDFs into images, though it notes it is beta quality. I assume "images" means BufferedImages, in which case you'd then use ImageIO to write them as a JPG.
(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

mister_gosh
May 24, 2002

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.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
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:
public static double cosineTaylor(double x, int k) {
		
		double sum = 0;
		int twoIFactorial;
		
		for (int i = 0; i <= k; i++) {	 //Recurse for every value of i up to and including k
			
			twoIFactorial = 1;
			
			for (int j = (2*i); j > 0; j--) {
				twoIFactorial = (twoIFactorial * j);		//Define (2i)! as a single int (Works)
			}
			
			sum = sum + ( ( Math.pow((-1), i) * Math.pow(x, (2 * i)) ) / twoIFactorial  ); //Add to sum
		}
		
		return sum;	//Return the final sum
		
	}
I know from a bit of experimentation that the factorial loop works like it should, and as far as I can tell the way I wrote the expression is correct as well, so I think I must've hosed up the way in which I do the recursion. I've been staring at this problem for an hour now, and I can't for the life of me figure out where I went wrong. (The problem is that with a k value of 10 and an x of 3.14 I get a return value of -4, which is way off base)

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

Nippashish
Nov 2, 2005

Let me see you dance!

Joda posted:

code:
		for (int i = 0; i <= k; i++) {	 //Recurse for every value of i up to and including k
...
I must've hosed up the way in which I do the recursion.
...
a number of times to recurse the expression

There's no recursion in your post.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe

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.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
How much have you played around with this? Try some smaller values for your input 'k' and see what you get. Something like

code:
for (int k=1; k<= 15; k++){
   System.out.println(k + " recursions :  " + cosineTaylor(3.14,k));
}
may be illuminating for you.

Newf fucked around with this message at 20:28 on Sep 18, 2012

Adbot
ADBOT LOVES YOU

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe

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

code:
for (int k=1; k<= 15; k++){
   System.out.println(k + " recursions :  " + cosineTaylor(3.14,k));
}
may be illuminating for you.

Output:
code:
1 recursions: -3.9298
2 recursions: 0.12068800666666757
3 recursions: -1.2105183783510216
4 recursions: -0.9761404770345857
5 recursions: -1.0018168365436917
6 recursions: -0.9998989681026615
7 recursions: -1.0069810853034464
8 recursions: -0.9624220627974793
9 recursions: 0.01762731720225519
10 recursions: -4.112208875974112
Oh. So, as far as I can tell now, I'm breaking the limitations of the data types if I go over k = 8 for x = pi. Is that correct? If so, that's a bloody load off my mind. I was going through my discrete maths notes and everything worried I might've completely misunderstood something.

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply