Posts Tagged java

Twitter on Scala Interview

There is a nice interview with the Twitter development team on Artima about using Scala in production on Twitter code. The team talks about some issues and facilities regarding the chose of Scala to develop Twitter’s queueing system and how Scala affected the team’s programming style.

My personal highlights:

And Ruby, like many scripting languages, has trouble being an environment for long lived processes. But the JVM is very good at that, because it’s been optimized for that over the last ten years..

So Scala provides a basis for writing long-lived servers…Another thing we really like about Scala is static typing that’s not painful. Sometimes it would be really nice in Ruby to say things like, here’s an optional type annotation

And because Ruby’s garbage collector is not quite as good as Java’s, each process uses up a lot of memory. We can’t really run very many Ruby daemon processes on a single machine without consuming large amounts of memory

In some cases we just decided to burrow down and use the Java collections from Scala, which is a nice advantage of Scala, that we have that option..

As I’ve learned more Scala I’ve started thinking more functionally than I did before. When I first started I would use the for expression, which is very much like Python’s. Now more often I find myself invoking map or foreach directly on iterators..

The reason you should care about immutability is that if you’re using threads and your objects are immutable, you don’t have to worry about things changing underneath you..

It’s very worth read. Post your comments here when you read it.

Tags: , , , ,

Bean Validation – Emmanuel Bernard on JSR 303

JavaLobby released an interesting interview with Emmanuel Bernard, the spec lead of of JSR-303: Bean Validation..

One of the important goals of the Bean Validation spec is, as Emmanuel Bernard says, is

to provide a default runtime engine that is used to validate the constraints around the domain model, in Java.

The development team decided to use annotations to express the constraints applied at the domain model. They argued that with annotations the constraints are put directly at the properties in the code, expressing the constraints associated with the property.

I highlighted some interesting parts of the interview:

Bean Validation lets you standardize the way you declare the constraints. So an application developer will just know one way to declare constraints, and just forget about all the different models. There’s no duplication around the validation on the layers.

If you think about a constraint, a constraint is really some kind of an extension of the type system.

Bean Validation lets you validate an object graph using the @Valid annotation. Basically saying, ‘Well, when you validate this object, make sure the associated object is validated as well.’ By the way, even if Bean Validation is primarily annotation focused, there is the equivalent in XML.

Any framework that is having a need to use validation, to apply validation, can either use the runtime engine of Bean Validation or go extract the metadata and play with that. So the user declares it once, in one place, and every framework in the Java space can actually go and either apply the validation routine …

You can listen the podcast of the interview also. It’s very noteworthy to read or listen the interview and see what’s next on validation in Java. Before the Bean Validation API become public to all of us, which framework do you use to validate constraints on the Java platform?

Tags: , , ,

Joshua Block on How to Design a Good API & Why it Matters

In this talk (recorded at Javapolis), Joshua Block presents guidelines about how to design good APIs. I highlighted what i think are the most important parts of the talk:

  • Functionality should be easy to explain: If it’s hard to name, that’s generally a bad sign
  • Good names drive development
  • Be amenable to splitting and merging modules (If names are nasty, take a step back and make things easy to describe)
  • When in doubt, leave it out
  • You can always add, but tou cannot take it out
  • Implementation Should Not Impact API
  • Always omit implementation details
  • Inhibit freedom to change implementation
  • Don’t let implementation details “leak” into API (For example: Serializable, hash functions)
  • Minimize Accessibility of Everything (This maximizes information hiding)
  • Public classes should’nt have public fields
  • API should be easy to learn, read and use: It should be consistent, it’s a little language
  • Documentation matters (Example: Method contract between it and it’s clients)
  • Think of preconditions, postconditions, side-effects
  • Don’t Transliterate API’s
    • What’s the problem it solves?
    • What shoud abstractions did it use?
  • Don’t Make the Client Do Anything The Module Could do
  • Throw Exceptions to Indicate Exceptional Conditions

When you see the talk, post your comments here.

Tags: , , , ,

Effective Java Programming with Joshua Bloch

