298 points · by xngzng · 12y ago · 220 comments
First off, it's important to know the difference between value types and objects.
For a value type, public final fields are good. They are set in the constructor once, and can only be read, and can't change. Getters are pointless, and my code does not have them. If you want them for a reason, then intellij does an amazing job fixing that.
Objects encapsulate mutable state, and getFoo() and setFoo() are inappropriate methods to have. They should be things that affect the behavior of the object, not simple setters and getters.
The big issue is that a lot of java was created when we still hadn't figured out how to properly do Object Oriented Programming. But we know now (well - some of us), and there is nothing in Java that prevents you from doing it well.
Contrast Java with Ruby or C#. There, the clients don't need to know whether they're accessing a member var or calling a method to get/set a property, NOR SHOULD THEY. The inability to do this in Java fundamentally breaks encapsulation.
Others have noted that in many contexts in C# there is a difference, so clients do need to know.
As far as Ruby, clients definitely need to know, its just that since public fields can't happen in Ruby, its always method-based access for the normal cases.
Both of these lines are always calling a method on "obj" in Ruby:
foo = obj.a # equivalent to foo = obj.a()
obj.a = foo # equivalent to obj.a=(foo)
While these are using instance var (the closest thing to a "field" in Ruby) access: foo = obj.instance_variable_get :@a
obj.instance_variable_set :@a, foo
foo = obj.instance_eval { @a }
obj.instance_exec { @a = foo }
There's no common syntax like C#-style properties that unifies field-based and method-based access, so Ruby is sort of the extreme opposite of attempts to have "properties" that make method-based access look the same as field-based access in the same language, even though its method syntax can make method-based access in Ruby look like field-based access in a completely different language. class Foo(object):
def __init__(self, bar):
self._bar = bar
@property
def bar(self):
return self._bar
@bar.setter
def bar(self, value):
self._bar = valueSure, you can beat the big ones into working, and there is generally no shortage of libraries in Java. But at some point you are just wasting resource to work around other people code. Java has properties and some libraries use them.
Discussing if you should use them at all is offtopic, the real problem is that java has properties but instead of being a language/compiler supported feature, it is only defined as a "convention" with some half-assed support classes. Seeing how popular properties are, that either needs fixing or deprecation (starting with all the Oracle provided framework that use them)
This! A lot of the horrible Java you see around is nothing but an artifact of mindlessly applying patterns to constructs that don't need them.
> a lot of java was created when we still hadn't figured out how to properly do Object Oriented Programming.
Which is quite unforgivable, considering Smalltalk has been around since the early 80's.
Let's see. OOP generally involves "objects", ie structs or records with visibility controls on fields, sporting "methods," ie functions with a magic/hidden this/self argument. This alone doesn't buy you much, and in fact is quite inflexible when compared to good old ADTs, so let's hope there's more to it.
OOP does not mean "all methods are defined within the class declaration/file" a la Java, plenty of OOPLs allow external method definition. So it doesn't mean "well in OOP I always know the behavior of my class" when you have friend functions etc.
OOP might mean "abstract classes" ie virtual methods. This leads us to inheritance, which is a) not confined to OOP and b) widely criticized. Remember that inheritance != polymorphism, c.f. Visual Basic for instance (at least VB5. Showing my age...). In practice, OOP usually invokes a great-chain-of-being-like hierarchy descending from Object, but again this is not universal.
OOP generally means "polymorphism", but the mechanisms vary widely. OOP's "Classic" inheritance-driven polymorphism is probably the worst way to do it, good for quick code-reuse and that's about it. "Interfaces"/pure virtual classes are a design pattern on top of abstract classes, better expressed as mixins or type-classes.
OOP generally implies strong typing but not always (python). OOP typing is quite clunky, especially in "noun-oriented" Java. You can make an argument that the rise of DI frameworks is in response to having impoverished type systems.
My semi-rant here is because people say things like "do it this way, it's good OOP" without there being any agreement about whether we're discussing polymorphism, inheritance, encapsulation, factoring, normalization, or design patterns that are largely a response to the confusion.
On the other hand we have folks like the clojure crowd bagging on OOP using similarly vague concepts like "OOP means stateful objects/side effects" ...
> Colleagues & I once doubled system's functionality & replaced 750K lines of Java with 50K lines of ... Can you guess the language.
> Of course it was Java!
Another option is to use builders (that are mutable), to build/copy your immutable business (?) objects.
(link provides no real details: http://openjdk.java.net/jeps/199)
Bollocks, there were already plenty of OO languages when Java appeared on the block.
My somewhat unorthodox rules for writing Java:
1. Don't use private. No reason to restrict yourself or others, and do extra typing. Friendly is a perfectly good default.
2. Don't use reflection. Reflection is only useful for making frameworks. Frameworks don't reduce the complexity of the problem you're trying to solve. Don't use them.
3. Don't use getters/setters. Sometimes they make sense for updating a cached value, or using a different underlying representation, but in general it's unnecessary clutter. If you still want them (e.g., for code style reasons), just generate them.
4. Don't use other people's code (tongue-in-cheek). If you use third-party libraries, consider wrapping them in your own interfaces as needed. This makes it easy to change the implementation and perform tests. It's not much effort, since you'll rarely use more than a limited subset of the functionality offered by the library. If you need a large subset, then just use the library directly.
5. Use final. Immutability makes programs simpler, more efficient, and inherently thread-safe.
6. Consider writing bean classes as follows. It's simple, efficient, thread-safe, and has a clean syntax (item.name):
public class Item {
public final int id;
public final String name;
public Item(int id, String name) {
this.id = id;
this.name = name;
}
}
7. Use an IDE, refactor, find references, generate code. It's easy to changes names and styles later, so just focus on important things like performance and reliabiltiy.8. Keep improving the way you write your code, don't listen to the crowd.
How do you account for value objects in that statement? Are you saying there should be no such thing?
class Rectangle {
num left, top, width, height, right bottom;
}
and can access like normal: var height = rect.bottom - rect.top;
But can later be changed into a computed property without affecting the above callsites, e.g: class Rectangle {
num left, top, width, height;
num get right => left + width;
set right(num value) => left = value - width;
num get bottom => top + height;
set bottom(num value) => top = value - height;
}
C# is a close 2nd, but it's not binary (or reflection) compatible to change from a field to a property for call-sites (i.e. it's only source-compatible).I'm surprised to hear that it's not reflection compatible. As a Java programmer, I assumed that was the main point of C# properties: Create a property now because there's no logic needed, but if you need logic in the future you can change the code and nobody outside needs to be aware of the change.
attr_accessor :left, :top, :width, :height, :right, :bottom
And you can change these to computed properties (regular methods) later without affecting the callsites
As an added bonus, you don't need to write foo.getBar(), you can just write foo.bar and it Just Works, whether foo.bar is a concrete implementation or a computed property.
Look at this blog post for example:
http://java.dzone.com/articles/java-properties-without
The sad thing is the request here is for something more ugly than what is really wanted (this is just automatic getter/setter implementation -- computed properties are better both for developers and consumers of their output.
class Blah(object):
foo = 2 # A normal property. Direct access
@property
def bar(self):
return self.some_lookup_method()
@bar.setter
def bar(self, value):
self.set_the_bar(value) // Sorry if there are any mistakes, I have not
// written any Java code for quite some time.
public class Point
{
private int x;
private int y;
.
.
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void setX(int newX)
{
x = newX;
}
public void setY(int newY)
{
y = newY;
}
}
Look at how long the class definition is for something so basic!In Common Lisp there are two ways to define classes/structures, defstruct and defclass. Defstruct[0] automatically automatically defines everything for you:
(defstruct point x y)
will define the procedures make-point, point-x, point-y, (setf point-x), and (setf point-y). The cool thing is that they are all procedures. It easily change the class definition without changing the code that uses it. There are also some additional options for defstruct to specify default values, how to print the structure, as well as what prefix to use (the default is the name of the structure, 'point' in this case).Defclass[1], while much more verbose than defstruct, is much more powerful:
(defclass point ()
(x :writer set-x :initarg :x)
(y :reader get-y :initarg :y)
(z :accessor z))
will define procedures, set-x, get-y, z, and (setf z). Set-x and (setf z) are the setters, while get-x and z are the getters. To construct a point that is defined this way, one has to use the procedure make-instance which will take keyword parameters[2] :x and :y, for x and y respectively. [0] http://www.lispworks.com/documentation/lw445/CLHS/Body/m_defstr.htm
[1] http://clhs.lisp.se/Body/m_defcla.htm
[2] http://www.gigamonkeys.com/book/functions.htmlIt's just redundant code. Most of the time developers don't actually need to override the basic get/set operation on a variable. Yet you have to write the get/set methods over and over.
How do other languages address this issue?
Scala does a good job. You don't need to actually write a get/set method. But if you wanted to modify getFoo() you would simply implement the method with your custom getter
public int Age{get;set;}
no need to declare private variable, get or set methods.
foo.baz += foo.bar;
vs.
foo.setBaz( foo.getBaz() + foo.getBar() );
Basically you keep states encapsulated without have to manually write methods,you just write methods when you need then.
Java verbosity on that matter is totally unecessary.
Granted when one use an IDE refactoring features can help,but still... A great strenght of the Java language is its stability.But stability doesnt mean a language needs to be that verbose.
This goes back to at least Eiffel (1985).
class Car
attr_reader :model, :company # only read
attr_accessor :color # read and write
endThis is pretty trivial so bear with me... If you have something that looks like this...
class Person
attr_reader :children
def initialize
@children = []
end
end
You can then do this... x = Person.new
x << "Bobby"
You will have then altered the value of @children without completely reassigning it.It is pretty astonishing they haven't done something about that. It doesn't seem like it should be a very hard language feature.
public class Foo { public readable int canSeeeMeButCantChange; public writeable int cantReadMe; public int existingBehavior; }
These are pretty simple changes to the compiler and verifier. You would make canSeeeMeButCantChange an invalid "left hand" variable in the compiler, and the verifier would have to check for any writes to the fields. cantReadMe would be an invalid right hand variable, and a similar check for the verifier. Any other public field behaves as normal.
Integer val = some.other.chain.of.objects.value;
In Java, this code has a huge potential for NullPointerExceptions. Instead a new operator (yes, I know) like:
Integer val = some.?other.?chain.?of.?objects.?value;
If any of the intermediate objects are null, the whole assignment becomes null. This could be done with a smarter compiler (easy way), or a new JVM bytecode (probably 'better' but not easy).
T obj = ...;
Optional.of(obj).map(T::some).map(U::other).map(V::methods).getOrElse(null);
Not quite as clean syntactically, but much more general, as the same operations can be applied to other monadic objects.
I'd be interested in seeing C#-like getters and setters. As long as they're just getting and setting, they're implied, but if you want to introduce a check or some other logic, you can do so without changing the signature of the class.
Groovy does some of this, but it requires you to use the name of the field - ie. person.age will check for a getAge() method first, then fall back on the "age" field. I quite like that methods have verb-names, but I don't want to verb my fields.
I was thinking this is more for _public_ variables... so like internally, a class could modify it's own readable fields, but code external could read only.
We ran out of patience and switched to Scala. Never been happier :)
I love C#, but I do wish that setters weren't so easy to define (and that classes were sealed by default, and that fields were read-only, and that all extant warnings would become errors, etc.).
That being said, I still make my classes immutable unless there is a damn good reason not to.
State changes can have desirable side effects.If you expose an instance variable directly it's harder to encapsulate that.
Of course there are exceptions. If you have a class that is meant to be only a parameter bag(in an rest API for instance),that's ok,imho.
Don't get me wrong, I'm big on encapsulation and separation of concerns, etc. But you don't need to force "privacy" onto your class's users in order to achieve it.
The worst thing about having everything public (this is python, btw) is that sometimes it pollutes the auto-complete, and hinders discoverability. It's also not immediately obvious what the user should/shouldn't have access in your class.
Let's say you have
data Point = Point {x :: Int, y :: Int}
If you have a Point object called "point", you can get x by doing x_coord = x point
If you want to create a new Point with x set to 5, you can do point' = point {x = 5} type point = { x: int; y:int}
let z = {x = 5; y = 10}
let y = {z with x = 17} case class Point(x: Int, y: Int)
val p1 = Point(5,10)
val p2 = p1.copy(x=17)
How does F# handle nested data types? In Scala if you want to copy a case class of a case class (of a case class ...) it can get boilerplate-y as you have to copy outside-in through each property a la: x.copy(acase.copy(bcase.copy(cprop=1)))http://projectlombok.org/features/Value.html http://projectlombok.org/features/experimental/Builder.html
Although I prefer not using getters & setters at all.
Also, it breaks encapsulation, because your internal storage should be changeable without ruining your external surface area.
At least if it will be ever used by code beyond your control.
Because then you'll never be able to add a getter or setter later without breaking people's code.
Java is frustrating in that regard. As it should be able to deal with automatically invoking getters and setters when needed (it already inlines getters and setters at runtime, this is "just" the reverse), but it's a language decision that it doesn't.
As an additional bonus, this would help reduce the (legendary) verbosity of Java. a.b += c.d is much easier to read than a.setB(a.getB() + c.getD()). And don't get me started on Java's generics or lack of operator overloading...
Now, props where props are due: Sun crushed the collections APIs compared to other languages at the time. And that more than makes up for everything else.
But I see little evidence that standardizing JSON parsing will improve things.
Perhaps Sun should have just adopted slf4j and a simple console-logging stub, but I don't think j.u.l is really any worse than the alternatives -- only a different implementation.
Now date APIs: those do suck, but I think the new Date JSR will finally get things to a place where we can use Java Dates rather than Joda.
But it is unclear how many of the existing implementations conform to it, and it definitely doesn't work toward your misguided One True JSON Implementation goal.
Above and beyond the fact that in section 2.2 of the JSR it plainly states: "This JSR is targeted for Java SE 6 or higher and Java EE 7 or higher platforms."
FYI: Just looked at your nanojson, looks good. Might have to try it out, i like the fluent api for object creation.
It becomes one when serializing and de-serializing across a distributed application like xerces class path issues in different jvm implementations.Not a common sore point though!
>> Chances are many of these options would still exist even if there was an official API.
True and agreed.
Publish an official blessed and supported way of daemonizing processes. Yeah sure, you can use Apache commons-daemon and others of it's ilk. And it will work. But it will feel hacked together (at least it does to me).
2. Fix Dependency hell!
Publish a blessed / supported / standard of supporting / managing different classloaders. Java has this great mostly unused mechanism (classloaders) for managing dependency hell. It would be great to have platform (maybe even language) level support to make that easy to do and a standard way of building software.
This is fixed by process supervision software such as systemd -- no need to implement it yourself. Just leave your application running in the foreground.
Java 8 was supposed to provide modules but they were scrapped so in the meantime, OSGi is the only option.
I also thought that type reification was being researched.
Does anyone know if either of these is still a thing?
- if continues to be a keyword
- Spyware continues to be included
Edit: Real Hotswapping will requires profound changes to the memory model. It would introduce too much complexity. I rather restart my application than to suffer from a fragile and leaking platform.
Unfortunately, this will require externalization of state data, but if you can't be down for 5 minutes, that's what you need to do.
You probably only need one large server running the instances, rather than a cluster. Java apps don't seem to do well -- longer GC pauses -- when they have over 2 GB of memory, anyway, so run multiple instances of "small" apps on a server with say 12 cores. A single server with a large pool of RAM shared between a large number of cores can do pretty amazing things with a collection of "small" programs on it (DB, web service apps, message queue server, web servers)
Of course, I'm assuming said server isn't Windows...
Edit: Demo of it in action here, notch is rapidly developing a game in Eclipse by changing the code while it's running: https://www.youtube.com/watch?v=rhN35bGvM8c
He's modifying the Swing object tree from the main thread! Don't do that, Swing isn't thread safe ;-)
https://www.youtube.com/watch?v=rhN35bGvM8c#t=1454
http://docs.oracle.com/javase/7/docs/api/javax/swing/package...
`ImmutableList.of("a", "b", "c")` is not as concise as e.g. Python, but it's not bad.
Swift has this: var airports: [String: String] = ["TYO": "Tokyo", "DUB": "Dublin"]
I like the swift example... Map<String, String> map = new HashMap<>(){"TYO": "Tokyo", "DUB": "Dublin"};
Then it scaled back to a re-org of the rt.jar to make it easy to run on mobile devices (Ironically we are seeing the full circle - Java started out as a Set-top box language, then graduated to an enterprisey kitchen-sink and now wants to come back to a modular approach).
Now they seem to want to do some half-baked OSGI compliant approach. Have they used OSGI on medium/larger projects? There is literally no amount of money you can pay me to tackle something that hairy and complex.
I remember seeing something about that in a presentation a few years ago.
I think it's a good decision from Oracle to not include much more (compared to Jigsaw) in Java 9, given the huge scope of the Jigsaw change, which might probably be the change with the largest internal code impact so far ever done in Java, or at least one of the largest (if the plan to refactor the JDK for modules goes further).
I've heard this thrown around before, but what this actually mean? Is it just some optimizations to the garbage collector?
And see also: https://bugs.openjdk.java.net/issues/?jql=project%20in%20(JD...
Maybe around 2020 we'll get some useful stuff like string interpolation, long strings, default param values, and multiple return values!
"user-defined value types", i.e. structs, can already be done today by (ab)using the Flyweight pattern and storing data (possibly off-heap with RAII rather than GC semantics) in some byte[].
All a JDK-supplied implementation would really need to do is (1) automate/hide all the painful work necessary to set this up and (2) provide syntactic sugar in the form of operators that can directly manipulate members of these types (+fast implicitly inlined implementations of them, specialized on the member types).
The http client was so basic in the JDK it has spawned TWO apache HttpClients projects.
Jigsaw... fool me three times? Wasn't this supposed to be in JDK7?
is there any contender to json at the moment?
JSON somewhat replaced XML, but that made sense since XML is more complex and a lot more expensive (both in terms of network AND processing).
I can see people building more complex obstractions on top of JSON in the next for years (essentially re-building what XML was, but in JSON) however I cannot really see JSON being entirely dethroned for what it is good at.
As far as contenders to JSON, I can't really think of any besides XML. The biggest benefit to JSON is its simplicity; which becomes a huge drawback in a strongly typed language like Java.
For other message protocols it's a different story. Each system has its own needs, so it's much harder to say.
They are going to improve lock performance, but do nothing to help people avoid locking like lightweight threads. Not waking up a thread and not locking is faster...
It's weird how so many software projects completely lose sight of the fundamentals.
I know I am biased due to how I use Java. I care very little for syntax and syntactic sugar. Reading and typing speed is not a problem for me. Get stuff done on time is and working around these shortcomings eats up my time.
(disclosure: I'm a very happy customer of theirs)
The reality is that you have to build software that works on the Oracle JVM.
It's bad enough that people who care aren't using G1 yet. They still use CMS and small heaps and are careful to prevent promotion and fragmentation.
You basically end up benefiting from GC for short lived allocations, but pay dearly for using Java when managing state the collector can't handle.
I have not closely reviewed this benchmark but this was one person's experience http://blog.mgm-tp.com/2013/12/benchmarking-g1-and-other-jav...