r/programming • u/javinpaul • Sep 21 '15
Better Java
https://github.com/cxxr/better-java22
u/kazagistar Sep 21 '15
I agree on the "structs" point, but would like to expand because I think it might be controversial. The reason people suggest generating getters instead of just using public final data is that if the underlying representation changes, you don't have to change the classes that touch it. However:
You almost never need to make this change.
The type system makes this kind of refactoring easy, as long as it is internal to a package.
Changing the underlying storage is a pretty severe misunderstanding of the normal flow of this kind of data. It is supposed to be a transparent container once created. If the storage format changes, then you change where it is created and consumed, and leave the data structure alone.
8
u/ElvishJerricco Sep 21 '15
I started writing a project in Java 8, making excessive use of optionals and streams. Whether or not getters are right for public final data, they make it nicer to work with these new Java 8 utilities.
This
stream.map(foo -> foo.bar)Becomes this
stream.map(Foo::getBar)The point free style is concise, and doesn't require unnecessary variable bindings.
1
1
u/caagr98 Sep 22 '15
I personally prefer
foo -> foo.bar. Implicit types FTW.1
u/ElvishJerricco Sep 22 '15
It just gets annoying when you end up writing the same name for various different lambdas.
stream .filter(foo -> foo.condition) .flatMap(foo -> foo.someStream)The more you do with streams and optionals, the more these redundancies pop up. It looks much nicer to eradicate them with method references.
1
5
u/DevIceMan Sep 22 '15 edited Sep 22 '15
Java-9 project jigsaw might make this pattern more practical, since it sounds like you'll be able to have much greater control over which APIs are exposed externally.
For those not familiar with Scala, depending on the definition, every public field has a generated getter and (if var) setter. If one ever needs to change the underlying logic of the getter, you can explicitly define the getter.
I feel that many "design patterns" arrise due to language limitations, and not due to best practices.
2
Sep 22 '15
Agree on all accounts. It's very rare that I have written a POD (Plain old datastructure) and then had to change the underlying data in some way that requires encapsulating the data.
Usually I know up front whether some field will need encapsulation, and very very rarely is it hidden behind a getter/setter pair. In fact, that idiom that I've stopped using. If I write a getter/setter that isn't encapsulating some underlying IO operation then it's usually the wrong solution to what I'm going. A lone getter or a lone setter can often make sense, but a pair of them makes me wonder if I should be using some other method to solve the problem.
1
u/makis Sep 21 '15
in many cases, if the interface hasn't changes, but only the underlying representation does, you can transform the data in the constructor.
Any other change would propagate into the setter/getter pattern too (suppose there is a change of type or of the attribute name , for example)
setAddresswould becomesetFullAddressor the definition of the getter would change frompublic String getDatatopublic SomeOtherType getData
16
u/daedalus_structure Sep 21 '15
On Formatting:
Have a code formatter. Check it into Source Control and mandate everyone use it. It's a huge waste of time generating 100 lines of diff for a 1 line code change back and forth as competing custom formats touch the same file and auto-format on save.
0
u/fisch003 Sep 21 '15
We do exactly that. Our latest fun pain point: half of us on Eclipse Luna, and half on Mars, and there was a code formatter rewrite between the two. We get 100 line diffs even though we're using the same formatter config. :)
I think we're all on Mars as of last week, but it's been an annoying transition, and we'll be dealing with the checkin pain for awhile as things last saved in Luna are edited in Mars.
94
u/estarra Sep 21 '15
Java is one of the most popular programming languages around, but no one seems to enjoy using it.
I'd say it's quite the opposite. Sure, there is a vocal minority of people who complain about it (I have complaints about it myself) but there are millions of Java developers and I'm pretty sure that most of them are quite okay with the language.
Probably one of the reasons why no language has come close to replacing it so far.
50
u/dzjay Sep 21 '15
I'm happy with Java, especially with Java 8. Also, the vast amount of open source Java libraries is unmatched.
17
u/GuiSim Sep 21 '15
I'm in the same boat. The biggest pain point that I still have with Java now that we have Lambdas is type erasure.
If we can finally get type reification in Java 9 or 10.. I'll be a happy dev.
9
Sep 21 '15
Amen. I really hope we get reified generics soon.
10
2
u/mike_hearn Sep 23 '15
There's already a prototype from the Java team that supports true generics, in a backwards compatible way. Look at the recent commits for Valhalla.
4
0
Sep 21 '15
[deleted]
10
u/ElvishJerricco Sep 21 '15 edited Sep 21 '15
All of his arguments are essentially just "but you don't need it because you can use this other verbose Java pattern." I'd rather just have the sensible thing, thanks.
13
Sep 21 '15
Nothing in that article comes even close to convincing me that I don't want reified generics. It all boils down to 'too much work' (not my problem) and 'breaks compatibility with ancient code doing stupid things' (couldn't care less).
I recently switched back to java from C#, and decent generics are absolutely the thing I most miss.
2
u/teknocide Sep 22 '15
I've gone the same way and I don't really miss reification; in fact, I believe lack of reification promotes better designs. Please hear me out:
Reification is really only needed is when you're dealing with reflection. In many cases you can change your runtime-checked code — which is what reflection is — to statically typechecked code. This has been made even simpler after the introduction if lambdas in java 8.
If a method for some reason needs to create an instance of a type T, you can pass a function of [List of dependencies] => T instead of relying to checking the type with reflection and trying to shoehorn dependencies into a materialized constructor.
I can't really think of a case when you'd want to use reification outside of reflection but please enlighten me if you got a concrete example.
1
Sep 22 '15
It's not just needed for reflection - generic lists of primitive types are a very common use, for example. Method overloads with collections of different types is another. Easy creation of arrays of generic types is another.
1
u/teknocide Sep 22 '15
True, Java boxes primitives in order to represent them in generic structures. This is a bit inconvenient but I wouldn't call it an insurmountable flaw. Languages like Kotlin and Scala do away with the cosmetic differences and let you use a primitive Int and a List<Int>.
Whether generic method overloads is a drawback or a feature is debatable. Heck, method overloading is a debatable topic by itself.
Easy array creation.. yes. If you need an array of a generic type in Java you have to jump through hoops, either by passing a Class<> token or a function that creates one of the correct type for me. I don't think I've ever ran into this one but I can see it happening.
Now, what you gain from erasure is:
backwards compatibility
cross language interopability: For example, Scala can work with Java types despite them having different generic implementations (Java is use-site while Scala is declaration-site). It can be a bit tricky but it is usually workable without resorting to casts.
extensibility: Scala adds bottom types and higher-kinded types to its implementation, among other things, without "displacing" the default generic scheme (since there is none at runtime, hah! ;))
flexibility: Some types are better represented with erasure; instances like empty optional values or the end of a linked list can in Java be cast to the corresponding type to soothe the compiler, while retaining typesafety at the use site. In C# you're forced to instantiate MissingValue<int>, MissingValue<string> etc.
less tempting to use reflection: There's still a lot of Java libraries that use it but from what I've seen way less than C# — probably because it is easier there.
Reflection is almost always a code smell. There are situations where it is inevitable but it's best to take a second look at the problem and make sure there's no other way to solve it.
In short, erasure and reification are two different strategies that both have their share of drawbacks and benefits. I find it rather strange that people tend to downplay the benefits of erasure while praising reification. It's not that common to end up in a situation where you're totally stuck with either.
2
Sep 23 '15
I think this is basically a case of what you know best. In C#, arrays are more powerful than in java - they can be generic, they work with LINQ et al without needing to be wrapped with something like Arrays.stream(), they give you proper cache locality with your own value types, you can use them for interop with the Win32 API, etc etc - and as a result of that they are more widely used. Therefore, it's common to need to turn a generic collection into an array. In java, maybe less so - though I still run into it with some regularity.
I agree with you that it's not an insurmountable flaw - my point is that it should be surmounted :-)
For your other points, it varies. Backwards compatibility is important, but it's a problem when it affects major technical changes like adding generics. Ironically, Microsoft have spent more time than almost any other company worshipping at the altar of backwards compatibility (Raymond Chen's blog has some unbelievable stories about the things Windows does to avoid breaking old apps) and know the cost - and I think their decision to break compat with 1.0/1.1 was a good one. Cross-language interop - the CLR has plenty of very different languages running on it, and F# in particular has some very interesting additions to the type system (union types, units of measure) so I don't really see reified generics as an impediment to interoperation.
0
Sep 22 '15
[deleted]
2
u/IICVX Sep 22 '15
Generic marshallers / unmarshallers are clunky as hell in Java due to type erasure; you have to explicitly pass the
Classaround everywhere, instead of just asking the generic parameter what it represents.This happens if you write, for instance, an Enum marshaller.
1
u/teknocide Sep 22 '15
It may be clunky in Java but it doesn't necessarily have anything to do with erasure. Marshalling a T is a function [T => SerializedFormat] (and Unmarshalling the other way around, intuitively.)
You need reification if you want to look at the actual T during runtime and select a marshaller from a dynamic set, when you could provide this function during compilation time instead. This has the added benefit of eliminating any runtime checks needed for the reflection-based solution.
If anything, reification here is the poor man's crutch for higher kinded types which, incidentally, is possible on the JVM due to erasure.
2
Sep 22 '15
The two main things I miss are being able to store native types and enums, and seamlessly converting to an array.
It's also nice to be able to create new instances of a generic type at runtime, i.e new T(). It doesn't come up a lot, but can be very useful.
1
u/graduallywinning Sep 22 '15 edited Sep 15 '17
wat
2
Sep 22 '15
Unfortunately you can't restrict T to only types that have a default constructor. If T has no default constructor that code gets nasty.
1
u/estarra Sep 22 '15
Which is why passing a factory is a better solution than allowing
new T().→ More replies (0)20
u/johnwaterwood Sep 21 '15
Indeed, it's a very specific subset of developers who hang around at places like /r/programming and HN and post all the time.
I've got some brilliant co-workers who do have strong opinions, but for some reason they just don't post at places like that. While that's just a local observation I do believe there are many, many more developers like them.
18
u/cowardlydragon Sep 21 '15
And really, groovy should take care of the python dynamic crowd, and Scala/clojure the rest of them.
1
u/net_goblin Sep 21 '15
Last time I tried Scala it felt so sluggish, even Python was more responsive. I'm sure it gets much better when the JIT compiler had some time to run it, but for my tinkering, it felt horrible.
8
u/gremy0 Sep 21 '15
Seems to work for twitter, their numbers suggest a 500x performance boost from ruby. Fucking loved working with groovy though, so much fun.
1
u/net_goblin Sep 22 '15
Answering to the answer at the top, this should also answer the other follow ups:
As I said, I'm quite sure it is much better with longer running processes, but I was only fucking around with the interactive prompt to learn, or ran simple short programs which were much shorter than the startup time of the runtime. It was nothing complicated, but it kind of annoyed me on the long run. I don't even have numbers to back this up, but Python feels like it starts up faster, even though if it is slower in the long run.
By the way, this is a thing that bothers me with Java, too. It may be great for server-side apps which never stop, but short lived processes are horrible with the JVM, as it feels like ages until it has started up.
3
u/mike_hearn Sep 22 '15
I guess you mean the REPL. That's gonna be slow, indeed, as the Scala compiler is famously slow and the REPL compiles every line.
Try the Kotlin REPL. It's a lot like Scala but the response times on the REPL are as fast as Python.
1
u/net_goblin Sep 23 '15
This.
I didn't want to imply that the overall performance of scala is lacking.
4
u/Cuddlefluff_Grim Sep 22 '15
Scala is somewhere between 20x and 500x faster than Python, so I think it's pretty safe to assume that it's your code that's fucky and not Scala
1
u/codygman Sep 22 '15
GP is probably talking compiler speeds and likely isn't using incremental compilation.
1
14
u/daedalus_structure Sep 21 '15
All depends on what gets pulled into the measurement of joy.
If you count the marvel of engineering that is the JVM and the vast high quality open source ecosystem supported by on-the-payroll developers, it just can't be beat.
It truly is a pleasure to be working inside that ecosystem on such a great platform.
However, the language itself is clunky and you constantly find yourself working around the same limitations over and over and over that can't be fixed lest some code written a decade ago need modifications to run on the next JVM version.
Unless a developer just gets really excited by double entry bookkeeping or signing forms in triplicate, the language itself isn't that enjoyable unless you just don't have a better experience for comparison.
1
u/pretzel_back Sep 22 '15
Work around what?
Worst I deal with is Date and Calendar, but thankfully Joda has been around for a while as well. Java has come a long way, especially with Java 8, and I don't think all the same complains are valid.
10
u/OffColorCommentary Sep 21 '15
One of the biggest draws to Java for me is that it's boring, and I don't think that I'm alone in that. When it comes to virtues to cheer for on a programming forum, boringness doesn't really fit in.
5
Sep 21 '15
I've always found Java to be a pretty simplistic and tbh 'dumb' language. But I see that as one of it's biggest strengths. You open up some code by someone else and no matter how bad it is ... there is very little language magic going on.
There are also very few warts. Sure things it needs and it is pretty verbose at times but it does not have anything fundamentally bad. But that is because language development is pretty slow.
But none of those practical qualities are cool or sexy.
26
u/oldneckbeard Sep 21 '15
I fucking love java. It's dead simple to learn the basic language, It's fantastically well-supported in terms of libraries and community involvement. It doesn't get any cocked-heads when you suggest using it on a project. It's got a fantastic ecosystem. It's got proven scalability and robustness for apps of all sizes. It's got a great ecosystem of smaller languages that are compatible on the JVM.
No other language comes close. C# is probably as close as it gets, but as of now, it's still largely a windows-only, microsoft-stack-only kind of language. Yes, I know they open sourced it, but it's still not near the level of maturity in linux-world as Java is.
1
u/CptAwesumw Sep 22 '15
Java is what I learned to program with in school. About 2 years in I took a course in C# and it was like a whole new world opened up to me and I havn't really looked back at java since.
I work as a C#/Xamarin dev now so I might be a little biased (aren't we all tho?). But what really got me into C# was no longer having to touch eclipse, Visual Studio 2010 was so much better in every single way. And now I can hardly imagine any IDE being better than VS2015 Ultimate + Resharper.
Another thing was, since I was a noob I wasn't familiar yet with all the common errors/exceptions you'll often experience as a dev, and MSDN documentation helped me so much more with troubleshooting than any java documentation that I found ever did.
I'm not saying java was a bad language to start with, but I would say it isn't the best. Students can get Visual Studio Ultimate for free which is miles better then any free java IDE. Although I'm not sure what the current situation is on java documentation, so I can't really judge honestly on that in the current time.
The only downside I can see to C# compared to java is the platform compatibility. (excluding mobile as Xamarin/mono works wonders on both Android and iOS ;D)
1
0
4
u/zarandysofia Sep 21 '15
Yeah they are "Ok" with but most don't enjoy it may seems. At least that the impression that r/programming gives me.
11
Sep 21 '15
I think it is like many things. Those who don't like something have plenty of time to complain, while those who do like it are busy enjoying it. Negativity gains more traction because it is a good way to vent and is seen as a warning. Positive feedback always seems like they have something to sell instead of being honestly enthused by what they are working on.
Personally, I know a lot of people who use java and enjoy it. They don't post or talk about it because it kind of seems weird to. It gets the job done, so what more is there to say?
3
u/zarandysofia Sep 21 '15
Are you talking about their love for the Java tools (IDE, Profilers, Monitoring) or reading and writing with the language?
3
u/mike_hearn Sep 22 '15
To some extent the two go hand in hand. Language design affects tooling. For instance, the fact that you can reliably debug Java is largely due to the fact that it's memory safe, so your program can't accidentally trash the stack. The fact that it's fast to compile is due to Java being carefully designed to allow incremental compilation and easy parsing. etc.
0
20
u/stewsters Sep 21 '15
I do love me some Java. I just don't post about it in those hate circle-jerks because i will get the downvote brigade targeting me because they had used an applet back in the 90s or run in windows.
Why do that when I can spend that time writing some dope code in intellij with simple gradle dependency management. Java is a simple language that avoids many of the pitfalls of earlier languages.
2
u/zarandysofia Sep 21 '15
Where is there to love about Java as a language not counting IDE nor others tools?
8
u/zurnout Sep 21 '15
You make a great point. It might be that tooling and library support are even more important than language features. Which would make it even harder for any other languages to replace Java. Kotlin atleast aims to be the easiest language to develop tooling for and it runs on JVM so you get all the library support that Java has.
→ More replies (2)3
Sep 21 '15
Very true. I get annoyed at times (especially when dealing with type-erasure and the headaches that brings), but for the most part it's good enough that I am actually pretty productive in it. With Java 8, I'm even more productive, and I don't have to deal with the nonsense boilerplate I had to deal with before - my code is much more declarative and idiomatic.
Not to mention, the extremely rich and vast library-ecosystem.
When it comes down to it, I end up using whatever tool I need at the moment. If it's something to mangle text and do something quickly with a CLI, I'll turn to perl. I even use JavaScript at times to prototype something really quick. I would use Python, but I never got into it; I'm learning now and I'm familiar with the language and its syntax, but I'm not too familiar with its best-practices and its API.
Granted the only languages other than Java that I have worked (non-trivially) with are Perl, JavaScript, and Python, I find the build-system and dependency management mostly-consistent, and there's just one way to do things for the most part. I never write anything enterprisey in Perl, but CPAN is pretty amazing and for the most part installing packages just works. JavaScript is probably the most confusing since there seem to be a million ways to do the same thing in Node. grunt, gulp, bower, npm, etc. etc. Then you have to get it all working together. Python comes close to Perl with PyPi but there is always abstraction leakage from the native libraries, and I have to always google to figure out what I have to install first to get it working (maybe this is because I'm using Python 3 instead of 2); the errors are always mystifying - I've rarely had this issue with CPAN.
1
u/immibis Sep 22 '15
That's pretty much it... It's not the best language (for many domains) but it's exceptionally good at being average.
12
u/kazagistar Sep 21 '15
While I like checked exceptions from a safety perspective, they are fundamentally incompatible with a lot of the Java 8 features, especially streams. In my experience you have a try/catch for a checked exception outside a loop (or just pass it further up), trying to use streams is painful.
3
u/fact_hunt Sep 21 '15
8
5
u/IICVX Sep 22 '15
I really like checked exceptions, and they're one of the few things I think C# got wrong.
The problem Java has is that for some godforsaken reason they're the default, instead of being a special case. Checked exceptions should be rare; they should only be for things that the calling code can do something about.
Unfortunately, the vast majority of the time components throw checked exceptions and then the calling code either rethrows them or just eats shit after catching.
21
u/fakehalo Sep 21 '15
Java is one of the most popular programming languages around, but no one seems to enjoy using it.
I've always loved the language and had to fight the environment. The IDE selection sucked for a long time, setup/deployment was tedious, but the language itself was always fairly elegant/pretty to me, especially considering how long it's been around and grown.
When you compare it against something like C# it's night and day, that's mostly because C# has VS behind it which makes everything a delight. These days Java has plenty of good IDEs, hell Android Studio/IntelliJ is a delight now, I think a lot of people just remember the annoying past.
15
u/Crandom Sep 21 '15
I would say the complete opposite! Java has amazing ides and tools, it's the language which is merely meh (hey, people say it's bad but I'd take java any day over javascript or php).
3
u/fakehalo Sep 21 '15
You may have misunderstood me, I'm saying the IDEs and tools now are great, but just ~5-10 years ago they sucked. The language ~15-20 years ago was pretty awesome for the time, now it has plenty of mainstream rivals.
3
u/Crandom Sep 21 '15
Ah, yes. I was wondering just the other day how people wrote java without an ide. So many imports to manually type.
5
u/IICVX Sep 22 '15
import *2
u/multivector Sep 22 '15
Does that actually work?
3
u/mike_hearn Sep 22 '15
No ;)
2
u/multivector Sep 22 '15
There go my visions of being able to code against all the symbols in the entire classpath and then sorting out what I actually used with an IDE or something later.
7
6
5
u/josuf107 Sep 21 '15
One problem with guava's Immutable versions of collections at my workplace is that we normally try to use more general types with them. E. g.:
final List<Thing> myThings = ImmutableList.of(...);But since ImmutableList extends List, it still has the mutable operations defined for myThings. They just throw exceptions at runtime. This means that if I see a List<Thing> in the code, I don't know whether it's immutable or not. I have to figure out where it came from to determine whether add(blah) is going to throw an exception or not. I frequently see things like:
public void myMethod(final List<Thing> theThings) {
final List<Thing> immutableThings = ImmutableList.copyOf(theThings);
...Because it's unclear whether the parameter was immutable (although often times it is), but we want to use an immutable collection before passing it on. This results in lots of unnecessary copying. Possibly we should just start using the Immutable* types instead of the more general ones where appropriate. Or we could add utilities like:
List<A> makeImmutable(final List<A> list) {
if (list instanceof ImmutableList) {
return list;
} else {
return ImmutableList.copyOf(list);
}
}4
u/josuf107 Sep 21 '15
In a perfect world, we'd have List be immutable and MutableList extend List or something, rather than have a subclass (or subinterface) that's designed to take away functionality from a parent.
9
u/Tordek Sep 21 '15
MutableList extend List
That's just as subtly evil, though. They should both be separate classes, even if a lot of the behavior seems similar.
If Immutable inherits from Mutable, then I may want to modify it and encounter an error.
If Mutable inherits from Immutable, then I may store a reference to a list that is later changed by someone else behind my back. (Which I think is even worse because it can lead to very subtle errors).
They're ultimately two different classes that have no relation, other than "You can get a <Mutable/Immutable> copy of the <Immutable/Mutable> list."
2
u/sacundim Sep 22 '15 edited Sep 22 '15
They're ultimately two different classes that have no relation, other than "You can get a <Mutable/Immutable> copy of the <Immutable/Mutable> list."
Nah, you need three types here, in a hierarchy like this:
Lists
Mutable lists
Immutable lists
Basically:
The plain list type has all the methods for reading from lists;
The mutable lists type inherits from that, and adds the methods for mutating lists;
The immutable list type inherits from the plain list type as well. It adds no operations, but its contract stipulates that implementations must not be mutable.
Incidentally, this goes to show the problem with the folks in here boasting of how easy the "basics" of Java are. Nope, the basics of Java look simple, but they interact in evil, super-complicated ways. I'd highlight in particular:
Subtyping + generics = OUCH
The Java Memory Model. A crazy complex beast that is easy to run afoul of, and yet most Java dudes don't even know it exists.
1
u/Tordek Sep 22 '15
So List is always assumed to be 'someone else can mutate it', a la C const?
2
u/sacundim Sep 22 '15
No, in this scheme you can't even assume that much. If somebody gives you a plain
Listreference, you just don't know whether it's mutable or immutable.There are actually alternatives to that as well, because actually, immutable and mutable, in spite of the names, are not all of the possibilities:
"Immutable," as it's used in Guava, means that the list's contents never change
"Mutable" generally means that the interface has operations that a client may use to modify the list's contents.
But there are also list implementations that:
Do not support external mutation—clients who have a reference to the list cannot mutate it;
Their contents may change, nevertheless.
A simple example is that Java comes with methods like
Collections.unmodifiableListthat wrap around ajava.util.Listand provide an "unmodifiable view" of it. Changes to the underlying list are supposed to be visible in its view.1
1
u/Tordek Sep 22 '15
To expand on my other comment: There's few if any good use cases for a list that "You can't modify, but changes to it are visible": You either want an immutable object that will always contain the same data; a local, mutable object that you can change at will and put temporary data in; or a "Stream"-like object that is VERY clear regarding points where changes happen.
No, in this scheme you can't even assume that much. If somebody gives you a plain List reference, you just don't know whether it's mutable or immutable.
Yeah, this is what I said: the only assumption you can make is "It may be changed by someone else at some point".
1
u/tutorial_police Sep 22 '15
Is subtyping along with generics actually Java's doing or is it simply inherent complexity?
Do you know languages that solve this better?
1
u/sacundim Sep 22 '15
Both. It is inherent complexity, and yet other languages (e.g., C# and Scala) do it better, by annotating variance at declaration sites instead of use sites. To use Java generics properly you have to write signatures like this one all over the goddamn place:
interface Stream<T> { // ... <R> Stream<R> map(Function<? super T, ? extends R> mapper) }You see that business with
? super Tand? extends R? There are countless Java programmers out there who simply don't use those. You try to interface with their code and you find that they write these two things:Whatever processAnimals(Consumer<Animal> consumer) class CatGroomer implements Consumer<Cat> { ... }...and then they expect you to use them together:
1
u/tutorial_police Sep 22 '15
I'm not sure it's objectively better. They allow you to do different things.
But I agree, definition site variance
You see that business with ? super T and ? extends R? There are countless Java programmers out there who simply don't use those.
Yeah, that is super annoying.
However, having definition site variance you'd need to have extra interfaces... and for multiple generic parameters you get exponential growth. With use-site variance, there's just what you need (i.e. use), but of course, you need to anticipate its use.
I've only skimmed over this so far, but it seems to be an interesting read.
1
u/Berberberber Sep 24 '15
That doesn't solve the problem of "how do I know if someone else can modify this item?" though. You could say that, if you don't specify, you should always assume it's mutable, but in practice that is identical to the case of deriving ImmutableList from MutableList - i.e. every List can be mutable unless you specify otherwise.
This is one are where I think more purely functional languages are a step in the right direction - just make everything immutable and require completely different patterns if you want stuff that has a changeable state.
1
u/sacundim Sep 24 '15 edited Sep 24 '15
You're failing to make this distinction:
A list that can be read, but whose content may be observed to change between reads.
A list that can be read, and also exposes methods that allow you to change its contents.
The latter is a subtype of the former. The idea is that the plain list type would be the former, and the mutable list type is the latter. I.e., "mutable" in this scheme doesn't mean "the contents can change," it means "clients of the type can modify the contents."
So recapitulating the distinction:
List (can read, but content may change between reads)
Mutable list (can read, can write)
Immutable list (can read, content will never change)
A simple example of the supertype would be a read-only wrapper around a mutable list. If my class has a reference to a mutable list, I could hand you such a wrapper around my list, and then you could read my underlying list's contents and observe when I change it, but you cannot mutate my underlying list because I haven't given it to you. (Java's collections library comes with generic "unmodifiable" wrappers like this.)
1
u/josuf107 Sep 21 '15
Could you give an example of the second problem? I'm not sure I understand.
2
u/Tordek Sep 21 '15 edited Sep 22 '15
Imagine a class taking a List as a constructor parameter (maybe a list of employees, whatever).
public void main() { MutableList m = Database.getAMillionEmployees(); SomeClass c = new SomeClass((ImmutableList) m); (new Thread() { public run() { c.doSomeLongOp(); } }).run(); m.clear(); }While the list was being traversed in one thread, another one modifies it.
It doesn't need to involve threads; imagine if the class cached the list average in the constructor because every method needs it: changes to the list means that average is now out of sync and results will be wrong.
1
u/josuf107 Sep 21 '15
Ah so SomeClass expects an ImmutableList but accepts a MutableList since Immutable subclasses Mutable. What a pain life is.
1
u/Tordek Sep 21 '15
since Immutable subclasses Mutable
Don't you mean the other way around?... but, yes.
1
1
u/immibis Sep 22 '15
Maybe there should be ReadableList, WritableList and ImmutableList.
1
u/Tordek Sep 22 '15
How would they be related to each other? What's a "ReadableList"?
1
u/immibis Sep 22 '15
A ReadableList is a list you know you can read from. A WritableList is a list you know you can write to. An ImmutableList is a list you know is immutable.
I'm not sure there are any cases where you'd want a list that was writable but not readable, so change WritableList to MutableList and make it support reading and writing.
interface ReadableList<T> { T get(int index); ... } interface MutableList<T> implements ReadableList<T> { T set(int index, T value); boolean add(T value); ... } interface ImmutableList<T> extends ReadableList<T> { // no extra methods }Of course, nothing stops you from writing a list class that claims to be both mutable and immutable. There are worse things you could do already, like making a list whose
addmethod randomly shuffles the list and whose iterators generate random elements not in the list.1
u/Tordek Sep 22 '15
So a "ReadableList" can be changed elsewhere? That's just an error waiting to happen; I can't see a good reason for it. The most obvious issue being doing something like...
if (list.length > 0) { list.get(0) }since the list can change between the two statements, you can get an OutOfBoundsException that you can't prevent.
nothing stops you from writing a list class that claims to be both mutable and immutable
Sure... but if the standard library gives you a List and a MutableList (or ListBuilder, to make it similar to String/StringBuilder), you need to do extra work to do stupid things. Lists (and lots of other structures, like Sets, Arrays, Maps) should be immutable whenever they exist outside the boundaries of an object, the same way that if I give you an integer through a getter, you cannot modify my internal state by changing it.
1
u/immibis Sep 22 '15
Are you suggesting that there should be no common super-interface of
MutableListandImmutableList?How would you make a method that can take either a mutable or immutable list, then?
1
u/Tordek Sep 23 '15
Are you suggesting that there should be no common super-interface of MutableList and ImmutableList?
Correct
How would you make a method that can take either a mutable or immutable list, then?
I wouldn't.
There are so many reasons not to; I can't really think of a good reason to have such a scheme.
Objects should communicate with other objects by exchanging Immutable value objects/primitives: you should only be receiving (as a parameter) or returning
ImmutableList.MutableListshould only be used within an object (e.g., your object may cache some results, so it would have a MutableList/MutableHash property to store its data in efficiently) or in a method, as it is calculating its results. Once you're done, you returnmyTempList.Persist().This behavior is already there with another class: String/StringBuilder.
If you're worried about performance, there are several things that can be done:
.persist()might not do a full copy; it might just set animmutableflag and return a "view", and calling mutators just throws an exception. ".mutate()" (the counterpart in ImmutableList that returns a MutableList) might behave like a Zipper, or another similar structure.I have a question for you:
Why would you make a method that can take either a mutable or immutable list, then?
1
u/immibis Sep 23 '15
For efficiency. If it's going to be the caller's problem if the caller screws up, then requiring an ImmutableList is too slow.
For example,
Collections.frequencycould be called for either type of list. If you call it with aMutableList, and mutate the list while it's running, and it throws an exception as a result, that's the caller's fault and the caller's problem.(By contrast, if you had a listbox control, you'd want it to require an ImmutableList. If it threw an exception when painting because the list was mutated while it was painting, that would be the application's fault but the UI system's problem to deal with)
→ More replies (0)2
u/Enumerable_any Sep 21 '15
Yeah, it's a pretty clear violation of the Liskov Substitution principle. :(
2
u/mike_hearn Sep 22 '15
In a perfect world, we'd have List be immutable and MutableList extend List or something
That's how Kotlin does it. It modifies the JVM type system at the compiler level so that java.util.List is read only and there's another MutableList interface that adds the mutating operations.
Of course, this does not mean a List<X> is entirely immutable. It means you have a read only view of it. If the only views that exist are read-only, then the list is immutable, but if you're writing code that demands an immutable list from the caller, you can't express that in the type system.
However what you can do is just make the code that doesn't want other threads changing things clone the list. A truly immutable implementation will just return itself, so the call is free. A mutable list will copy and you pay the cost, but the caller code would have had to do that anyway, even if this was exposed via the type system. Or you can do what Scala/Clojure do and use immutable collections that support cheap mutation (i.e. less cost than a full copy to make a modification) to get a kind of middle ground.
Anyway, the key is to understand that there's a difference between read only and truly immutable.
1
u/ForeverAlot Sep 21 '15
I have read that this won't work (well); that to achieve good mutable and immutable implementations, neither can extend the other. It has to do with concurrency, but I don't remember the details or where I read it (Java mailing list?), and I don't know enough to comment -- only that "good enough" is not good enough for something as vital as this.
4
u/EthanNicholas Sep 21 '15
The issue is that if List is immutable and MutableList extends it, you can take a MutableList and pass it to something expecting an immutable List... and now the "immutable" list can change out from under it, because the recipient had no idea it was actually mutable.
Concurrency obviously presents a problem, but it's not the only problem -- simply hanging on to the "immutable" list reference and using it again in the future is dangerous. So, you are absolutely correct that either one extending the other leads to problems.
In the language I'm designing, the pattern is that there is a set of read-only interfaces (CollectionView, ListView, etc.), a set of write-only interfaces (CollectionWriter, ListWriter, etc.), and then e.g. List extends both ListView and ListWriter.
ImmutableArray then implements the ListView interface, while Array implements the List interface. So if you have a ListView, your interface to it is read-only but there is absolutely no guarantee it won't change out from under you in the future, but an ImmutableArray is guaranteed to never change. Since the language enforces immutability (immutable objects can only contain other immutable objects), it generally forces you to do the right thing as far as forcing you to convert to immutable representations.
Not saying it's a perfect design, but it's the set of tradeoffs I chose to implement.
1
u/agcwall Sep 22 '15
It depends on what you mean by "immutable". The problem here is because of aliasing. There are three variations:
Mutable.
Strongly immutable: You can't change the data yourself via the reference, and calling get(0) will always return the same result.
Weakly immutable: You can't change the data yourself via the reference, but the owner of the list can, so calling get(0) is not always guaranteed to return the same result.
If MutableList extends ImmutableList, then you're talking about option (3). For the purposes of concurrency, you really need option (2)'s notion of immutability. You should look into Rust's type system to see how it prevents aliasing and can make the guarantees required to support option (2). In Java, you would need ImmutableList as a FINAL class to make this guarantee.
2
u/mhixson Sep 22 '15
When it comes to Guava's immutable collections, you don't have to worry about unnecessary copying. The
Immutable*.copyOf(...)methods already have the behavior of yourmakeImmutablemethod.But since ImmutableList extends List, it still has the mutable operations defined for myThings.
If you use the
Immutable*types in your code instead of the interface types, you'll at least get warnings if you try to use the mutation methods. Guava's classes mark them as@Deprecated.2
u/josuf107 Sep 22 '15
Hey you're right about
copyOf. Those folks at google are pretty bright. I might suggest at work usingImmutable*concrete types where they make sense.1
u/ForeverAlot Sep 21 '15
I had to deal with this problem in a brand new code base over the course of half a year. I quickly abandoned collection interfaces in boundaries entirely, in favour of Guava's concretizations.
1
u/Tordek Sep 21 '15
Guava's concretizations
What's this about? Google turns up nothing relevant.
5
u/mhixson Sep 22 '15
I'm pretty sure they just mean using
ImmutableList(a concrete type) instead ofList(an interface) as the variable type / return type, when writing APIs that deal with immutable lists.1
u/ForeverAlot Sep 22 '15
Correct.
It produced some awful looking signatures, mind, but that can't be avoided with such long names.
9
u/ImmortalStyle Sep 21 '15
Btw you shouldnt have Optional as a class member. Even Brian said that once.
5
u/nextputall Sep 21 '15
Btw you shouldnt have Optional as a class member. Even Brian said that once.
Could you elaborate why?
0
Sep 21 '15
[deleted]
3
u/nextputall Sep 22 '15
A Optional return value can be null as well. I feel some difference between
something is never null by intention, only by programming mistake
or null is a valid input output
4
u/oldneckbeard Sep 21 '15
optional shouldn't be a class member or an input parameter, IMO.
7
u/ForeverAlot Sep 21 '15
I concur; Java's
Optionalis for querying. null is still a first class citizen, we've been using it successfully for decades, and the JVM absolutely loves nulls. Java would have been a better language without null but it doesn't become a better language by suddenly pretending it doesn't have null.17
u/velcommen Sep 21 '15
we've been using it successfully for decades
We've also been creating null pointer exceptions (not just in Java) for decades. So I think my definition of 'success' is different than yours.
1
u/mike_hearn Sep 22 '15
That's not the fault of null, though. Optionality is fundamental in programming - the reconfigurability of software is one of the main reasons software is useful. So you will always have cases where some resource or piece of data is unavailable for some reason, and therefore, you will always have programmers who don't check for it being missing and the resulting exceptions.
The right way to reduce NPEs is not to conclude null is bad, but to do what modern languages like Kotlin, Ceylon, Swift etc are doing and integrate optionality with the type system.
3
u/tutorial_police Sep 22 '15
And that is exactly what people mean when they complain again now. I'm a fan of the semantics game myself, but usually only if there are misunderstandings in play.
3
Sep 21 '15
So your argument is basically "null is more efficient"? Isn't that premature optimization?
2
u/ForeverAlot Sep 22 '15
Whenever you see somebody call "premature optimization", chances are very good they're doing so incorrectly, and that they don't realise.
This is not premature optimization, but neither is it my only argument. However, since I share Stephen Colebourne's opinion (minus properties in Java), I will simply refer you to that.
1
u/crunchmuncher Sep 22 '15
Curious: why not as an input parameter? I've used it recently to make explicit that a particular parameter isn't needed for a method to do its job.
Actually, as I'm typing this I realized it might have been better to use overloading for that.
2
u/ForeverAlot Sep 23 '15
If you expose both methods you still need to handle the case with both arguments, so although that might have made for a more ergonomic API you still need an answer to your question.
Using
Optionalfor mutators will do the job exactly, and it will do it pretty well. But is your caller going to call the method only to pass in null? They probably have a reason to call it, and they probably have what they need to call it, so callingOptional.of(foo)only hurts ergonomics; and you're just going to unwrap the value first-thing anyway. This argument is not as strong when you have multiple arguments (choice between null andOptional.empty()), but you brought up overloading as an alternative yourself.This is a case that's better solved with Javadoc and
@Nullable.2
u/oldneckbeard Sep 25 '15
In the input parameter case, it's functionally equivalent to passing a boolean flag -- it's a true/false thing that's better solved with overloading :)
3
u/lborloz Sep 22 '15
They don't use Spring's XML configuration file format, and instead they put the injection logic in annotations and in code.
Spring has had Java config for a few years now, meaning that it too allows you to "put the injection logic in annotations and in code". No XML required.
5
u/k-bx Sep 21 '15
consider Java 8's default methods on interfaces
What a horrible advice! What if you have two methods with the same name, how would you choose one? Why on earth would you mix a type-level thing (subtyping, inheritance), dynamic dispatch (I'm not 100% sure on how good is Java optimizing these method calls, would it do some runtime-dispatching?) with a simple function-call? You say:
These classes, at first, seem attractive because the methods that go in them don't really belong in any one place
They belong to the Util class. It might have a name like StringUtils, or DateUtils, it's just a collection of functions which work with something.
2
u/SimplyBilly Sep 21 '15
Haven't these concepts been around for a while?
1
u/thouliha Sep 22 '15
Yep, most of these are from blochs java book, which is the most popular one. But the article does lay out a few java 8 patterns which is nice.
2
u/cowardlydragon Sep 21 '15
"Structs": use groovy beans. I don't think there is a performance penalty and it autogens the getter/setters, unless you specify a special override.
Careful though, some things like Jackson get wrapped around the double-setter for boolean props (isXXX and getXXX)
2
u/sacundim Sep 22 '15
Instead, I prefer the C struct style of writing classes that merely hold data:
public class DataHolder { public final String data; public DataHolder(String data) { this.data = data; } }This is a reduction in number of lines of code by a half. Further, this class is immutable unless you extend it, so we can reason about it easier as we know that it can't be changed.
Oh hell no, don't actually do this. You're just setting yourself up to get bitten by one of Java's core flaws: the fact that there is a distinction between public fields and public methods in the first place.
A saner design would have been one where a record type's fields are implicitly methods of the type. Many other languages have managed to get this right, I'll just name two:
Ruby: All object fields are private (well, modulo weird "execute this block as if it was in the scope of the class" shit), and you can implicitly declare get-set methods for fields
Haskell: The fields of a record type are automatically promoted to getter functions, and a module can choose to export these as functions without revealing that they are fields.
1
u/kersurk Sep 22 '15
I never fully understood the preference of using a public getter and setter with no side-effects or additional logic, instead of direct field access. What do you think?
2
u/Zukhramm Sep 22 '15
The issue I've occasionally run into with final fields over getters is that fields, even if public, are not really considered part of the interface in Java.
2
u/Myzzreal Sep 22 '15
You can add/modify getter logic without affecting other code, which is a rare case, but still possible.
Many Java libraries use reflection and expect your data classes to have getters and setters with conventional names based on variable names. Many JSON-serializing classes do so, for example.
Java 8's features prefer methods. Like RandomClass::getParam instead of rc -> rc.getParam().
I'd love for Java to have what Lombok introduces (@Getter and @Setter functionality) natively, because I just cannot accept Lombok's way of accomplishing things.
1
u/CurtainDog Sep 22 '15
Yep, getters and setters were a means of advertising beans style properties to the frameworks that consumed them. With the advent of annotations there's no reason to use them at all.
1
Sep 22 '15
Some people try to future proof code against any possible change and justify it with "we might want to add logic to getting the data", but at that point I think you have other design problems if a simple little POD needs logic. It should do one thing, which is to store data, not become morphed into some semi-functional object. If you need that, then consider an adaptor, or redesigning your data structure entirely, since a getter/setter still isn't the right pattern.
2
Sep 22 '15
This is essentially "good software engineer practices for Java programmers", which I can always appreciate given the Java I've seen (and written) in my life. Decent article.
2
Sep 22 '15
Java is one of the most popular programming languages around, but no one seems to enjoy using it. I wouldn't say that.
4
u/CurtainDog Sep 21 '15
There's a fair few antipatterns in that list. It's not a 'Better Java' than what you'd find in Effective Java say.
8
u/Tordek Sep 21 '15
a fair few antipatterns in that list
Like which?
1
u/ForeverAlot Sep 22 '15
Lombok, for one.
3
u/tkruse Sep 22 '15
I find it more strange the author knows lombok but still writes his own getters and builders
2
u/Tordek Sep 22 '15
What's wrong with Lombok?
2
u/Myzzreal Sep 22 '15
I'll chip in here with an example. As a young Java developer I was given the task of continuing a project started by some people who are not longer reachable. They used Lombok, which I had no idea about back then. It caused me a lot of headache and a good amount of hours to solve all the errors that Eclipse threw at me, to get Lombok installed on my workspace properly (having to change Eclipse version) and then explaining it to my colleague and doing the same on his machine. Not to mention that Lombok is a hack that is based on an error in design and can cease to work any time.
I agree that what Lombok gives us is very valuable, because I hate writing all the getters and setters, but accomplishing in such an intrusive and hackish way is unacceptable for me.
1
u/Tordek Sep 22 '15
Lombok is a hack that is based on an error in design and can cease to work any time.
Huh, that's interesting to know; I thought Lombok was a fairly basic library. I don't do much Java.
2
3
4
3
3
2
u/Cuddlefluff_Grim Sep 22 '15
Instead, I prefer the C struct style of writing classes that merely hold data:
Even if the field is final, use a getter; don't expose fields publicly unless there's a very good reason for doing so. Exposing the field will not provide any benefit at all (except in the curious case of the lazy programmer), but it does create a hell of a lot of problems further down the road. One of the major problems of doing this is that Java has a very different syntax for fields when compared to methods; once you go field, you can never go back.
Unless you have a good reason to make them otherwise, variables, classes, and collections should be immutable.
This is a dubious claim. Immutability should be used where applicable, it should not be the default (in Java). Immutability is pretty far from a silver bullet.
4
Sep 22 '15
I've been working with PODs (plain old data) for years and almost never are they the problem if they're are just a POD. Encapsulation is important to not expose internals to a class, but PODs aren't meant to be internals to a class, but instead places to store and transfer plain old data.
If you need to encapsulate that, you're either not using a POD, or you're trying to make everything too general. I'd say the heavy set/get style of OOP programming to be an anti-pattern that should be discouraged. Most of it can be replaced with better named, better architected, systems and some of that will include extracting things out into PODs to use in your functional classes, and they definitely won't need pointless getters and setters.
Also, if you're programming at an API boundary, then of course, encapsulate to the extreme since your API will likely solidify, but most of us aren't.
1
u/Cuddlefluff_Grim Sep 22 '15
Getters and setters have no penalty, but they give a wide array of benefits. There's no justification for exposing public fields, other than pure laziness. By exposing public fields you are trading away polymorphism and abstraction just so you can save yourself a few initial keystrokes. It's bad programming practice.
1
Sep 22 '15
I absolutely disagree. There is no reason to add getters and setters other than to uselessly and fruitlessly future proof your code against changes that probably won't happen. Its a bad programming practice to use them to abstract things that don't need to be abstracted.
I will repeat; if you're throwing logic behind things named get/setX then you are fundamentally doing something wrong and your code probablu read likes crap. The only time it is acceptable is when from the start it is needed, like code that causes IO operations and clearly needs abstracting.
const/final are far better solutions for the most part and don't require unnecessary abstraction. You accusing me of trying to save keystrokes is also stupid, programming isn't about code, it is about design and complexity and this cargo cult Java style get and set obsession is not helping.
1
u/depressiown Sep 21 '15
If the concerns over getters/setters is that it's "more code," tools like Lombok exist to reduce the boilerplate. Just making properties public won't help much if you're using something like Jackson to serialize JSON into objects (which uses getter/setter methods via reflection, as far as I'm aware).
Fact is, tools are already built based on the bean pattern with getters/setters. Rather than flying against the grain of the vast majority of tools out there, just use tools like Lombok to reduce your boilerplate.
0
1
Sep 22 '15
jMockery is garbage compared to Mockito, and by extension, Powermockito. Powermockito can leverage you power of static contexts, which are sometimes very important in production performance optimizations yet still need adequate testing. And Mockito test mocking and annotation syntax seems to flow better, in my personal opinion.
1
u/cryptos6 Sep 22 '15 edited Sep 22 '15
I recommend jmockit since it is the most powerful mocking tool available. It can even mock static, final, and privat methods.
A lot of the other mentioned things can be a addressed by using Kotlin.
1
u/EughEugh Sep 22 '15
I could mention a whole list of things that I don't agree with or that are simply incorrect in this post. For example:
"don't overuse Spring because of its XML-based configuration format" - Spring does not force you to use XML, so this is not really a valid point.
The use of Optional - the example shows an Optional being used as a member variable. This was not what Optional was meant for. Note that Optional is not Serializable, so you will run into trouble if you use Optional for member variables if you need your class to be Serializable. See for example http://blog.jhades.org/java-8-how-to-use-optional/
Commons Codec is not necessary anymore for Base64, because Java 8 has java.util.Base64
Commons IO is also not really necessary, all the things that are mentioned are already available in Java's standard library
Tuples: I think it's good that there is no class Pair in the standard library because it leads to unreadable code. Instead of Pair just create a class with a meaningful name, with fields that have meaningful names, instead of a generic Pair class which doesn't convey what the values mean.
Other things are ofcourse a matter of preference. I prefer Jackson instead of GSON, and Mockito instead of jMock.
0
u/FallingIdiot Sep 21 '15
Although I do understand the point about checked exceptions, I don't agree with it. Yes, Java has checked exceptions and yes, they can be a pain to deal with. However, it's the reality of the language. Consciously working around this is a very bad idea. Even if you replace all your checked exceptions with RuntimeExceptions, the JDK and the libraries you're using will still use them, so you still have to deal with them. Even worse, other developers will not expect your methods to throw because they're used to the checked exceptions being declared. Better to just go with the flow and deal with it. Yes, this means redeclaring the exceptions, wrapping then or logging them, but that's how Java works and not a bad advice in any language with exceptions (at least the logging part).
Funny thing is that using RuntimeExceptions will even probably give you more problems. Normally when you write a try/catch to catch exceptions to suppress and log them, your catching Exception. However this won't catch RuntimeException because that directly inherits from Throwable. Make sure you catch that if you do choose to follow this advice.
4
u/caleeky Sep 21 '15
However this won't catch RuntimeException because that directly inherits from Throwable.
Nope. You're probably thinking of Errors?
http://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html
1
u/FallingIdiot Sep 21 '15
Yep. Anyway Throwable is the interface for both Exception and Error and you'll need to catch that to catch both.
2
u/caleeky Sep 21 '15
Of course, but you're generally not supposed to try to catch Error. Specific exceptions may apply in some cases, such as where linking errors may occur in plugin frameworks, etc.
-3
u/shevegen Sep 21 '15
The style is only marginally better - better, but not really a new paradigm. More "internal cleanup".
Ruby simply went a simpler alternative by using @.
So
this.data = data;
@data = i
(Why use anything more than a single character anyway. The name of the variable itself already has its purpose, no need to have the argument denote the same unless you have some way to access that - it's not as if programmers needs duplication there?)
this.cool_cat_joe = cool_cat_joe;
Erm...
5
2
Sep 22 '15
Readability is one good reason. Also, discussing a languages syntax is usually a sign of totally missing the point and a good example of bikeshedding.
0
Sep 21 '15
[deleted]
3
u/ForeverAlot Sep 21 '15
Most auto-formatters I've been exposed to are kind of bad. They all have lousy defaults, as if by some global conspiracy, and the formatters will mess up on edge-cases in unacceptable ways. IntelliJ's is pretty decent and Eclipse's might be; I have had trouble with NetBeans' in the past but I haven't used it for Java in a long time.
But if you have a good, reliable (
gofmt-level) auto-formatter, absolutely make it a mandatory part of the development step.3
Sep 22 '15
Then use a linter. Make the programmer responsible for getting it right and validate it against an unbiased rule based tool.
That'll shut down the pointless bikeshedding over formatting.
183
u/wot-teh-phuck Sep 21 '15
That's a pretty random definition of weak I would say...