Posts Tagged java

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);

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.

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?


Indicating the absence of an object

Sometimes I’ve seen some Java code intended to indicate the absence of parameters, that is, code validating null parameters (every public method must have a test to check against null parameter), verifying if a certain range is respected (like date, number ranges) and other kinds of contextual validation before calling the objects’ public methods. Some validation code (written in Java) is shown below:

At class Player:

public void pickUp (Item item)
   assert(item != null): "item cannot be null";
   // some code here

The above code uses Assertions, introduced in JDK1.4, to validate the item parameter. If item is null, an AssertionError will be thrown with the message “item cannot be null”.

public void drop (Item item)
   if(item == null) {
      throw new IllegalArgumentException(“item cannot be null”);
   // some code here

This above one uses an IllegalArgumentException, which is a RuntimeException, to report a null item.

public boolean addToInventory (Item item)
   if(item == null) {
      return false;
   // some code here

And this above Java code snippet returns false if an item is null.

or, maybe, applying the NullObject design pattern:

class NullItem implements Item

and at Player it becomes:

public void drop (Item item)
   // some code here

The last avoids a lot of tests to see if the parameter is null, replacing the tests with an object that provides the appropriate null behavior (“do nothing” behavior).
The question is: which do you think is the best way to indicate the absence of such an object? Which do you use often? Tell me if you use another approach to report this.


Open sourcing Java with GPL license?

CRN is announcing that Sun is set to put JavaMe and J2SE under the GPL license. Last months Sun commented about putting its Java plataform under a public license, but they were deciding which license to put Java into. Now the preferred choice is GPL. I think it’s to promote and increase Sun’s reputation in the open-source community. However, as the new said, a GPL license would require those developers making changes to the core Java platform to freely release their code. What do you think about this? Has Sun made the right choice? And what about Apache’s license?