Nice video from Joshua Block, Chief Java Architect at Google, talking about his Effective Java™ Programming Language Guide book and also about the consequences of adding new features on the Java language, like the closures’ proposals. He also offers an advice to the programmers, when designing API’s, classes or methods:

“When in doubt, leave it out”.

Tags: , , , ,

Is Java on a evolutionary dead end way?

Artima is running an article where Bruce Eckel talks about about Java’s objective on backwards compatibilities and the problem of combinatorial complexity when you combine a new feature in every possible way with the other language features already present.

It’s the combinatorial complexity that you get when you combine a new feature in every possible way with the other language features. The combinatorial complexity can produce horrifying surprises, typically after the feature is added when it’s too late to do anything about it.

It’s clear Eckel is mentioning the Java closures’ proposals to become part of the language on the Java 7 and the major improvements occured when Java 5 appeared.

If Java is unwilling to break backwards compatibility, then it is inevitable that it will acquire both unproductive complexity and incomplete implementation of new features. I’ve made the case in Thinking in Java 4e that Java Generics are only a pale imitation of real generics, and one of the more appealing suggestions for closures is an incomplete implementation of true closures, but it would actually be preferable to a complete implementation because it produces clearer, more straightforward code.

I particularly agree with him, when he also says

Fundamental new features should be expressed in new languages, carefully designed as part of the ecosystem of a language, rather thanbeing inserted as an afterthought.

He also considers Scala as an alternative for the Java language. Eckel also declares

Java values backward compatibility over the clarity of its abstractions.

I don’t agree with him at this later point, the Collections’ framework is an example of good API design rules with a lot of well designed abstractions by Joshua Block, separating things that change from things that stay the same.

And you? What do u think about it? Should Scala be considered as an exit for Java?

Tags: , , , ,

Strongly Java typed safe delegates

This great post explores an interesting Java implementation about using the delegate programming feature, in a type safe way. Delegate is a form of function pointer, commonly used to implement callbacks. It specifies a method to call, which is dispatched in runtime. From Wikipedia, we have:

The short definition is that delegation defines method dispatching the way it is defined for virtual methods in inheritance: It is always the most specific method which is chosen during method-lookup – Hence it is the original receiver entity which is the start of method lookup even though it has passed on control to some other object(through a delegation link, not an object reference). Delegation has the advantage that it can take place at run-time and affect only a subset of entities of some type and can even be removed at run-time. Inheritance on the other hand typically targets the type rather than the instances and is restricted to compile time.

We almost know weakly typed Java delegate implementations, relying upon Strings to delegate to named methods. This way, it lets you mistype the method name easily and it also does not not allow method completion in the IDE. Alex shows us a type-safe Java delegate implementation, which enhances readibility and supports code completion on the IDE, using the cglib dynamic proxy facility. The article is very worth reading. As a developer on a daily basis I’ve never seen a concrete use of this programming feature, despite being very interesting. Have you ever used the delegate feature?

Tags: , , ,

Swing tips and tricks

Some days go I was given the task to customize the Java Swing widgets for a project in our company. The default look and feel of a JDialog, specifically, has the Java logo trademark icon on the upper corner left, the close button on the right one and the title panel is painted according to the default MetalLookAndFeel probably. As an example, we have something like this:

We wanna have an option to change the title’s panel color, to remove the close button and not to have the Java trademark logo showing on the panel. The final JDialog should look like this:

I’ve thought it was a nearly difficult task, because I had to override a default look and feel and some hidden properties, sometimes difficult to find. Shame on me. Searching through some forums, I’ve found some interesting tips and tricks about how to customize a the entire dialogs of a Swing application, even without creating a look and feel or overriding an old one.

For your knowledge, here are some overridden properties to make the JDialog seems like the latter above. These properties let you define new colors for the active caption of your widgets, other font colors, custom family types and much more (for other properties see through the documentation API or the forums below).

UIManager.put(“activeCaption”, Color.BLUE);
UIManager.put(“activeCaptionText”, Color.WHITE);
UIManager.put(“InternalFrame.titleFont”, new Font(“Arial-12-i-2”, Font.BOLD, 11));
Border cuverdBorder = new LineBorder(new Color(210, 210, 210), 2, true);
dialog.getRootPane().setBorder(cuverdBorder);
dialog.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame.setDefaultLookAndFeelDecorated(true);
dialog.setUndecorated(true);

