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
Doctor w-rw-rw-
Jun 24, 2008

Sedro posted:

No, Java can only close over final variables.

Personally, I try to make all fields/variables/parameters final. I'm curious, does this have any impact on performance?

The answer is: no...but yes in multithreaded environments.

In general it's a good idea to use final wherever possible. When I'm not on Android, I like making immutable objects for my models whenever I can. It's a useful design constraint so that rather than mutating a model object, possibly reading the in-memory representation for some updated data, and letting it be persisted at some random other time as well, I am forced to atomically update it in order for changes to be reflected. Doing this means (to me, anyway) that you can more easily design a proper abstraction for a multi-level cache because of stronger control over the workflow re: persisting poo poo.



MEAT TREAT posted:

This is going to sound counter to what you guys want, but learn loving maven and be done with it. If you want to do anything with the Java ecosystem you're going to run into it, and it basically replaces all that setup that the IDE does, so I think it's worthwhile for beginners to learn and use it.

By placing all of your source files in the correct directories maven, will compile and generate a jar file containing the compiled sources. You can use that jar file directly from the command line and not have to deal with all the classpath bullshit. There is no benefit to know how to do that poo poo by hand, it's a huge waste of time and ultimately detracts from what you actually want to learn.

One of the main features of maven is its dependency resolution, but for your baby's first program you probably won't require any dependencies. As you start doing more complex things that aren't part of the standard api you'll want to use them and maven can help.

Ah, yes. Maven. Sometimes an excellent tool. Its dependency resolution is hard to beat, but on the flip side it must be your entire universe should you decide to use it. M2Eclipse can sometimes play poorly with WDT+Eclipse (web), and M2Eclipse+ADT (Android) isn't something I've tested yet. On the other hand, I believe Ivy can access the same repositories as Maven can, without the build-system universe having to be ported over. Ant+Ivy is a common pairing (and it helps that the android tools provide a build.xml for you). While Maven can execute Ant tasks, it's also a reality that configuration can be arcane at times - sometimes simple things become incredibly complex, even when at the same time incredibly complex things become simple. I'm still very partial to Maven, but beware of its enterprisey nature.

pigdog posted:

Java IDEs don't necessarily do any of that. Yet if you choose to create a project structure, Ant build files and whatnot, then for projects larger than Hello World it's probably a good idea anyway. A good IDE checks syntax, integrity, imports etc on the fly and lets you fix them semi-automatically, saving you a lot of javac->edit->javac cycles. Going for commandline first is kinda similar to learning to write prose by insisting on using a pencil and paper, as opposed to word processor on a computer.

Pretty much.

  • Auto-import
  • Refactoring massive amounts of code
  • Auto-completion
  • Auto-stubbing of unimplemented methods
  • Code formatting
  • Incremental compilation as you write code
  • Automatic @Override annotation
  • Flagging deprecated methods
  • Displaying documentation inline with the autocompletion
  • Exception suggestions
  • Code path analysis (i.e. you forgot to return in this possible chain of if conditions in your method)

Java behaves as if it was practically designed to be written for you. I only write a small chunk of code; my IDE auto-completes the rest. A good Java programmer should be writing a low percentage of the actual text that comprises the code base, and spend all their typing and brainpower on business logic.

Doctor w-rw-rw- fucked around with this message at 20:14 on Jan 19, 2012

Adbot
ADBOT LOVES YOU

Doctor w-rw-rw-
Jun 24, 2008

NotHet posted:

What are the cool kids using these days for an MVC Framework? Struts 2 + Hibernate?
I've been playing around with the Spring + Hibernate and it seems to be pretty nice.

Play framework is a really cool non-Servlet app framework. Klout and some other companies use it in production and its Scala support was good enough for Typesafe to anoint it officially as...something. I forgot. But its Java bindings are great, and I find it a lot of fun.

Doctor w-rw-rw-
Jun 24, 2008

TRex EaterofCars posted:

