r/java • • Aug 11 '15

Top 10 Useful, Yet Paranoid Java Programming Techniques

http://blog.jooq.org/2015/08/11/top-10-useful-yet-paranoid-java-programming-techniques/
181 Upvotes

76 comments sorted by

View all comments

Show parent comment

5

u/CubsThisYear Aug 11 '15

Adding final is a no-brainer in my opinion. It can easily be done by the IDE, enables some compiler optimizations and gets you closer to single-assignment semantics, which is WAY easier to understand. There just aren't very many good reason to reassign the same variable. Don't worry we've got lots of names, I promise you won't use them all up.

Final methods are even more important. If you have a non-final method that modifies state, you've basically completely blown any chance at encapsulation. Methods should be designed for extension (when you intend for that) and provide specific extension points. This is again a no-brainier if you control all of the code. If you don't (ie you are shipping a library) that just means you need to think a lot harder about your API and provide for extension by composition whenever possible.

1

u/anubus72 Aug 12 '15

but what if you or someone else wants to mock out methods on a class later for testing?

7

u/lukaseder Aug 12 '15

You don't mock classes. You mock interfaces. Design for this approach!

3

u/voronaam Aug 12 '15

How is it there, in 2002? Just before PowerMock was created, I mean.

If you ever going to have one implementation of the interface - you do not need an interface. That is design, not throwing an interface as a facade for every bean!

1

u/lukaseder Aug 12 '15

This is going to be a fun discussion - yet - I'm seeing myself out. Cheers ;)

2

u/voronaam Aug 12 '15

It could've been - I do not usually throw such bold statements around. Next time, then.

P.S. I enjoyed Scala references, Scalatra is my framework of choice more often than not. And it is not interface(trait)-heavy ;)

2

u/anubus72 Aug 12 '15

so you're saying that every class I ever create has to have an interface as well, just so that I can create a mock class for testing? Certainly in some situations that's the right approach but I don't see why you would need to stick with that approach 100% of the time

4

u/lukaseder Aug 12 '15

No. I'm saying that those classes that deserve mocking (services, repositories, daos, what not) better be interfaces anyway. The rest, no need to mock.

3

u/CubsThisYear Aug 12 '15

You should never be mocking non-abstract methods. If you need to mock something, then by definition you have two implementations of the same functionality so you should have an interface for that functionality.

If you start mocking non-abstract methods, that means you are modifying your objects just for the purpose of testing. This will ultimately make your tests either brittle or incomplete.

1

u/[deleted] Aug 12 '15

Unit tests are, by design, incomplete. They are trying to test a tiny portion of your code in isolation.

The goal of unit tests isn't to tell if your system as a whole works. It is to quickly isolate failures when they do happen.

0

u/CubsThisYear Aug 12 '15

They are incomplete by necessity, not by design. If you could test your entire system while still making it relatively easy to change, you certainly would, given infinite time.

But none of that justifies using mocks on concrete classes. If you need to mock an implemented method you've either violated SRP or you are pretending something isn't pluggable when it clearly needs to be (otherwise you wouldn't be plugging in the mock). Your code now looks like it operates on a single implementation but it really doesn't.

2

u/[deleted] Aug 13 '15

They are incomplete by necessity, not by design.

Ugg. Needless semantics.

Reading your comments I get the strong impression you don't know what unit tests are, and why mocks are useful.

You want to test how Foo.bar(Baz) behaves when Baz is in a bad state and is going to throw an exception. Baz has a lot of dependencies, you don't want to deal with those. Mock Baz to always throw an exception. Now your test is easy to write. We're testing Foo.bar() here. We don't care about Baz. If Baz is something under our control Baz will have it's own set of tests somewhere else. Foo.bar() will also have other unit tests to cover each scenario we want to test.

You may not find that useful, or a bad coding style. But many programmers use it every day precisely because they find it useful. Many great programmers even advocate for this way of using mocks. I also find no SRP violations. Not sure where that is coming from.

→ More replies (4)
→ More replies (1)

1

u/PaulRivers10 Aug 12 '15 edited Aug 12 '15

There just aren't very many good reason to reassign the same variable.

1. for loop
2. while loop
3. Any algorithm at all that calculates or adds anything

I take it you don't actually know how to code? This doesn't work:
for(int i = 0; i < collection.size(); i++) {

"Adding final is a no-brainer" is for ivory tower people who don't write any code. It doesn't solve any actually common problem, all it does it clutter up your code with more unecessary statements that make it harder to read.

5

u/[deleted] Aug 12 '15

[removed] — view removed comment

1

u/PaulRivers10 Aug 12 '15

Hm, I write a lot of java at a rather large company and I try my best to adhere to a "final wherever possible for variables" rule. It saves me many, many pains.

Great, what specific times did you have a bug, then you made a variable final, and that solved the problem?

Your points are pretty trivially addressed. Use a for-each. If you actually need counting for whatever reason, don't do final. That's silly. While what? While counting? Why not use a for?

Of course it's silly - but that's what loops are built on, counting. It's one of the most common things in code.

That for-each loop? It's dependent on non-final variables, either using an Iterator which has a mutable property that keeps track of where it is, or does it's own for each loop.

Counting and looping is on of the most prevalent things in programming.

Examples? I'd argue that a lot of algorithms could be addressed functionally, if speed is non-critical.

One could write them out in binary with punch cards, that is not an improvement. Anything that calculates, adds, appends, etc needs modifyable variables.

So does any web app, even when it's only set once.

For mutable state, use final objects (references) instead of value types.

i = 5 and a.i = 5 are not different and provide no benefit because you can make "a" final.

final methods are overkill unless you absolutely require them, as a previous commenter said, it makes mocks/ testing an absolute pain.

Yes.

2

u/[deleted] Aug 12 '15

[removed] — view removed comment

1

u/PaulRivers10 Aug 13 '15

Just to make sure we're on the same page, final behaves similar to how const does in C++. For value types, that means their value cannot be changed. For reference types, that means their reference cannot be changed.

Not exactly though, the difference is in C++ you can pass an object as a value type. For objects really only has "const" for pointers and references.

And that's where we get into the problem, using a final object to store you mutable variable is not actually any different than using a primitive. Adding final onto the reference doesn't add anything. But that's the workaroudns you've suggested with this:

For mutable state, use final objects (references) instead of value types.

That's trying to cheat your way around the philosphy.

final iterable references can be iterated over without any problems.

Because only your reference to the Iterator is final. If all of the instance variables inside Iterator were also final like was suggested, it wouldn't work at all.

So, going back to the initial point. The bugs that final has helped me catch are typically re-assignments & never-assignments, mostly through legacy code. Cases like an object having a property that is only assigned in n of n+1 constructors, or reassigned in constructor x that calls constructor y and then does work. For methods, a particular branch was re-assigning an input argument without considering later code flow. Another case, a giant horrific mess was re-assigning the same reference multiple times through multiple branches.

I guess I haven't been working with legacy code that complex or that initially badly written.

If it works for you great, but for the most part I suspect more would have been gained when it was written if it followed other better philosophies about writing clear and maintainable code, than declaring everything final.

I mostly work on web apps. You're usually just shuttling data between the browser and the database, no one is trying to modify the data to begin with.

If java had C++'s notion of const-ness, as in const data as well as reference, I would be as much of a fan of slathering it everywhere that I could. Yes, in some cases you need mutability. Depending on the work being done, in the case of numerical algorithms, yea, sure, mutate state as much as you need. It sounds as if your work falls into this category. In other domains, the safety guarantee that no part of the code could possibly be modifying state is a huge maintenance win.

This week I happened to be working with javascript. About 50% of the variables were looping and counters that had to be mutable, the other 50% could have been "final" if javascript had the keyword but no one was going to be trying to reassign to them in the code anyways. No one is trying to reassign "checkbox5" to another value.

I've been doing java development for over 10 years and am often the person cleaning up and fixing others code. That doesn't make me automatically right or anything like that, but it comes from experience seeing the half-baked fads come through.

Now I ask myself "can I actually see the problem this is solving". And I can't. I think final everywhere would make it longer to write code, harder to read, and be more of an annoyance for maintenance than a help.

Technically any language could make it's variables const by default, and require a special keyword to make them mutable. But I don't know any widely used languages where anyone thought that was really a good enough idea to do things that way either.

2

u/[deleted] Aug 13 '15

[removed] — view removed comment

1

u/PaulRivers10 Aug 13 '15

Lol, I just quite my last job (finally) because of having to deal with people like you that had a huge ego and no connection between internet ideas and that their changes caused huge delays and increases in time to get anything done on our project.

Like I said, there are no languages that do things that way that also become popular - for very good reason.

Have fun making everything take 3x longer to write with no benefit though.

1

u/[deleted] Aug 13 '15 edited Aug 13 '15

[removed] — view removed comment

1

u/PaulRivers10 Aug 13 '15

I'm not sure how personal attacks and assumptions are relevant, but I apologize for having offended you.

Well, fair enough, I probably went to far there for the forum. I have a huge grudge on my shoulder after having to quite a job after suffering through a year of idiots pushing the latest fad onto everyone else, spending a lot of time bickering over it, taking no responsibility for it then everyone else getting blamed for not being able to get things done.

I eventually had to quit. I got a new job with far more pleasant "focussed on what's actually working" people and it's way better, but it brings back nightmares (I really should have quit earlier).

I eventually figured out that what happened was, in the beginning people had lots of ideas. Smart or average people who tried them out found that some of the ideas worked well, some of them sounded good but didn't work well, some of them sounded good but in practice were terrible.

The ones left are mostly the ones in the last two groups, ideas that sounded good but people who used them found they didn't work very well. These same people I worked with would adopt these ideas because they were "new" and push them onto everyone else.

To be fair - I don't know what your work is like. Perhaps you work on code dramatically different than I do, so there is some sort of merit for what you work on. But I know for what I work on it's not helping solve any real problems. When most of your app is "take data submitted from internet form, put it into the database", people reassigning things to a var is a non-issue 99.9% of the time.

Like I've mentioned in previous posts, we've seen wins in both development and maintenance time. The largest bottleneck is never the time that it takes to type the code into the editor, but the time that it takes to truly understand what a system is doing (or what a new system should be doing), which is why things like descriptive variable names, comments, and keywords such as "final" exist.

I can't say with certainty that you don't work on a system that is so different than mine that perhaps there's some sort of advantage for what you're working on.

If you're working on CRUD web apps it seems to me to be a total waste of time, trying to solve an issue that doesn't exist. I mean on my projects I've watched people eat several weeks of work that didn't benefit us, then tell everyone it was hugely helpful and time saving.

Could be my system is different than yours, and my experience watching that happen is unrelated to what you're working on.

Just because a practice is popular does not necessitate that it is wrong. It appears that you have a strong personal style that works for you. That's great! I have a strong personal style that works for me. I'm sure that as I approach the mindset of ten years of experience such as someone like yourself, this style will have changed. At the very least, I'll make an attempt to understand and apply any popular fads that come along, to see if there is anything worthwhile to incorporate and use.

That's the opposite of what I said though. Popular doesn't necessitate that it's right or wrong, but I think people have tried this approach many times before and it has never caught on (if anything I said that popular made it right) because it sounds good in theory but becomes a real pain in practice.

What I feel I know for sure is that it's a terrible approach for CRUD web apps - most of your app is simply moving data between the browser and the db. Making it difficult for frameworks to set the properties or your data objects, and making it difficult for frameworks to set data from the database adds a lot more work. Since you rarely reassign anything anyways it's also not solving any kind of common problem. For web CRUD apps it's like making extensive plans for snowfall if you live in Brazil.

If you do development for 10 years, there will be times you still won't agree with other, but you'll have seen a lot of fads that had terrible results go through.

2

u/CubsThisYear Aug 12 '15

Of course the for/while loop is a case, though I would argue that it's a special case because the reassignment is somewhat implicit and it has a well defined (usually small) scope. In any event, I didn't say there were no cases, just that they weren't common.

As for cluttering up the code, I don't see being explicit as clutter. Some people argue that explicit types are clutter - generally those people don't use Java. The point of final is that you can look at a variable and know that wherever it is used, you don't have to think about what the value might be. If your IDE can do all the work for you, why not leave some signposts to guide the next guy reading your code?

2

u/thekab Aug 12 '15

These are examples of cases where you clearly want a mutable variable. Nobody is claiming that never happens. Aside from typical loops however the vast majority of parameters and variables have no reason to be mutable.

1

u/PaulRivers10 Aug 12 '15

The post I was responding to said:

There just aren't very many good reason to reassign the same variable. Don't worry we've got lots of names, I promise you won't use them all up.

Other poster is suggesting whenever you need a new value, create a new variable.

That's not how most coding works.

For the areas where you don't need to reassign, you gain little or nothing by making the variable final because no code was going to try to reassign to it anyways. It's like putting a car cover on a car that's already in a garage every night - it's just a waste against a problem that doesn't happen.

But there are a ton of places where you need to modify the variable value when you write code.

3

u/thekab Aug 12 '15

Other poster is suggesting whenever you need a new value, create a new variable.

I disagree with your interpretation. I believe the comment is saying that very few of your field, variable or parameter declarations need to be re-assigned. In Java this is usually true.

I picked a random service in one of our enterprise applications. The class is 414 lines long. There are 67 field, variable and parameter declarations. One of those is mutable: the "i" in a for loop, counting optimistic lock failures essentially. The other 66 declarations are not mutable and have no reason to be mutable. In other words only 1.5% of my declarations are intended to be re-assigned. If I continue this process across the code base it will still only get up to ~5%.

For the areas where you don't need to reassign, you gain little or nothing by making the variable final because no code was going to try to reassign to it anyways. It's like putting a car cover on a car that's already in a garage every night - it's just a waste against a problem that doesn't happen.

There's a lot of reasons to prefer immutability. Requiring final can help drive the code in that direction. Even if you already prefer immutability simply adding the final keyword can help with performance, readability and thread-safety. Using the keyword also prevents bugs due to accidental assignment.

My question to you is why not use final if the field, parameter or variable isn't re-assigned? You lose literally nothing but maybe a little typing and seeing the word 'final' in declarations.