As a little example, below is the Java code to remove the close button from the panel’s title. This little code snippet below traverses the component hierarchy, passed as a parameter, in a recursive method.

   1:public static void removeCloseButton(Component comp)
   2:{
   3:    if (comp instanceof AbstractButton)
   4:    {
   5:        Action action = ((AbstractButton) comp).getAction();
   6:        String cmd = (action == null) ? "" : action.toString();
   7:        if (cmd.contains("CloseAction"))
   8:        {
   9:            comp.getParent().remove(comp);
  10:        }
  11:    } else if (comp instanceof Container)
  12:    {
  13:        Component[] children = ((Container) comp).getComponents();
  14:        for (int i = 0; i < children.length; ++i)
  15:        {
  16:            removeCloseButton(children[i]);
  17:        }
  18:    }
  19:}

Here are some Sun forums I’ve searched so far to find the possible helps for this solution:

Hope you make use of those tricks in your projects :-).

Tags: , ,

The war between Apple and developers

Cédric has posted an interesting point of view about the war between Apple and the developers. This war started when Java developers knew Leopard doesn’t include Java. Cédric resumed Apple’s position in one paragraph, saying:

“What is needed in Cupertino is a radical change in attitude. Dropping the elitist behavior is a mandatory path to success for Apple, and listening to hordes of developers banging at your door is a good first step. Apple doesn’t need to implement Java, but they could show a little bit more willingness to work with whoever is interested in helping take their platform to the next level. Dumping Objective C is probably not an option, but making other languages first-class citizens on a top-notch IDE would undoubtedly go to great lengths toward making this goal a reality (ask Microsoft how Visual Basic and Visual Studio worked out for them). I’d start with C++, maybe C and even some sort of Basic. Hell, just swallow your pride and create a Visual Basic clone for Mac OS.”

Tags: , , ,

Do you need closures in Java?

TheServerSide has raised a question about whether closures proposals to be implemented in the Java language are really necessary. In my opinion, I think the Java language must be as it is, because:

  • Generics syntax introduced in Java 1.5 are very difficult to understand and parse when code is read; mixing it with closures will keep the code a little messy;
  • People would prefer to do things in the way they are used to, instead of learning a new construct in the language to implement their tasks (it’s better to focus on code maintenance and readability, after all, code is more read than written);
  • Anonymous-inner classes are far less readable than inner classes, imagine when closures appear in such a code;

So, I think it’s better to maintain the language with the abstractions it already offers and focus on other improvements, like reifiable generics, that is, making generic type information available at runtime. And you? Will you think useful closures on the Java language?

Tags: ,

Checked or Unchecked?

Nice post from Bruce Eckel about whether Java needs or not checked exceptions. I have to admit, I changed a lot my thougths about using checked exceptions in Java code with this post. He explains why it’s better to use unchecked exceptions instead of checked ones with some good arguments, like the possibility to swallow the exception inside an empty catch block and loose the stack trace information. The programmer is tempted to swallow the exception because he’s forced to catch it and write reams of code around the exception. Bruce also states, emphasizing the use of unchecked exceptions:

“If I want to catch the exception, I can, but I’m not tempted to swallow it just to avoid writing reams of code. If I don’t’ want to write around the exceptions, I ignore them, and if one comes up it gets reported to me during debugging, and I can decide how to handle it then. I still deal with the exception, but I’m not forced to write a bunch of code about exceptions all the time.”

I think there’s a tendency to apply checked exceptions because people are used to static type checking, people are afraid to catch errors at runtime, static type programming languages forces this. People from Python, Ruby are used to the unchecked approach, because those languages are dynamically typed, so, there’s no pain :-). Now I prefer to use unchecked exceptions rather than checked ones because I agree with Bruce’s arguments and I’m moving my thoughts forward to dynamically typed languages. And you, what do you think about using checked / unchecked exceptions? Do you have a different opinion?

Tags: