Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the awkward Design of System.out?

Tags:

java

api

Has anyone got an idea regarding the motivation behind the awkward design of the java.lang.System.out?

Awkwardness:
First, the out member is exposed (Encapsulation anyone?).
Second, it is final but can be changed via setOut() (contradicts final).

like image 961
Shimi Bandiel Avatar asked Apr 07 '09 11:04

Shimi Bandiel


3 Answers

In Java 1.0.x System.out and friends were not final—it was possible to change them by assigning directly to them. However, this presented an issue when Sun decided to optionally restrict this behavior in Java 1.1 (for applets, at the time). To maintain at least some backwards compatibility, out was made final and written to with a native method, which was wrapped with the appropriate security checks.

like image 139
Nicholas Riley Avatar answered Nov 04 '22 02:11

Nicholas Riley


I would bet it is exposed mainly for brevity. Compare:

System.out.prinln("blah");

with

System.getOut().println("blah");

The former is not many character shorter, but still it is shorter, and simpler conceptually. It is also very probably faster, perhaps especially back in the day when JIT was not too common in Java virtual machines; I bet the direct access is faster than a method call in those cases. So, it boils down to being a tradeoff.

UPDATE:
As for final and setOut(), the documentation for the latter says that if there is a security manager, it will be queried to see if the caller is allowed to re-set the output stream. This might be the answer; if the out member had been directly assignable, there would not have been a way to protect it.

This is just my interpretation of the API and the thoughts that might be behind its design, I could be off.

like image 26
unwind Avatar answered Nov 04 '22 04:11

unwind


This has similarities with Array.length vs List.size().

Could it have been done for historical reasons? Are there any other languages like this?

like image 2
masher Avatar answered Nov 04 '22 03:11

masher