Val's Blog
Lots of stuff for Web 2.0 freaks and Java addicts
Feeds RSS | Atom | RDF
 
 
Albert Einstein: "Intellectuals solve problems: geniuses prevent them."
[ Login ]

May 2004
SunMonTueWedThuFriSat
       1 
 2  3  4  5  6  7  8 
 9  10  11  12  13  14  15 
 16  17  18  19  20  21  22 
 23  24  25  26  27  28  29 
 30  31      
Apr  |  Today  |  Jun
XML Feeds   Subscribe with Bloglines

Javaranch Sheriff   My LinkedIn Profile
Drop me a line or two   Bloglines Blogroll
JavaRSS   Referers
How cool are you?   My Reviews

Next trips...
SpringOne 2008 (Jun 11-12, 08)
Ajax Exp. 2008 (Sep 29-Oct 1, 08)
Top 10 entries (#hits)
(As of Nov 30, 2007)


Top 10 entries (#hits/day)
Come Back (5.032)
(As of Nov 30, 2007)
Recent Blog Entries
Recent Blog Comments
Re: Review of "Marketing Management 12th"
i know marketing management by kotler is good book but the problem is that the management part of this book is totally missing as fare as i know managemet is complete different subject and it should not be mixed i am student of MBA i was looking at ass...

Re: Review of "Pro Spring"
Using simple POJOs + factories without Spring for "echo" and "counter" would be a lot more easier. No need to write those XML files... So, in this case using Spring makes me write a lot more code... (OK, you can generate everything with the help of And...

pls urgent
Hi I am trying to generate the word doc but i m not understanding wats happening any one pls figure it out /* * WordAPI.java * * Created on May 30, 2006, 10:50 AM * * To change this template, choose Tools | Template Manager * and open the te...
Archives (# entries)
Links
Other Blogs
Other Blogs

Reviewing
Reading
Locations of visitors to this page
What they once said...
 

It's no secret that primitive and reference arguments are always passed by value in Java. This means that a copy of the primitive value, respectively a copy of the reference to an object, is actually passed on to the method as depicted in the small example below.

Code view Object graph view
    [...]
5.  public void method1() {
6.    Vector v1 = new Vector();
7.    method2(v1);
8.  }
9.  public void method2(Vector v2) {
10.   // the original reference to the Vector
11.   // object in method1 does not change
12.   v2 = new Vector();   
13. }
    [...]
  
  Line 6: v1 -----> Vector 1

  Line 7: v1 -----> Vector 1
                       ^
                       |
          tmpcopy -----+
  // tmpcopy is a copy of the reference 
  // v1 that is passed to the method

  Line 9: v1 -----> Vector 1
                       ^
                       |
          v2 ----------+
  // v2 is conceptually the same
  // reference as tmpcopy

  Line 12: v1 -----> Vector 1

          v2 ---> Vector 2
  

In clear, every primitive or reference value that gets passed to a method usually goes unaffected and the caller can be sure that the value he passed has not been changed in the body of the called method.

The designers of the Java language originally decided not to include pass-by-reference semantics into the language in order to prevent some obscure things that have been known to happen in C++ programs to occur within your Java program. Briefly, in Java all parameters are IN parameters, which doesn't mean that you cannot invoke methods on the reference you get in order to alter the state of the object!!

Now, there are some areas like distributed computing where it might be sometimes desirable to pass objects around by reference. For instance, CORBA has the concept of "Holder" classes to simulate the behavior of INOUT or OUT parameters. Holder classes usually contain a reference to some value that the caller wants to be changeable from within the called method. By using OUT or INOUT parameters, a method may possibly "return" several values. This wrapping trick can help you bypass Java's requirement of having at most one value being returned from a method call. A small academic example illustrates this concept below:

    // In file Holder.java
1.  public class Holder {
2.    public String value;
3.    public Holder(String initial) {
4.      this.value = initial;
5.    }
6.  }
    
    // In file Test.java
1.  public class Test {
2.    public static void main(String[] args) {
3.      String hello = "Hello";
4.      Holder holder = new Holder(hello);
5.      method1(hello);
6.      String ret = method2(holder);
7.      System.out.println(hello); // prints "Hello"
8.      System.out.println(holder.value + ret); // prints "Hi James"
9.    }
10.   public static void method1(String s) {
11.     s = "Hi";
12.   }
13.   public static String method2(Holder h) {
14.     h.value = "Hi ";
15.     return "James";
16.   }
17. }
  

You could as well use an Object[] array and modify its components from within the called method. Moreover, since primitives are not objects (at least until the Tiger gets unleashed), they are always passed by value. If you want the called method to change the value of primitives you pass to it, you just have to wrap them within a primitive array (i.e., int[], long[], etc) and modify the values directly in the called method.

On the other hand, you might ask yourself whether you really need to return several values from your method calls. Usually, when this case arises, it is usually a sign of poor object-oriented design. Using OUT or INOUT parameters makes your code harder to understand and to maintain. The semantics of the Java language is usually sufficient for solving 99.9% of the problems you may come up with. So maybe, you might have to rethink your design and see if the values you have to return might not be better bundled in some new class...

Personally, I must admit that I have never really used this technique in any of my applications and I don't think it brings much business value, but it is good to know that it is possible to simulate pass-by-reference semantics and to be able to "return" more than one value from a method call. Not all inventions and findings are useful ;)

Ever wondered what evil power can be unleashed when using reflection? Do you think private methods are really only accessible from within the declaring class? Do you think that a private field can only be modified from within the declaring class? No? That's what I thought!! In this blog, I will try to demonstrate that it is always important to correctly set the security properties of your applications. For instance, let's look at the following example where we successfully retrieve a private password from another class:

1.  class A {
2.    private static String getPassword() {
3.      return "someHighlyPreciousPassword";
4.    }
5.  }
6.
7. public class Test {
8.   public static void main(String[] args) throws Exception {
9.     Class cl = Class.forName("A");
10.    java.lang.reflect.Method[] m = cl.getDeclaredMethods();
11.    m[0].setAccessible(true);
12.    String password = (String) m[0].invoke(null, null);
13.    System.out.println("I got it:" + password);
14.  }	
15.}
  
Output:
 I got it: someHighlyPreciousPassword
 

Ok, the example is not really sexy. Let's mess up a class that implements the Singleton pattern. In the normal case, a singleton object is supposed to be the only instance of a given class. To achieve this, we usually declare the class constructor private, so that no one can invoke it. Well, as demonstrated below, with reflection we can bypass this restriction and create a second "singleton object".

1.  class A {
2.    public static final A singleton = new A("I'm the only instance of class A");
3.    private String name; 
4.    private A(String name) {
5.      this.name = name;
6.    }
7.    public String toString() {
8.      return this.name;
9.    }
10. }
11.
12. public class Test {
13.   public static void main(String[] args) throws Exception {
14.     Class cl = Class.forName("A");
15.     java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
16.     c[0].setAccessible(true);
17.     A anotherA  = (A) c[0].newInstance(new Object[]{"Not anymore!!"});
18.     System.out.println(A.singleton);
19.     System.out.println(anotherA);
20.   }	
21. }
  
Output:
 I'm the only instance of class A
 Not anymore!!
 

Using this technique, you can create an instance of any non-abstract class, even if all its constructors are declared private. For instance, below we create an instance of the Math class even though it is useless since the Math class has no instance method. Still, it is possible to do it.

1.  public class Test {
2.  public static void main(String[] args) throws Exception {
3.      Class cl = Class.forName("java.lang.Math");
4.      java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
5.      c[0].setAccessible(true);
6.      Math mathInstance = (Math) c[0].newInstance(null);
7.      System.out.println(mathInstance);
8.    }
9.  }
  
Output:
 java.lang.Math@1cde100
 

Finally, let's mess with the Runtime class which has one private static field for storing the current Runtime instance. This is another example of a badly implemented singleton class. Let's look at the code below. We first retrieve the current runtime object and display it (3-4). Then, we set the Runtime.currentRuntime static field to null, which means that all successive calls to Runtime.getRuntime() will yield null (6-9) since currentRuntime is initialized at class loading time. We then get the currentRuntime field again and display its value (11-12). And finally, we try to use the current runtime to execute a command for displaying the content of the current directory (14). The output talks for itself.

1.  public class Test {
2.    public static void main(String[] args) throws Exception {
3.      Runtime r = Runtime.getRuntime();
4.      System.out.println("Before: Runtime.getRuntime() yields " + r);
5.
6.      Class cl = Class.forName("java.lang.Runtime");
7.      java.lang.reflect.Field f = cl.getDeclaredField("currentRuntime");
8.      f.setAccessible(true);
9.      f.set(null, null);
10.
11.     r = Runtime.getRuntime();
12.     System.out.println("After: Runtime.getRuntime() yields " + r);
13.
14.     r.exec("dir"); //raises NullPointerException!!
15.   }
16. }
  
Output:
 Before: Runtime.getRuntime() yields java.lang.Runtime@cac268
 After: Runtime.getRuntime() yields null
 Exception in thread "main" java.lang.NullPointerException
       at Test.main(Test.java:59)
 

All this could have been avoided if the currentRuntime field had been declared final. Nothing prevents setAccessible(true) to be called on the field (8) but when the set(null, null) method is called, IllegalAccessException is thrown with the message "Field is final".

I'm pretty sure that there is a huge amount of code out there that could be broken this way. Watch out!!
Bottom line: singleton fields should always be declared private static final!!! Moreover, make sure you never grant ReflectPermission and RuntimePermission.accessDeclaredMembers in the java.policy file of your production code.

I have just finished reading "Secure XML - The New Syntax for Signatures and Encryption" by Donald E. Eastlake and Kitty Niles. I'm pretty much happy with what I have read in this book. It wouldn't have hurt to see the presented standards applied on concrete case studies, though. This is what cost the book two horseshoes. No big deal!!

My review follows (also available at Javaranch.com):

When looking back, it is safe to say that using XML has become one of the most preferred ways of transferring data across the web. With the rise of web services and given the way the Internet is organized and governed, this ubiquity raises the fundamental issue of how to effectively protect the content of an XML transmission at the application level.

This book presents the efforts of two well-known consortia (IETF and W3C) working on the XML Digital Signature, XML Encryption and XML Key Management System standards. This book is meant to be within anybody's range as prerequisite knowledge in neither XML nor cryptography is required. Consequently, this means that about a third of this 500 pages book is dedicated to introducing both topics.

The authors do an outstanding job of presenting the technical details and cover areas such as, XML basics, digital cryptography fundamentals, XML canonicalization techniques, XML encryption, and key management. This is one of the most comprehensive resources on the subject currently available in store. I really enjoyed reading it and I would recommend it to any developer in need of a solid understanding of how XML communications can be protected against undesirable intrusions.

On the downside, even though the authors have presented two concrete applications of XML digital signatures (i.e., P3P XMLDSIG and SOAP XMLDSIG profiles), I would have much appreciated to see a case study about a plausible application of the technologies presented and how they fit into the big picture.

Imagine software components that could adapt to each other and dynamically elaborate and fine-tune the protocol(s) they would like to use in order to collaborate. Imagine that we could actually develop pieces of software that would be smart enough to discover the presence (or absence) of well-known patterns in an environment thereby enabling them to participate in the collaboration governed by the newly discovered patterns. Even though some of you will say that many research dollars have been (and are still being) spent on this topic and that not much has come out of the labs yet, I have to believe that something cool and promising will come out in the future.

In Jaron Lanier’s opinion, in order to attain the goals mentioned above, we have to rethink the way we develop software. Lanier coined the expression "phenotropic computing" for qualifying this new kind of software.

  "Phenotropic" is the catchword I'm proposing for this new kind of software. "Pheno" refers to "phenotype," the outward appearance of something. "Tropic" means interaction. [...] In phenotropic computing, components of software would connect to each other through a gracefully error-tolerant means that's statistical and soft and fuzzy and based on pattern recognition in the way I've described. [...] In software, there's a chaotic relationship between the source code (the "genotype") and the observed effects of programs -- what you might call the "phenotype" of a program. And that chaos is really what gets us. I don't know if I'll ever have a good idea about how to fix that. I'm working on some things, but you know, what most concerns me is what amounts to a lack of faith among programmers that the problem can even be addressed. There's been a sort of slumping into complacency over the last couple of decades. More and more, as new generations of programmers come up, there's an acceptance that this is the way things are and will always be. Perhaps that's true. Perhaps there's no avoiding it, but that's not a given. To me, this complacency about bugs is a dark cloud over all programming work.  

In the previous part of this odyssey, I stated that the way we develop software today is doomed to fail because current software engineering technologies (processes, methodologies, programming and modeling languages et al) don’t let us cope well with the ever-increasing complexity of existing and future software systems. As Lanier said in his interview,

  I suppose we are all so emotionally committed to the particular problems under our noses that we lack the long-range faith that software could be fundamentally better. That's the long-range faith that drives fields like medicine, and I want to try to bring that faith back to computer science."  

I completely agree with his first sentence, but not with the second as I’m not really sure there is any "long-range faith" that has ever driven computer sciences so far. However, I think that this is rather legitimate as the software engineering area is one of the youngest of all engineering domains. Even though it is one of the most rapidly evolving engineering area, it still needs to mature quite a lot. Apart from that, I think we all agree that we have to come up with new ideas to make software become fundamentally better. In order to achieve this, we have stop for a second and think about how we would like to develop software tomorrow. Today, when we talk about developing software, we almost directly think of it in terms of code. This is pretty normal as the code is pretty much all we have to comprehend and reason about the behavior of a software system and at the end of the day this is more or less what you feed into the compiler to build your system. According to this, some people will argue that the design of their software is fully contained within the code. While this is correct to a certain extent, this is a very dangerous statement as the design should offer a much more abstract view of the software than the code does. Moreover, there are plenty of things that we cannot express in code and that are better specified somewhere else. The only reason why I would agree to this idea (i.e., the code is part of the design) is that today we dramatically lack techniques for accurately synchronizing design and code and that we have to somehow build our system one way or the other even if we don’t have the right tools. This is really sad, but I’m pretty sure many people do actually manage the design of their software at the code level. Still, I’m really not convinced that their approach can be effective for any software systems whose code base grows over, say, 50’000 LOC.

Finally, I kind of liked the metaphors Mike Loukides used to vulgarize Jaron Lanier’s definition of "phenotropic computing"

  The fundamental idea behind the articles that Jaron Lanier has been publishing in the past few months is that protocols should be designed around the idea of "what are you trying to tell me to do" , rather than "that was an illegal operation" (404: not found). I hate the name "phenotropic computing", but his ideas are extremely important. [...] "How do I figure out what you really want me to do" is clearly the question we ought to be asking.  

While the advantages of annotating the code (JSR 175 - Metadata Facility for Java) are somewhat clear to me, I have been wondering what the drawbacks could be. I don't deny that being able to specify auxiliary information for classes, interfaces, fields and methods is a good thing. What I question is the means we will supposedly use to achieve this, namely, we will be putting the whole stuff directly within the code. If not used with care, annotations could (and most certainly will) massively contribute to code pollution as legitimately pointed out in James Strachan's web log this morning.

James also mentions that future IDEs should be made more clever and handle most of these boring details for us. For the most geekish of us, I can also imagine a functionality where we can define the granularity of the details we want to see in the code and then use some sort of slider control to zoom in/out the code details. Yesterday, the Eclipse community announced that code folding has been added to their IDE. Great!! I see this as a first step towards removing visual clutter in a selective and temporary way. Although, much more will have to be done in order to allow developers to use their eye power more efficiently.

Actually, the problematic is quite simple: we want to get rid of the many different documents that describe some aspects (not necessarly meant in the AOP sense) of the same concepts and put everything together at one central place, namely in the code. That way, it seems to be less likely that we forget something when we have to do some changes. While this is questionable, I don't doubt in the expressive power of annotations. What I fear is that this expressiveness could be used (inadvertantly) in a way that ends up not being beneficial to developers, thus defeating one of the primary goals it way initially intended to attain.

This pretty much goes in the same direction as mentioned in my previous blog, namely that current tools will have to be considerably improved to successfully address problems such as this one in the future.

"How will we develop software in 50 years from now?" As a passionated developer, this is one of the questions that often crosses the maze of my neuronal highway. I think this question is more than legitimate given the ever-increasing complexity of the tasks that have to be carried out by software systems and the pace at which new technologies are created.

I have a very personal opinion on this problematic which I have shared with some close friends and coworkers of mine. Personally, I think that the way we are creating software today is doomed to failure. Don't get me wrong, I'm a passionated developer, I love coding, I could spend my whole days and nights on coding new software.

It's just that I don't see current practices going anywhere mainly because of the complexity we are asked to handle. Of course, some of you will argue that if the software is architected and designed correctly (whatever that means), the complexity would be kept to a minimum. Basically, if complexity shows up, there must be a problem with your design. I don't agree with that since I'm of the opinion that the complexity lies in the problem at hand and it is neither removable nor negligible.

My opinion is that today we dramatically lack tool support not only for dealing with this complexity but also for tracking it down into the software that realizes one solution of the problem. A project usually involves an heterogeneous group of stakeholders (analysts, developers, architects, marketers, project managers, end users, HR, etc) who all have different interests in the project. How do we measure the impact of change if one or more of those stakeholders change their mind during the project? (Every sensible person knows that changes do happen!! A lot and often!!) How can we discover where and how the software will be impacted by the changes? Even if we do know where to make the changes, how do we know that we have applied them consistently across the whole software? Even if we apply them consistently, how do we know that we haven't forgotten to change some other code that is related to the code that has just been updated? As we have seen yesterday, MDA is supposed to partly solve this problem, but this is not going to happen anytime soon. It won't hurt to keep an eye opened, though :)

Some of you will argue that XP best practices and agile processes are already taking care of this. Well, in a certain sense they are, but I dare you to find one single tool that includes and automates these practices. In the future, we will have to come up with smart tools that somehow "participate" in the development process and proactively assist all the project stakeholders. In the future, we won't need passive code editors and/or modelers anymore. What's more, since the project stakeholders all come from different places in the company (or even from other organizations), we will need tools that can share all the digital resources of a project in a much better way than CVS does today.

I'm having a nice discussion on Javaranch.com about this. Agreed, this is no pic-nic, but I can assure you that it will be a fun ride :)

I have found Dan Haywood's article on TSS titled "MDA: Nice idea, shame about the..." very interesting. It's kind of a high-level analysis of where MDA is today and how it will "probably" evolve in the future. Dan also tries to answer very relevant questions as to why an organization would adopt MDA (or not) in the future.

Although I was already aware of the fact that there are two different actors on the MDA scene (elaborationists and translationists), the following statement hit me right in the face:

"At a minimum what this means to MDA adopters is that they should not expect PIMs developed with a tool from one camp to be usable in any form in a tool of the other camp. And the fact that two camps exist at all is disconcerting, to say the least. There ain't ever gonna be such a thing as a standard MDA tool."

If you come to think of it, this is really scary. MDA is still at an embryonic stage and there are already two very well demarcated camps who think they are on the right path. This is understandable in some way since usually when a new technology comes to life, everything has to be created and it is sometimes not easy to get people to look in the same direction and share the same opinions. Still, so-called *MDA-compliant* (whatever that means) tools already exist on the market. They comply to MDA but not to each other. Anything wrong here?! As an analogy, think about the chaos if a Java program written with JBuilder could not be opened in NetBeans. This is often the case when you use vendor-specific libraries (X-Y layout, etc) for building up your applications.

I would just like to continue on the same subject I started yesterday and give some more insights on the ongoing discussion.

Basically, Francis says: "Stop wasting your time with the SCBCD exam since EJB 2.0 will soon be overhauled by EJB 3.0. Better learn Spring and Hibernate instead."

While his statement his comprehensible up to a certain point, it does not make much sense given the way things work and the pace at which technologies evolve. JSR 220 mentions that EJB 3.0 will be released with J2EE 1.5 which has just been filed under JSR 244 and is not due until late summer 2005. As pointed out by Kathy Sierra in the same thread, "it [EJB 3.0] just won't be mainstream for a long time, and at Sun we want people to certify in something that is practical and useful for at least the next 18 months". She further adds that "...the main point is that EJB 1.1 and EJB 2.0 are what customers are using *today*, and will be continuing to use [...], for potentially another 18 months to two years or MORE".

So the bottom line is that the perceived value of a certification should principally lie in its practical applicability given the current industrial settings and community acceptance. Nobody in the thread argues that Spring and Hibernate are bad (I'm a fervent supporter of both), just that learning EJB 2.0 is neither a waste or time nor money given the fact that EJB 3.0 will be backward compatible.

First off, let me get something straight. I won't go into the ever-recurring theme of "certification value" and why one should or shouldn't not be certified, blablabla... All I want to show is that sometimes pragmatism and realism take over logics :)

In this post and this one, Francis is bragging about the merits of EJB 3.0 and telling people to stop wasting their time with the SCBCD certification because EJB 2.0 will soon be overhauled, and thus, the hardly gained certification will have no value at all.

To a certain extent, he is right. But what Francis is forgetting is that when a new technology comes out, it takes a subtantial amount of time to take off. Industry acceptance is not always straightforward, and even if it is, internal processes and custom practices usually have the last word. People don't use a technology because it is good or because it brings plenty of added value, people use a technology because it is useful to them for their particular needs. Times where we were using a technology just because it was trendy are (fortunately) over. People are now much more reluctant when it comes to make major changes to their systems. Remember the old saying: "If the thing ain't broke, don't fix it". If the whole stuff works with EJB 1.0 or 2.0 for that matter, why on earth would I turn everything upside down to use the latest tech that hasn't made its proofs yet and hasn't even been accepted by a majority of industry actors.

Moreover, as I said to Francis and as far as the certification is concerned, my opinion is that in order for engineers to solve problems efficiently, it is not only important for them to know the technology as it is today, it is also important that they know how it was yesterday!! This is what I call technological culture. It is all about the "Know your enemy" thing, where I compare enemies to the issues of the old specs that you have to master in order to comprehend why and how the new spec gets over them.

I have reviewed "Hardcore Java - Secrets of the Java Masters", the latest title from O'Reilly written by Robert Simmons Jr. I must admit that I'm pretty disappointed with it and I'm not the only one (here, here, here and here).

My opinion is that there were way too many typographical errors in there. Moreover, many topics handled in the book were not that "hardcore" at all. As the book is not that thick (300 pages), I don't think it was wise spending 30 pages on Java 1.5 while a full-blown book from the same publisher (due in June) will be dedicated to the very same subject...

I just hate it when books are rushed to press to the detriment of quality. Coming from a usually high-quality publisher, this really surprised me. Let's hope the second edition will undergo a major rewrite.

My review follows (also available at Javaranch.com):

My first thought when I saw this new book on O’Reilly’s web site was: "Well, there must be some really cool Java hacks hidden behind this rather evocative title."

Basically, it’s one of those books where you expect the next page to actually delve into the real matter and give you some crispy details. My personal impression after finishing it was that the content was a little lightweight for deserving to be qualified as “hardcore”, but maybe I’m being too harsh. The author handles a good deal of “advanced” topics, such as the effective use of Collections and nested classes, constants, immutable types, reflection, proxies and the four different flavors of references. Also qualified as hardcore, the novelties introduced by the upcoming Java 1.5 release are also part of the story...

I have always regarded O’Reilly’s books as high-quality work (and I still do), but I have never been able to find 50 typos in any of their books before. I’m inclined to interpret this fact as if the book had been rushed to press to be on the shelves before JDK 1.5 comes out. I just wish the book had been more thoroughly proofread.

On a more positive note, I’m quite sure medium and advanced Java programmers will be able to distill valuables tips and tricks from this book. On the companion web site, the author also provides the sources of all the examples illustrated in the book.

Open-sourcing Java seems to be a recurring theme since Eric S. Raymond, President of the Open-Source Initiative, opened the debate back in February.

Last week, Joshua Marinacci blogged about the benefits and problems of open-sourcing Java and made a rather good analysis of the situation. Also worth reading, James Gosling's blog on the subject.

What comes out, in my opinion, is that there are lots of parameters to take into account and that such a "decision" is not a simple yes-or-no answer. Also, I have no real opinion (yet) as to whether Java should better go open-source or not. All I know is that it is virtually impossible to get all the benefits without accepting some drawbacks: it is all about compromises. This is how (almost) everything works, and Java will be no exception.

 
About this Blog