Or you can just use groovy. It makes xml super simple.

Because adding a whole language to a project for a single feature is no problem for anyone...what advantages and features specifically addressing XML does Groovy have?

Seconding XOM. It's straightforward in its usage.

Doctor w-rw-rw-
Jun 24, 2008

TRex EaterofCars posted:

No need to be a dick; XML in Java is so hairy that writing a small class in Groovy is vastly preferable. Java's going polyglot anyhow, might as well jump on board.

To answer your question, XML is basically a first class citizen in Groovy. Both reading and writing are super simple. I make judicious use of MarkupBuilder and XMLParser myself.

http://groovy.codehaus.org/Processing+XML

Sorry, wasn't trying to be a dick. I don't really favor the trend towards JVM languages that aren't statically typed. If I want to go for something interpreted or much looser in general than Java, I'm happy to make use of Objective-C and Python. And for many projects, usage of Groovy or even Scala is a pretty hard sell, so someone working on a project might not necessarily have the option to add a whole new language, particularly not if there's - for example - established practices for testing and a test scaffolding that expects things to be one way, and metrics that evaluate said testing. That is to say, for some, process might get in the way of progress.

I only took a very brief look, but it seems that Groovy has a concise format for parsing, but as someone who writes in Java, verbosity can sometimes be tolerated for other features. In the case of XOM, it can clean up the DOM of HTML files, which is what I like it for.

Doctor w-rw-rw-
Jun 24, 2008

Kilson posted:

Your class is called 'homeObj', and your last line is 'homeObj.<method>', which looks like a static call. The last line should say 'homeObject.setLocation...' instead.

Also, class names should start with an upper-case letter in Java. It helps avoid things like this.
Indeed. It would behoove all Java programmers to remember to follow standard convention:
ClassName
variableName (or variable_name, but this is awkward)
CONSTANT_NAME

Doctor w-rw-rw-
Jun 24, 2008

DholmbladRU posted:

code:
  <form name="setAsSold"  action="markSold.jsp" method='POST'>
   		<select name="setAsSold">
   		<option value="" name="hSold"></option>
   	<%
    for ( int i = 1; i < h.length; i++ ) {
    	
    	String tmp = h[i].getHome();
    	String tmp2 = h[i].getLocation();
    	
        %>
        
		<option name="hSold" value="<%= i%>">   <%=tmp + " " + tmp2%></option>
		
		<% }%>
		</select>
		<th><input type="submit" value="Mark as sold"/></th>
    </form>
    </body>
When displayed the drop down is populated with two concatinated strings. Howester I am unable to get the "value" of the element I select in the drop down when I submit the form. I am using 'request.getParameterValues("stuff")' on the JSP end to get the value. This worked for other forms when they were text fields.

Are you checking setAsSold[], or just setAsSold? Maybe it's being treated as an array?

Doctor w-rw-rw-
Jun 24, 2008

Tots posted:

Forums upgrade or equivalent for anyone willing to help me complete a java assignment tonight. I don't want someone to do it for me, rather to walk me through the whats and whys in a collab online editor.

More details, please

Doctor w-rw-rw-
Jun 24, 2008
MyBatis or JPA/Hibernate? Relative strengths?

Background:
After a lot of finagling to get Guice and JPA/Hibernate to play nice, I've finally got something hooked up to a h2 database (for testing) to where I can call entityManager.persist(foobar) or entityManager.createQuery("SELECT f FROM FooBar f").getResultList(), but I'm wondering if it's worth it. MyBatis' Guice integration looks awfully neat, and all this SessionFactory and EntityManager and persistence.xml stuff looks mighty confusing. However, JPA generates SQL schemas, which is super useful for me before I even know what my schema should be like.

I'm tinkering with Quartz, Guice, and Abdera. For now the goal is just to get an RSS feed and stuff items in a database, but ideally I'd be crawling stuff like web searches or my facebook feed and persisting the crawl. Not really sure how to approach this, and I think that choice of ORM framework would influence these.

This is sort of for a hobby thing so it's also for learning, so "Just use JDBC directly" is a boring option I'd prefer alternatives to.

Doctor w-rw-rw-
Jun 24, 2008

TRex EaterofCars posted:

Hibernate is great until it's not. Once you hit that wall you will be loving pissed at it until you invariably rip it out. But that all depends on the scale of your application. If it never grows very big Hibernate is perfectly fine. Personally, I like it for prototyping and that's about it. Using the DDL generator (like you mention) is definitely a plus, it's a very slick little tool.

MyBatis is great if you know SQL well and you don't really plan on being a DB nomad. SQL is a fine language and MyBatis is a good way of making your SQL calls less ad hoc.

Sweet. Thanks. I suppose I'll keep on going with JPA until I've got something worthwhile to make less prototype-y.

Doctor w-rw-rw-
Jun 24, 2008

ComptimusPrime posted:

I don't use the IDE for source control. I use git proper. And NetBeans does not like the way it handles merging files.

I actually use git on the command line with EGit in Eclipse, and generally avoid using EGit altogether. Here's why:
* When I check out a different commit, EGit actually refreshes the files instead of giving me a screen telling me to refresh
* When I rename a package, it git mv's the files for me
* If something is conflicted - and stuff rarely is - it'll show up in the IDE, even though I always resolve it manually.

It works pretty great for me. For that matter, Eclipse has never given me any plugin troubles, because I avoid installing them as much as possible. Now if only Scala would auto-import for me like Java does in Eclipse (someone please tell me they added this in the last year, please)

Doctor w-rw-rw- fucked around with this message at 23:03 on Mar 9, 2012

Doctor w-rw-rw-
Jun 24, 2008

MEAT TREAT posted:

This sounds like stupid dogma to me. You're going to have to backup this claim with some examples.

Maybe referring to the use of the domain model pattern? Which, granted, I don't fully understand, and am not sure if I have a proper understanding of.

Here's my take: a parameterless function that is not static but which returns nothing presumably alters the internal state of an instance in a way that is totally opaque to someone inspecting it without source (or is completely useless). It also makes the object stateful, something which is best isolated rather than spread out, because it gets harder and harder to reason about classes and their behavior the more the lifecycle is distributed.

In this case I think SmallRoom should define a leave(Person person) method rather than leave() because the interface itself is limiting it to a single occupant, and if a third party, say, a bouncer, were to have power over ejecting people, you might want to give them an interface that allows them to do so without having to specify the type of establishment they were bouncing for, or give them full access to all of the establishment's functions, such as serveBooze(Person person) or something.

In any case, you might try:
code:
try {
    return occupant;
} finally {
    occupant = null;
}
to return the occupant then set it to null - if keeping a temporary reference isn't your thing. Also, the code that wrote:
code:
   Person copyOfOccupant = occupant; 
Is grossly misleading.That doesn't copy the occupant, it copies the reference, and is probably best named something like "tempOccupant" instead of "copyOfOccupant" as it's temporarily there to hold a reference.

EDIT: See for yourself what the try-finally block does. You can use it to do things after something is returned, though I wouldn't recommend making it something you do all the time.
code:

public class Test {
    static String x = "asdf";
    public static void main(String args[]) {
       System.out.println(x);
       System.out.println(test());
       System.out.println(x);
    }

    public static String test() {
        try {
            return x;
        } finally {
            x = "zxcv";
        }
    }
}
results in:
code:
% javac Test.java
% java Test
asdf
asdf
zxcv

Doctor w-rw-rw- fucked around with this message at 18:46 on Apr 6, 2012

Doctor w-rw-rw-
Jun 24, 2008

I am in posted:

I used think chaining mutators was a good idea, but the resulting method call chains are really hard to indent properly and a big pain to step into in a debugger.

It's good for builders, though. And the way Guice does it for module configurations is actually pretty nifty.

Doctor w-rw-rw-
Jun 24, 2008

1337JiveTurkey posted:

I tried this with a set of builder objects which were covariant on the type of the object that they're building and that type had a deep inheritance hierarchy for historical reasons. I tried chaining for the hell of it and came up with something that started off like this and just got more insane:
code:
interface ChildBuilder<T extends ChildType, B extends ChildBuilder<T, B>> extends ParentBuilder<T, B> {
    B setFoo(String fooString);
}

Wow. That's horrible. I just meant that it makes sense for like, simple POJO builders, not for complex processes.

Doctor w-rw-rw-
Jun 24, 2008

Thermopyle posted:

Yeah, they can recover. I'll just make something from Exception.

(I don't write Java much, so wasn't sure if there was a good provided exception for this)

I don't generally like checked exceptions. Not from a "does it work" or "does it make sense" point of view, but a "how much time do you spend doing exactly the same thing" point of view. I go with unchecked because I don't have to add a bunch of boilerplate or worry about it infecting interfaces. For example when there's no reasonable expectation of a JSON parsing error or IO error but I have to handle it anyway, I'm kind of just...blah. More catching, logging, and re-throwing wrapped in a RuntimeException anyways.

Not that my way is necessarily the only or best way to handle exceptions, though.

Doctor w-rw-rw-
Jun 24, 2008

Hidden Under a Hat posted:

I need to send software that I've designed and coded to Germany, and I'm wondering if there are any special considerations I need to take to make sure it runs the same on an international computer. My software makes frequent timing control checks based on time-of-day to control devices connected via sockets.

Yes. Use Joda Time if time values are important to your app. Do not use Java's date/time.

If you need to schedule periodic tasks then consider and evaluate Quartz rather than implementing your own logic. It's easy to embed.

Doctor w-rw-rw-
Jun 24, 2008

Pie Colony posted:

This isn't really a java question per se but it involves java. For a class project (the class is unrelated to concurrency) I'm implementing an algorithm that I want to be parallelized, but I'm not really an expert on the subject. I know the basics, but am interested in how to implement this in the most efficient way.

The algorithm is something like this (I've implemented a non-parallel version):

-------
There are 100 nodes divided into 4 groups.

At each iteration of the algorithm, the node calculates a direction and a distance to move. The direction can be calculated independently for each node, but the distance depends on the locations of all other nodes in the same group.

After each node has been evaluated, some number of nodes get thrown out of each group and replaced with nodes from the other groups.
-------

So I'm thinking of creating it in a master worker style, where 4 threads calculate the distance and direction, then the master does the switching of the nodes between each group. Would this be a good idea?
Writing the threads yourself might be too low-level, but this is a class project so it'll probably teach you something.

Consider using the Executor framework. Specifically:

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html

You could just have a thread pool managed by the framework, and have the runnables schedule their successors.

Or if you want to go full-blown overkill, use Quartz Scheduler with the in-memory task store.

Then mavenize it. :D

(I played around with Quartz recently and mixed Guice in for good measure too)

If you really want to get to know parallelization/concurrency better, read Java Concurrency in Practice. It's *the* reference.

Doctor w-rw-rw-
Jun 24, 2008

Helg56 posted:

stuff

I wonder if using FileUtils in Apache Common's io package might work better, if it's not overkill to pull the library in. It'll reduce your boilerplate there by a lot, I wager.

printStackTrace prints to standard error (stderr). I generally use a logging framework such as log4j or logback in order to log the errors, because then you can redirect the logging output to log files, or filter stuff out as you like. It's definitely a staple of Java development.

Doctor w-rw-rw-
Jun 24, 2008

Hanpan posted:

Does Java have any kind of event handling / dispatching ala Actionscript 3? I know it doesn't have delegates so the C# system I was hoping to port over won't work. The only thing I can find on Google is the ActionListener interface, but that seems to be specifically for Swing?

For reference, what I am trying to do is listen for events on a particular object. If I was coding a game, for example, I might want to listen for events for when the player jumps, takes damage or dies so the rest of my game can react accordingly.

Never used Actionscript 3, but EventBus (javadoc) in Guava might suit your fancy.

Doctor w-rw-rw-
Jun 24, 2008

Devvo posted:

What's a good book / set of online tutorials for learning Java if you already know how to program?

I'm a college student who knows C, C++ and Python, how to write object oriented programming for the last two, and I've taken a Data Structures class in C++. My curriculum was more mathematics based, so I've never touched Java. I'm not particularly interested in taking a Java class in the other computer science track at my university, mainly because they'll be focusing on beginner stuff, but that could be a possibility.

I'd like to learn Java (or C#, I guess) because it's the dominant language in the Real World, Android app development seems interesting, and I feel weird not knowing it when every other CS grad is fed with it.

I can't speak to any particular text for learning the language, since I mostly learned it through osmosis, but I can't stress enough how important it is to pick good tools to work with it. I would recommend Eclipse, and get to know it well (and rebind the Content Assist key to 'escape').

One thing that many people don't grok about Java is that programming it effectively is, essentially, computer-aided programming:
code:
New class.
private static final String FOOBAR = "BLAH";
private final Object someImmutableReference;
private Integer thisCanChange;

<ESC><*select the constructor from the autocomplete menu*><ENTER>
this.<ESC>s<*someImmutableReference*><ENTER> = <ESC><*someImmutableReference*><ENTER>
Eclipse warns that you're assigning itself to itself.<APPLE-1 or CTRL-1><ENTER>
Added as a parameter to the constructor.
Repeat for the other ones as you wish.
getS<ESC><ENTER>
Eclipse creates the getter for someImmutableReference.
setT<ESC><ENTER>
Eclipse can generate setters too.
<*right-click->Source->generate getters and setters*>
Eclipse can also do many at once.
<*right-click->Source->generate equals and hashCode*>
And make equals and hashcode methods
(important for the objects to be useful as keys in hashmaps for example)
<*right-click->Source->generate toString*>
And generate a toString for easier debugging.

End result: You only really had to declare the fields, but you now have a constructor, getters, setters, toString, and the object is ready to be put in a collection of some sort if necessary. You can even rename methods, variables, and entire classes and those changes will be effected globally throughout the project to anything else that refers to them.

Going back to what I said about books for teaching the language, I should amend that by saying that there are two books that are absolutely essential reading once you've got some footing with the language: Effective Java and Java Concurrency in Practice (the former being the most important IMO). These will give you clues on how to use Java well, but aren't exactly language books, per se. I think that Java itself is not terribly complex, but lends itself well to creating complexity (for better or worse) and hiding it behind abstracted interfaces.

Doctor w-rw-rw- fucked around with this message at 07:46 on May 9, 2012

Doctor w-rw-rw-
Jun 24, 2008

pigdog posted:

IDEA is even smarter than Eclipse when it comes to autocompleting and programming aides :)
http://blog.codeborne.com/2012/03/why-idea-is-better-than-eclipse.html

Not significantly smarter for me to pass on official ADT support for Eclipse, is what it boils down to for me.

Doctor w-rw-rw- fucked around with this message at 08:34 on May 9, 2012

Doctor w-rw-rw-
Jun 24, 2008

Honest Thief posted:

I recently received a Java project from a colleague that implemented a class diagram's relations with sets. By that I mean something like A -> B -> C means A will have a Set<B> and B a Set<C>.
I'm wondering if there's a better implementation of it, because when I need to, say, get C from A I need to do 2 chained foreach, and I wonder if that's a good thing to do, since it could grow out of hand.
Sounds like an object graph rather than a hierarchy. If this is so then you'll probably need to add WeakReferences into the mix, or risk incredible memory problems. Can you explain more?

And with WeakReferences, it could definitely grow out of hand in verbosity and error-checking.

What kind of thing do you need to implement?

Doctor w-rw-rw-
Jun 24, 2008

Honest Thief posted:

etc

for(Participation p : this.participation)
for(Team t : p.team)
for(Player p:t.players)
p.age .....yadda yadda....

etc

Well, seems reasonable to me, then.

fletcher posted:

I was using Eclipse for about 4 years and recently switched to IDEA. I don't think I can go back to eclipse now, everything in IDEA is just way more intuitive.
I've found the opposite, personally. Different (key)strokes for different folks, I guess

Doctor w-rw-rw-
Jun 24, 2008

fletcher posted:

Yeah it has search & replace, tons of refactoring tools, debugging tools, etc. I can't think of anything I used in Eclipse that IDEA (free edition) doesn't have.
Are you an Android dev? ADT is heavily tied to Eclipse and I'm skeptical that IDEA would have first-class Android support quite so extensive. It's a big deal to me, personally.

Doctor w-rw-rw-
Jun 24, 2008

Aleksei Vasiliev posted:

How do I adjust a date-time to a future time?

Say I have this date-time object:
May 31 2012 10:54AM UTC

How do I adjust its time portion to something like 10AM but have it go forwards, so I end up with June 1 2012 10:00AM UTC instead of May 31 2012 10:00AM UTC?
I'm really bad at calendar stuff so I have no idea what the hell.

I'm using the ThreeTen alpha builds but I can presumably adapt a JodaTime solution/similar to work with it.

A quick hack, and potentially the best solution, would be to replace the time portion of the date with 10AM, compare it to the old one, and if it's earlier, add a day.

See: http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html
withTime(...) and plusDays(1). Or withTimeAtStartOfDay() and plusHours(10) instead of withTime().

Doctor w-rw-rw-
Jun 24, 2008

MEAT TREAT posted:

I'd say that Java UI applications are a dead end to begin with.

Agreed, but if one *really* wants to do UI on Windows, then SWT is probably the toolkit to use (see http://www.eclipse.org/articles/article.php?file=Article-Understanding-Layouts/index.html for a small example). It'll look typically bland like most Java UIs.

There's also 'clutter' and java bindings for it, neither of which I have ever used, but if you're going to want an application to look good, Java won't help you.

Doctor w-rw-rw-
Jun 24, 2008

Mindisgone posted:

Is anyone familiar with google maps api using javascript? I am specifically trying to use the geocoder api and my code is as follows:

Javascript is this way.
PHP is that way.

Doctor w-rw-rw-
Jun 24, 2008

fletcher posted:

Finally got a core dump for that JNI issue I was having, some sort of bug in one of the libraries that the native code uses.

Had to do the following on Ubuntu 10.04 to get the core dump: http://chrisjakeway.wordpress.com/2011/12/09/ubuntu-10-04-enable-core-dumps/


On to a new issue! How can I store a java object in memcached that does not implement Serializable?

Marshal it yourself. Maybe try Jackson, and store that, or use the binary extensions if you want it to be more compact.

And dear god, if nobody's holding a gun to your head, stay away from Serializable on servers. You want uptime and upgradability, not corrupted objects because of version mismatches between objects.

Doctor w-rw-rw-
Jun 24, 2008

fletcher posted:

Thanks for the suggestions.

We use protobuf for some other stuff. There are tons of different objects from a 3rd party library that I want to cache so I was hoping to avoid writing/maintaining tons of message definitions, need to investigate this though. It's mostly metadata information from a SOAP API, maybe there is something I can do to cache the underlying XML? I wonder if it's expensive to be parsing all the XML over and over though.

It's CPU bound so if your workload leaves your I/O saturated or memory full, then you should be fine.

Doctor w-rw-rw-
Jun 24, 2008

Ranma posted:

Understanding poo poo like that is worth roughly $0. Understanding all that stuff and knowing how to properly structure programs, lead product development, and in general get poo poo done would net you a lot of money as a senior lead.

I think he wasn't talking about the value of the skill itself, but rather how much someone with his level of experience might be able to market his skills for.

Thermopyle posted:

I don't work in anything programming related, but out of curiosity, how much could someone make as a Java dev who understands as much as me?

Probably a question for another thread, but location makes a difference, and I have no clue how experienced a developer you are. Upwards of $60k for sure, possibly $70k or $80k+. And I'm lowballing for the Bay Area (but then, higher Bay Area rent will easily make the difference).

Doctor w-rw-rw-
Jun 24, 2008

trex eaterofcadrs posted:

In Chicago there's a ton of high profile Java firms and talent is thin, you could get near 100k here if you didn't suck and hung around for 4-5 years.

I was lowballing. It's more like 2-3 years if you're good than 4-5 years, in the Bay Area. I know people who make less and work in areas where cost of living is also much lower, so they enjoy a similar discretionary income level. But this isn't a programmer salary thread, this is a Java thread. Moving on...
---

Is anyone sad that Java 7+ improvements may never make it into Android, since the language is no longer especially "open"? Is Apache Harmony dead because of a legal reason, or just developer lack of motivation, because there's no open-source technology compatibility kit? Could an open-source suite of unit tests help (eventually, when it's comprehensive enough to be a credible test for completeness)?

Doctor w-rw-rw- fucked around with this message at 09:19 on Jul 30, 2012

Doctor w-rw-rw-
Jun 24, 2008

lamentable dustman posted:

50-60k in Atlanta. 85-110k after 5 years.

Welp, looks like salaries for Java programmers is sufficiently on-topic that others are still talking about it.

If you play your cards right, being new to the industry in the Bay Area, you can probably start at $80-90k as a junior software engineer, depending on how well you negotiate, how well you interview, who you work for, and possibly other circumstances. If you prove yourself, jump jobs with good timing, and gain the right kind of experience, you can be making $10-20k more than that in a year or two (aka: lucky as poo poo), then you'll want to stick around somewhere for a while and follow a track to go from software engineer to a normal software engineer, then become a senior software engineer.

On the other hand, you might also consider a different track, which is to build some recurring income from stuff you build and put out there, which will then give you the flexibility to choose a job that will teach you the most, which you can also enjoy, since your supplementary income might make the difference between not making ends meet and living very comfortably. It's a longer timeline, to be sure. but might be more satisfying.

Doctor w-rw-rw-
Jun 24, 2008

Tres Burritos posted:

Easiest way to parse xml? I'm this close to just using regexes.

Any library that gives you XPath?

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.

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

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

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.

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.

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.

Doctor w-rw-rw-
Jun 24, 2008

Sedro posted:

Guava's immutable collections are also very nice for creating defensive copies of collections and especially when working with constant data.

Seconding this and quoting it specifically to highlight this. Using Guava's immutable collections sends at least two strong, obvious messages: "this collection won't change" and "don't gently caress with this collection, even internally". It gives you a builder so you can clearly define the point at which the data is set in stone, and depending on your circumstances, the immutable collections are more performant than their mutable counterparts. There's no temptation to make some changes to a collection and hope something isn't trying to concurrently access, because modifying the collection involves swapping it out for a different one.

In general, though, I may be biased because I believe it is easier to reason about code in which the data can be relied upon to be static, and when you use immutability to good effect, you can reduce the surface area of mutable state for you to keep in mind when writing your code.

Doctor w-rw-rw- fucked around with this message at 00:38 on Oct 12, 2012

Adbot
ADBOT LOVES YOU

Doctor w-rw-rw-
Jun 24, 2008

Win8 Hetro Experie posted:

Making things actually immutable is a lot more work than deciding not to mutate things that should be immutable.

Guava makes it easy. And I can turn a couple of variable declarations into an immutable POJO within a minute, including a builder, thanks to code generation. Good enough for me.

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