EJB 3, the New JavaBeans?

Home

News: EJB 3, the New JavaBeans?

  1. EJB 3, the New JavaBeans? (63 messages)

    Gavin King has predicted that the EJB 3 programming model will eventually be to Java development what JavaBeans is now. He provides a list of reasons as to why JavaBeans were so successful, and sees the EJB 3 component model as an enhancement to JavaBeans: JavaBeans with "extra" semantics, defined by the spec's general-purpose annotations.

    Read EJB 3, the New JavaBeans?

    Threaded Messages (63)

  2. Well, I still do not like getter/setter convention and get/set/is prefixes in silly methods, which have only goal to satisfy bean spec. Why Java does not have ‘property’ keyword? It is so damn convenient in Object Pascal (Delphi):
    property myProperty;[ read readMyProperty ][ write writeMyP_r_o_p_e_r_ty ];

    No more silly typing and ability to have more appropriate names for properties like: hasParens, or wasAccessedRecently.
  3. Well, I still do not like getter/setter convention and get/set/is prefixes in silly methods, which have only goal to satisfy bean spec. Why Java does not have ‘property’ keyword? It is so damn convenient in Object Pascal (Delphi):property myProperty;[ read readMyProperty ][ write writeMyP_r_o_p_e_r_ty ];No more silly typing and ability to have more appropriate names for properties like: hasParens, or wasAccessedRecently.
    Maybe you are right. They are overhauling so much in Java 1.5 and EJB 3 why not just go for broke? Maybe get that "goto" reserved word to actually do something :-)

    Whether or not the get/set/is convention is inconvenient, the greatness of its universal acceptance is the point. Whenever a standard can be agreed upon developers win. It would be detrimental to change that aspect of Java now. One bright-side of the sometimes-clumsy naming scheme is that you can pretty much tell the fields from the methods without having to look at the class definition.

    I hope that EJB 3 will simplify coding server-side objects as much as they seem to promise. I like what I've read in the spec so far.
  4. Is JavaBeans that convenient?[ Go to top ]

    I agree with Konstantin; get/set Javabean convention is a pain in the arse. It's not so much the name pair of getX/setX but it is the necessity of having to write the stupid do-nothing accessors/mutators in the first place. Plus, IMO it tends to lead to a bunch of objects which are nothing but a fancy struct, i.e. a data container with no behaviour. I would have preferred Java "5" to have acquired the keyword 'property' and some definied behaviour in relation to this in preference ahead of a lot of the other new features. (for example, 'property' keyword could be an instruction to the compiler to generate said accessor and mutator methods for you thus maintaining backwards compatibility).

    Back to the main article, however, I don't have a big issue with what Gavin said. I think he has a point; instead of people getting all wound up over EJBs (IMO it's really CMP+BMP that most people really despise) they will be be able to utilise them simply and effectively without having get mired in the complexity of their deployment - surely the number one criticism made of EJBs in the past. People who say 'oh you can do it with Spring (or whatever IOC/leightweight buzzword container you prefer)' seem to me to miss a point; Spring (or whatever) is still a form of container that needs to be configured and deployed. And typically in the client environment, the big brand J2EE servers are often trusted simply because of what they are and who makes them. Plus if you've already got one in production (obviously not EJB 3 compliant at this stage), why not use what resources you are already using (cf Martin Fowler 'Sunk Cost Architecture').
  5. Well, I still do not like getter/setter convention and get/set/is prefixes in silly methods, which have only goal to satisfy bean spec. Why Java does not have ‘property’ keyword? It is so damn convenient in Object Pascal (Delphi):property myProperty;[ read readMyProperty ][ write writeMyP_r_o_p_e_r_ty ];No more silly typing and ability to have more appropriate names for properties like: hasParens, or wasAccessedRecently.
    Maybe you are right. They are overhauling so much in Java 1.5 and EJB 3 why not just go for broke? Maybe get that "goto" reserved word to actually do something :-)Whether or not the get/set/is convention is inconvenient, the greatness of its universal acceptance is the point. Whenever a standard can be agreed upon developers win. It would be detrimental to change that aspect of Java now. One bright-side of the sometimes-clumsy naming scheme is that you can pretty much tell the fields from the methods without having to look at the class definition.I hope that EJB 3 will simplify coding server-side objects as much as they seem to promise. I like what I've read in the spec so far.
    And how am I supposed to know the methods without having to look at the class definition? I completely agree with the other guy. I think it could be good to define the reserved word "property" for a field and let the compiler do the dummy getter/setter, which you can override if you need more complicated work to be done. This is similar to the auto-casting method return in the new spec 1.5

    He dicho
  6. Well, I still do not like getter/setter convention and get/set/is prefixes in silly methods, which have only goal to satisfy bean spec. Why Java does not have ‘property’ keyword? It is so damn convenient in Object Pascal (Delphi):property myProperty;[ read readMyProperty ][ write writeMyP_r_o_p_e_r_ty ];No more silly typing and ability to have more appropriate names for properties like: hasParens, or wasAccessedRecently.
    When I heard about annotation metadata, one of my first thoughts was that it would be cool to have an @property annotation that defined a bean property. A tool could then generate the field and getter/setter methods. Of course, you'd still be able to provide your own getters/setters when the simple default methods weren't sufficient. You could also have something like @validate that could auto-generate validation code in the setter.
  7. same thought here[ Go to top ]

    It was my first idea also. I kinda hoped one could write "compiler plugins" with annotations; I remember an article about the future of programming languages which had such a principle, look very interesting. Now one has to post-process a class file, but I'm sure this annotation will be available:

    private @getter @setter String name;
    private @getter @isser boolean active;

    private @getter String description;
    public void setDescription(String value)
    {
        if (value == null) throw IllegalArgumentException(...);
        this.description = value;
    }

    Or something similar.

    And maybe someone can finally explain to me what all this complaining about set/get not being OO is about? Interface and internal storage are separated, so we do have encapsulation. Only, coincidentally, the two overlap (often), so we use that fact.
    If I decided to store the name as part of a complex internal structure, I still can have setName/getName, just need to code it out. The set/get is part of the interface, the variable part of the internals of the class.
  8. When I heard about annotation metadata, one of my first thoughts was that it would be cool to have an @property annotation that defined a bean property. A tool could then generate the field and getter/setter methods. Of course, you'd still be able to provide your own getters/setters when the simple default methods weren't sufficient. You could also have something like @validate that could auto-generate validation code in the setter.
    That sounds pretty cool, good compromise to the pain of adding a new keyword.

    Wonder if being able to define @assertions will come too. I always liked the idea of being able to define preconditions and post conditions on methods - even with test-driven development.
  9. Well, I still do not like getter/setter convention and get/set/is prefixes in silly methods, which have only goal to satisfy bean spec. Why Java does not have ‘property’ keyword? It is so damn convenient in Object Pascal (Delphi):property myProperty;[ read readMyProperty ][ write writeMyP_r_o_p_e_r_ty ];No more silly typing and ability to have more appropriate names for properties like: hasParens, or wasAccessedRecently.
    Well, I suggest that you keep writing Pascal (Delphi) or maybe Visual Basic programs then. You don't need to write getters and setters there. I think you even don't need to worry about ANY coding convention there am I right?
  10. Well, I suggest that you keep writing Pascal (Delphi) or maybe Visual Basic programs then. You don't need to write getters and setters there. I think you even don't need to worry about ANY coding convention there am I right?
    There is a very big difference, Delphi and Visual Basic have recomended coding convention too, but this stuff in JavaBeans is not a coding convention it is comonent and container contract.
  11. Well, I suggest that you keep writing Pascal (Delphi) or maybe Visual Basic programs then.
    It is probably not possible to avoid comments like the one above. I just suggest accompany them by personal oath like this:
    - I swear not use any languages and systems other than Java, ever!
    - I do believe that everything people did in the past (or outside of Java) is wrong and evil.

    I also recommend reading “What's New Is Old Again” in JDJ.
  12. You should take a look at what object oriented means at first.
    Encapsulation, for instance.
  13. Well, I still do not like getter/setter convention and get/set/is prefixes in silly methods, which have only goal to satisfy bean spec. Why Java does not have ‘property’ keyword? It is so damn convenient in Object Pascal (Delphi):property myProperty;[ read readMyProperty ][ write writeMyP_r_o_p_e_r_ty ];No more silly typing and ability to have more appropriate names for properties like: hasParens, or wasAccessedRecently.
    I don't know about you, but I let my IDE do the "silly typing" for me ... I just invoke the "Add Property" menu item, and tell it the property name and type. And, if I'm really serious about changing getParens to hasParens, or isAccessedRecently to wasAccessedRecently, I tell it to make me a BeanInfo class too -- and every tool or technology that understands JavaBeans properties will use your methods. Anyone who tells you that you can't have property getters and setters with whatever name you want hasn't read the JavaBeans specs.

    Craig McClanahan
  14. Yes, it is possible to change read/write method names using BeanInfo workaround, but we are talking about properties, language feature. JavaBeans is a framework, it is ActiveX contols clone fo JAVA (hosted by IDE and "active" at development time), this stuff is useless for me at this time.
  15. Yes, it is possible to change read/write method names using BeanInfo workaround, but we are talking about properties, language feature. JavaBeans is a framework, it is ActiveX contols clone fo JAVA (hosted by IDE and "active" at development time), this stuff is useless for me at this time.
    Does that mean you are willing to give up getters for property values that are dynamically calculated, instead of just returning the value of an instance variable? Or property setters that have side effects? That may be OK for you, but I would certainly not be happy to lose those capabilities.

    Craig
  16. "Property" is an abstract component oriented concept. Field alone is not a "property", it is not "virtual" and it can not be defined in interface ( "interface" is a component oriented concept for contract ), method is not a "property" too, you need to declare it as "property" to edit it in "property editor" by contract, so "property" is more about metadata than about methods and fields. JAVA components (JavaBeans) use code or naming conventions for metadata and contracts, it is workaround, but it is not a very big problem in practice too. In component oriented languages this stuff is declarative, but it is not very usefull in practice too, so this is academic discussion :)
  17. Does that mean you are willing to give up getters for property values that are dynamically calculated, instead of just returning the value of an instance variable? Or property setters that have side effects? That may be OK for you, but I would certainly not be happy to lose those capabilities.
    It would be nice if there was a way to define these as they were needed. After all, the typical getter/setter method simply return/modify an instance variable. What would be great is for this to be the default behavior of a property methd (that we would not have to define and clutter up the code), but this could be overridden with custom behavior when needed.

    Ryan
  18. Any variable that is public should be public. If a "tool" needs to know how to get and set a variable, the "tool" should be able to identify public variables and create it's own get and set handling. The only reason to use bean syntax is if you have public variables that you don't want the "tool" to be able to get and set.

    But what if you one day change the behavior of your class on a public variable? Oh, no! that would require a code change which is bad. Don't be silly, your modified behavior is already a code change.
  19. I don't buy it.[ Go to top ]

    If you're not doing distributed computing then why are you using EJBs? Seriously, if you need services like transaction management and so on then I think the current IoC lightweight containers have shown that you can have a true POJO service object and you don't need the local stateless session bean overhead.
    Futhermore, the previous example EJB 3 entity bean isn't a POJO either in my opinion. If you're starting a new project and you have to have an id data member along with getter and setters in the objects that are to be persisted then I'm calling them APOJO: Almost a Plain Old Java Object. If an object knows that it has a persistent id then it's not a POJO (again, in my opinion). I don't see the need to have the id overhead in persistent objects (from the point of view that the objects know they have an id). Now, for a legacy application where you're mapping a table to a Java object then I can see where you need this.
    Tony
  20. Here's a concrete example of the kind of thing I expect to see happen. I think session beans make perfect web framework actions! Currently, if we want to call into the EJB container from Struts, we have to write an Action and explicitly look up and invoke the session bean. But imagine if the action were itself a local, stateless session bean: we'd get all the services of the EJB container, right there in the web tier. It gets better. If our actions are session beans, then instead of keeping state associated with the user in that demon-spawned-son-of-HashMap, the HttpSession (I usually need a shower after touching that thing), we could keep the session state in stateful beans (one per application transaction, of course).
    That definetely would be a great approach. But Struts already allows to do that with session-scoped form classes. Of course, id does not provide transaction support, which I think is the greatest EJB feature. Anyway, I personally do not like to mix transport objects which Struts form classes are, with presentation objects and with business objects. So, despite the fact that I can store most UI data in session-scoped form classes, I still use my own classes for that. I can manage them better, I do not need EJB container or Struts for that. So despite the prospect outlined by Gavin, I would not use this approach just like I do not use session forms. Well, maybe these lightweight EJBs will favor better because EJBs were meant to represent business objects.

    On Java Beans I agree with Konstantin. The approach copied by Java from C++ does not look pretty. Accessor methods are fine when you need to verify a value before setting it or even before returning it, but otherwise... According to company coding standards I have to write javadocs for a field itself, for getter and for setter. This is half a screen of text for a simple property. And if I skip on getters/setters and open a field to public, I get "field must be declared private" error thrown by Checkstyle. Object Pascal has a great notion of properties, and as far as I know, C# accepted the same approach. I'd rather see this change in 1.5 than generics.
  21. There is nothing wrong with HttpSession but it can not be replaced with session bean, it is different things and concepts, but with the same sufix. You must think about stateful session bean in the same way as bout JDBC connection or hibernate session. Stateful session bean is a very usefull thing, it is designed to propagate transaction and security context (form client thread to server thread) and it is nothing more.
    HttpSession
    "Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user."
    It is a mistake to confuse transaction and http session.
  22. There is nothing wrong with HttpSession but it can not be replaced with session bean, it is different things and concepts, but with the same sufix. You must think about stateful session bean in the same way as bout JDBC connection or hibernate session. Stateful session bean is a very usefull thing, it is designed to propagate transaction and security context (form client thread to server thread) and it is nothing more.HttpSession "Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user."It is a mistake to confuse transaction and http session.
    As I said, for me transaction control is the greatest benefit for using EJBs. And yes, the security, you mentioned it. All I wanted to say is that I have my persistence/business/presentation classes already cleanly separated, so it is unlikely that I would throw them out and stuff the same information directly into session beans just because it is now easier to do so.

    Also, despite of currently popular opinion, I like entity beans. They describe a business object and they provide transaction control. This is great, I do not have to lock a row in the database to ensure pessimistic locking scheme, I just set up my app server and then read a bean and write it back. In this case session bean is very convenient, I start EJB transaction in the session bean and propagate in on entity beans. On the other hand, session bean transactions without using entity beans do not provide that great behefit for me. They do not provide something that I cannot do myself using session object, JDBC and duct tape. Oh, right, clustering. But HttpSession can be clustered as well.

    I did not want to start HttpSession vs. SFSB flame again. I just mentioned that an approach suggested by Gavin is exciting but will not make a lot of difference for me.
  23. It is not a HttpSession vs. SFSB flame, it is a problem and I see no good solution for this problem. SFSB do not solve it too.
  24. "I like entity beans. They describe a business object and they provide transaction control. This is great, I do not have to lock a row in the database to ensure pessimistic locking scheme, I just set up my app server and then read a bean and write it back. In this case session bean is very convenient, I start EJB transaction in the session bean and propagate in on entity beans."

    Thank you, I use them exactly the same way. I would add the DTO's to represent the object graph needed to serve the use case in action. And the use case can occur by different clients, Web, SOAP, CORBA, etc.., at the same time. The concurrency and transaction services allows our business domain (local entity beans)to achieve re-usability across different applications. Also, container managed persistence (CMP), along with everything else, provides a compelling business case for J2EE.
  25. What is wrong with HttpSession?[ Go to top ]

    HttpSession can be used for a variety of reasons

    1)storing session related data is just one part of it and i think that this is where it performs better than SFSB, I would rather store my user related here than in a SFSB. Please comment.

    2)There are a listeners associted with the HttpSession which can help you a lot

    Why would Gavin have to take shower after touching HttpSession?????
  26. What is wrong with HttpSession?[ Go to top ]

    It very trivial HttpSession is designed to sore user related data, SFSB is designed to store transaction related data.
  27. What is wrong with HttpSession?[ Go to top ]

    1)storing session related data is just one part of it and i think that this is where it performs better than SFSB, I would rather store my user related here than in a SFSB. Please comment.
    You should not select HTTP Session versus Stateful Session EJB based on performance. They are designed to solve different problems; use the one that solves your problem best ;-)
    2)There are a listeners associted with the HttpSession which can help you a lot
    And you get to write your own Session EJB's, so you can have whatever listeners you want ;-) .. seriously, they are for two different problems, even though they both have "session" in their name.
    Why would Gavin have to take shower after touching HttpSession?????
    Maybe he touched the wrong HTTP Session? ;-)

    Peace,

    Cameron Purdy
    Tangosol, Inc.
    Coherence: Clustered JCache for Grid Computing!
  28. What is wrong with HttpSession?[ Go to top ]

    You should not select HTTP Session versus Stateful Session EJB based on performance. They are designed to solve different problems; use the one that solves your problem best ;-)
    Hum, the way most people think about this problem today is in terms of "state associated with the client". Unfortunately, I think this is a severe mis-statement of the problem. Or at least, there is a dangerous ambiguity in the word "client".

    We need to refactor this to read:

    (1) Where should I hold state associated with the user?
    (1) Where should I hold state associated with UI navigation?
    (2) Where should I hold state associated with the application transaction?

    So, in current J2EE architectures, it makes sense to hold user state and UI state in the HttpSession. Unfortunately, most people today also use the HttpSession to hold state associated with the "application transaction". This feels completely broken, since it puts state naturally associated with the business tier in the presentation tier. Even worse, it muddles the "user" scope with "application transaction" scope (a user can have multiple concurrent application transactions, but just one HttpSession), and this is a major source of bugs in J2EE webapps.
  29. What is wrong with HttpSession?[ Go to top ]

    Hum, the way most people think about this problem today is in terms of "state associated with the client". Unfortunately, I think this is a severe mis-statement of the problem. Or at least, there is a dangerous ambiguity in the word "client".
    Yes, client is not the same. Browser is the client in HttpSession case and
    RMI caller thread is the client in SFSB case.
  30. (1) Where should I hold state associated with the user?
    (2) Where should I hold state associated with UI navigation?
    (2) Where should I hold state associated with the application transaction?

    So, in current J2EE architectures, it makes sense to hold user state and UI state in the HttpSession. Unfortunately, most people today also use the HttpSession to hold state associated with the "application transaction". This feels completely broken, since it puts state naturally associated with the business tier in the presentation tier. Even worse, it muddles the "user" scope with "application transaction" scope (a user can have multiple concurrent application transactions, but just one HttpSession), and this is a major source of bugs in J2EE webapps.
    This is a great explanation. Now when I start to think about this, I still do not see much of a difference between HttpSession and SFSB... for optimistic transactions. Because what is an "application transaction"? Is it database transaction, or transaction on objects or something else? In case of optimistic concurrencty I would not even use the word "transaction" in regards to the stuff, that I hold in (HttpSession, SFSB) between requests. This is just some stuff, which may not be even persisted if a user backs out.

    Consider shopping basket. I have a catalog with all goods that I potentially can sell. I do not have all of them simultaneously, but I allow customers to select anything they want. So, the shopping cart -- is it part of transaction, and which one? I think, it is not. When a customer submits the basket, I run the script on the database, which starts and finishes database transaction, and responds with "Sorry, we are out of this and that". Well, customers surely would not like that ;) But would I need to keep a transaction to tell this to them?

    Pessimistic concurrency is totally different thing. I have to allow to select only items which are in store, and I must decrement their amount, so other customers would not select item which can be sold to other person. And I need to return it back if transaction rolled back. In this case I need to have long-living transaction with all proper locks and item counts. I can do this with database myself, but ELB already provide me with this feature. I think that CMP are quite in place here. I would run CMPs in the context of SFSB transaction and would be beyond happy.

    What I am trying to say, is that SFSB are really important for pessimistic concurrency. Optimistic scheme can make do with HttpSession simply because there is no transaction. Well, the [temporary] business data [along with UI information] would be stored on the web layer. It is not academic, riiight.
  31. What I am trying to say, is that SFSB are really important for pessimistic concurrency. Optimistic scheme can make do with HttpSession simply because there is no transaction. Well, the [temporary] business data [along with UI information] would be stored on the web layer. It is not academic, riiight.
    There must be no major difference in concurrency control algorythms from user point of view, if we are talking about "academic" concurrency control (but you need to know about it in practice for many reasons)
    There are a lot of concurrency control algorythms, but I do not know "pessimistic" concurrency control, "optimistic" is just one of aggressive concurrency control algorythms (executes operations and tests serialization graph later). Aggressive algorythms reject or resubmit conflicting operations,
    conservative algorythms try to delay conflicting operation to serialize transactions. Aggressive concurrency control is more scalable, but it rejects more operations, conservative way reject operations too (deadlock).
    As I understand stuff known as "optimistic locking" or "optimistic transaction" in current frameworks is conflict detection algorythm, it is not "academic" concurrency control and it has nothing in common with transactions.
  32. A http session is a type of transaction
  33. According to company coding standards I have to write javadocs for a field itself, for getter and for setter. This is half a screen of text for a simple property. And if I skip on getters/setters and open a field to public, I get "field must be declared private" error thrown by Checkstyle.
    I don't know whether to laugh or cry when I see this sort of thing. For each proprty, a few characters of code surrounded by six lines of boilerplate garbage, imposed by a corporate standard and/or tool like Checkstyle being applied with much zeal. Makes for interesting reading (oh really? So setName ... sets the ... $%$%@ NAME??!!!). Seriously, an explanation for a setter/getter is about as useful as an instruction on a door (to borrow Don Norman's example) - if you really have to tell someone how to use it, your design is flawed.

    Because many frameworks adhere to the setter/getter Javabean convention, the attributes themselves usually can't be public. However, there are two things that can be done:
    * Avoid setters and getters and properties themselves, since they mostly break principles of encapsulation and autonomy (the typical mindset of just creating an attribute and then pumping out a getter and setter is indeed evil).
    * Use one (count it) line for the method, minus any commentary, i.e.:
    public String getName() { return name; }
    At least you can now see all your setters/getters in the IDE at the same time!
  34. Laugh through tears[ Go to top ]

    Use one (count it) line for the method, minus any commentary, i.e.:public String getName() { return name; }At least you can now see all your setters/getters in the IDE at the same time!
    For the code, which I write for myself I use the following notation:
    <code>/*
     * Item id [INPUT/OUTPUT; PRIMARY KEY]
     */
     private String id;
     public String getId() {return id;}
     public void setId(String value) {this.id = value;}</code>
    Sometimes it gets like this:
    <code>/*
     * Persistence status, can be "New" or "Stored".
     */
     private String status;
     public String getStatus() {return status;}
     public String setStatus(String status) {
       /*
        * Do not allow to change from "Stored" to "New"
        */
        if ("Stored".equals(this.status) && "New".equals(status)) {
           return "item.badstatus";
        }
        this.status = status;
        return null;
     }</code>
    Notice that the mutator returns a value, which is not exactly along with Javabean specs. Whatever.

    The problem is, I still want comments. And I want them in the Javadoc help file too. If I use javadoc-style comment for field only, getter/setter obviously would not recieve it. Javadoc tool is not that smart (ugh, yet).

    But all this is only for my own use. I cannot use notation like this in company code. What is more, I cannot write methods in one line even if it a simple getter. We use Checkstyle and adopted a lot of its default rules. I cannot even write <code>if (obj==null) return;</code> without curly braces. Ah, well.
  35. If you have any reason at all to use a getter/setter you damn well better document why you're opening a database connection, adding 1 to the parameter, setting the value of three other variables, and sending an email. If all you are doing is assigning the value of one integer to another, you can do that with an equals sign. You don't need the overhead of creating a function, a temporary variable, and that very same assignation.
  36. If all you are doing is assigning the value of one integer to another, you can do that with an equals sign. You don't need the overhead of creating a function, a temporary variable, and that very same assignation.
    What if later you would need to check parameter to be, say, non-zero? You'd have to create a setter, thus breaking the interface with callers. The concept of property is better because if you add set validation or get postprocessing, you would need only to recompile, the source code would stay the same.
  37. C# properties[ Go to top ]

    Object Pascal has a great notion of properties, and as far as I know, C# accepted the same approach. I'd rather see this change in 1.5 than generics.
    This is off the original subject, but I've found that C# properties are almost useless. The reason is because they require the same access modifier for the getter and the setter.

    For example:

    public int ID {
        get { return this._id; }
        set { this._id = value; }
    }

    There isn't a way to make the getter public and the setter private.
  38. C# properties[ Go to top ]

    This is off the original subject, but I've found that C# properties are almost useless. The reason is because they require the same access modifier for the getter and the setter. For example:
    public int ID {    
      get { return this._id; }    
      set { this._id = value; }
    }
    There isn't a way to make the getter public and the setter private.
    You can of course opt not to define a setter and use the private field _id directly...

    However,

    private int ID;
    public int getID(){return ID;}
    public void setID(int value){ID=value;}

    even is one line shorter and with a decent Doclet you will only need to specify doc comments for the field.

    The C# property style pays off while using the objects in other code:

    if (object.ID == 0) object.ID = 1;

    is IMHO much more intuitive than

    if (object.getID() == 0) object.setID(1);

    but I guess that's mostly a matter of personal taste...

     -Markus
  39. baby and bathwater[ Go to top ]

    This is off the original subject, but I've found that C# properties are almost useless. The reason is because they require the same access modifier for the getter and the setter.
    C# props can be fixed to solve that problem relatively easily (IMHO) .. I personally like the idea of encapsulating fields behind properties, and have done it that way for years in Java (like C# but with access modifiers on the get and set.)

    Peace,

    Cameron Purdy
    Tangosol, Inc.
    Coherence: Clustered JCache for Grid Computing!
  40. baby and bathwater[ Go to top ]

    This is off the original subject, but I've found that C# properties are almost useless. The reason is because they require the same access modifier for the getter and the setter.
    C# props can be fixed to solve that problem relatively easily (IMHO) .. I personally like the idea of encapsulating fields behind properties, and have done it that way for years in Java (like C# but with access modifiers on the get and set.)Peace,Cameron PurdyTangosol, Inc.Coherence: Clustered JCache for Grid Computing!
    I agree. When I said the C# properties were useless, I meant as opposed to creating getter and setter methods instead. Sorry, I should have clarified further. FYI, C# 2.0 seems to fix this problem with properties and allow you to define the get/set separately.

    I agree it's a necessity to encapsulate everything behind an accessor/mutator rather than access the internal fields directly. That's why I'm confused why some people on this thread think JavaBeans are "crap".
  41. baby and bathwater[ Go to top ]

    I agree it's a necessity to encapsulate everything
    I guess many people (and me among them) disagree with necessity to encapsulate _*everything*_. There are cases when accessors/mutators are necessary, but also many cases when they are not needed (typical DTO use).
    Beauty of property is that if later an accessor or mutator methods introduced, rest of the code need not to be changed, as it was pointed, syntax is much cleaner : myObject.myProperty = something;
    and mutator gets called transparently if it is defined. This is exactly what happens behind the scene in scripting environments like JSTL EL, Jython, etc. So far I did not hear/read complaints about it.
  42. baby and bathwater[ Go to top ]

    I agree. When I said the C# properties were useless, I meant as opposed to creating getter and setter methods instead. Sorry, I should have clarified further. FYI, C# 2.0 seems to fix this problem with properties and allow you to define the get/set separately.I agree it's a necessity to encapsulate everything behind an accessor/mutator rather than access the internal fields directly. That's why I'm confused why some people on this thread think JavaBeans are "crap".
    They're crap, because they're mutable AND every property must be treated atomically. This makes it impossible to create an object that can guarantee valid state. A severe limitation that reduces JavaBeans to almost nothing more than a typesafe map.
  43. This is off the original subject, but I've found that C# properties are almost useless. The reason is because they require the same access modifier for the getter and the setter.
    C# props can be fixed to solve that problem relatively easily (IMHO) .. I personally like the idea of encapsulating fields behind properties, and have done it that way for years in Java (like C# but with access modifiers on the get and set.)Peace,Cameron PurdyTangosol, Inc.Coherence: Clustered JCache for Grid Computing!
    For my 2 cents, I also dislike the way the property can have only one access modifier. I do otherwise like the convention. Perhaps a Java innovation would be:

    property String SomeString {
      public get { return _strinvVal; }
      protected set { _stringVal = value; }
    }

    This is almost exactly like it is done in C# with extra flexability.

    In the meantime, in C#, I define the property as publicly read-only, then create a standard setter for use by code within the assembly:

    internal void setSomeString(string val) { _stringVal = val; }

    Also slightly off topic, the "internal" keyword grew on me, once I realized what it did (took me a few minutes). Java could benefit from an access modifier that works at the JAR level. This way, classes in "com.quoting" can do server-only things to classes in "com.groups" (in the same JAR), but you could still pass objects from either to presentation tier code, located in "myservlet.jar" (to get their properties, etc.) (note, this would be non-distributed stuff).

    David Bicking
  44. This changes in C# 2.0, just ran a test using Whidbey Beta 1, with the following code;

    public class Employee
    {
        protected int _id;

        public int ID
        {
           get { retun _id; }
           private set { _id = value; }
        }
    }

    Regards,
    Marlon Smith
  45. I'm quite familiar with this one. I really like .NET's "internal" modifier, too. The root of difficulty of the problem in Java is that Java's "package" modifier fused the concept of "namespace" with that of "component", whereas in .NET, these two concepts are kept completely separate, via "namespace" and "internal".

    The symptom in Java is that you have to raise to public members that you'd rather not have to make public, only because you placed them in different namespaces. Since to Java, the namespace is the same as the component, you're stuck. Since discovering this, I strive not keep the number of namespaces I author in Java to a minimum, and leverage the default ("package") access modifier to achieve .NET's "internal".

    If first-class recognition were given to JAR files, equating them to assemblies, Java code would be able to distinguish between the concept of "component" and "namespace". But, then what would we do with "package" for legacy code? What would it mean? Would we have to create a new keyword to define component-level access modifier?

    This will really take some thought on the behalf of the Java language Gods. I would have liked to see something like this is JDK 5.0, but no luck. I really am surprised it hasn't become a louder issue thus far.

    --matthew
  46. I hear what you're saying, but I have never actually run into this being an issue. I rarely (basically never) use package-private (aka default) access, as it seems to me to be a bit of a "friend" hack. All data fields are private, all accessors / mutators / etc. are public, protected or private depending on their perceived audience. It is the KISS principle at work. Perhaps if I had the internal keyword I would think different[ly].

    Peace,

    Cameron Purdy
    Tangosol, Inc.
    Coherence: Clustered JCache for Grid Computing!
  47. EJB 3, the New JavaBeans?[ Go to top ]

    Gavin King is the founder of the Hibernate project... He is currently involved in the JDO expert group...
    Nitin, don't hang on to the past! JDO is history, EJB3 is the future, don't you know? ;-)

    (Gavin has explicitly left the JDO expert group and publically states that he is not interested in JDO anymore, so it's probably better to associate him with the EJB3 expert group these days.)

    Juergen
  48. Web monkeys[ Go to top ]

    Yes, this is indeed true, because the only place where javabeans are used now are in web applications.

    Come on folks, try to not lose of the world at large just because your little corner of it looks glamorous and is crowded with others doing the same stuff.

    I certainly hope that all the javabeans I use in my swing apps won't suddenly require annotations or some kind of container.
  49. But JavaBeans failed.[ Go to top ]

    How mean developers really use JavaBeans as components, as intended? Use the java.beans package? Use PropertyChangedEvents, Bound Properties, Constrained Properties, etc?

    The JavaBean component model failed. It did not take off in a big way. It is not commonly used.

    What took off (hugely!) was an idea that it's okay if pretty much every field has a public (public! eek!) get and a set method associated with it, as long as you call them all 'properties' instead of just fields. The result is a set of very, very bad OO practices that have permeated standard Java development, whereby tight encapsulation is a rarity in the Java world.

    sigh. I'll stop ranting now.

    Sean
  50. But JavaBeans failed.[ Go to top ]

    How mean developers really use JavaBeans as components, as intended? Use the java.beans package? Use PropertyChangedEvents, Bound Properties, Constrained Properties, etc?The JavaBean component model failed.
    This stuff was designed for single user applications (VBX,AtiveX,VCL,JavaBeans,CCM,EJB), component models failed on server.
  51. JavaBeans is used[ Go to top ]

    I do infact use the java.beans package. And i like it too :-) Even serverside. Are you absolutely sure you've read the java-doc for the javabeans package, I mean. Good stuff in there. Beans in contexts, who wouldnt like that.
  52. But JavaBeans failed.[ Go to top ]

    What took off (hugely!) was an idea that it's okay if pretty much every field has a public (public! eek!) get and a set method associated with it, as long as you call them all 'properties' instead of just fields. The result is a set of very, very bad OO practices that have permeated standard Java development, whereby tight encapsulation is a rarity in the Java world.
    Furthermore, on the server side these abominations are called data transfer objects and their use is considered to be a best practice. ;-)

    Now, what the comment above should make clear is that using this kind weak encapsulation is OK as long as the objects in question are just grouping data into semantically significant units. Those value objects should not have any business code, but will be manipulated by third party objects all the time.

    On the other hand we have functional objects that actually perform the manipulation. The fields of these classes should be tightly encapsulated, as modifying these fields tends to have side effects, as on the values of those fields the actual work done depends.

    I think the main problem is mixing data with business code, and then having third party objects modify the data and arbitrary times from arbitrary places in the code.

    Just my 2 cents,
    Lars
  53. But JavaBeans failed[ Go to top ]

    And here I am thinking that OO is all about putting logic into the same object as the data! :-)

    I still do not see how the interface of an object has anything to do with how it is stored internally (aside from the fact that the code implementing the interface has to know). So if an Person object has a date-of-birth, then it must have a getter/setter. That's it. And I can ask the object to calculate it age. How it does that, is of no concern to me, as the user of the object.

    If the developer decided to use the most logical approach and use an internal Calendar to store the data, matching 1-1 the set/get, very smart of him! Easy to calculate the age then!

    I believe (as Dr. Phil would say) the issue is not as much about OO impurities, but about the sensless coding efforts the setters/getters in Java result in. (Oh my)
  54. But JavaBeans failed[ Go to top ]

    I still do not see how the interface of an object has anything to do with how it is stored internally (aside from the fact that the code implementing the interface has to know). So if an Person object has a date-of-birth, then it must have a getter/setter. That's it. And I can ask the object to calculate it age.
    But that's not business logic, it's just a convenience method. And it has the implicit constraint that all calculations will be done according to the same calendar, e.g. the gregorian, which is okay with a Person in this toy-example. But if you have different ways to calculate the age, you must either subclass the Person (ugly, as this leads to something like PersonWhichCalculatesAgeByMayaCalendar), or pass an AgeCalculator to the getAge() method, or simply have a getDateOfBirth() method which the AgeCalculator can query.
    How it does that, is of no concern to me, as the user of the object.
    As shown above, it is of concern to you as you expect the age to be calculated in a certain way.
    I believe (as Dr. Phil would say) the issue is not as much about OO impurities, but about the sensless coding efforts the setters/getters in Java result in. (Oh my)
    I agree with you on this point. With functional objects, you should not be forced to have accessors for every field (especially not setters, as most things are likely to be set either using a constructor, and thus be final, or are created on demand). And senseless coding is never advisable. But if you have data and want to access or modify single aspects of it, accessors certainly are the way to go.

    Now about the effort, why not use Eclipse's "Generate Getters and Setters..." functionality?

    Cheers,
    Lars
  55. But JavaBeans failed[ Go to top ]

    But that's not business logic, it's just a convenience method.

    Simplicity often helps in understanding :-)
    But if you have different ways to calculate the age
    Ah, indeed, that means that the calculation depends on more that one object (e.g. the context in which the person's age is calculated). In that case the situation is indeed not that simple, interesting case. Since multiple inheritance is not possible (PersonInContext extends Person, Context in which the age calculation is implemented), one could end up with a utility class (having a reference to Person and Context) or a utility method (using parameters).
    How it does that, is of no concern to me, as the user of the object.
    As shown above, it is of concern to you as you expect the age to be calculated in a certain way.
    Unfortunately yes. What I often do is try to have the Context available to the object upon request. So the Person knows it has to calculate in a context and requests the active context within the age method.

    But out of interest and hopefully to learn some: in your approach, how would you solved this?
    Now about the effort, why not use Eclipse's "Generate Getters and Setters..." functionality?
    Thomas took the words out of my mouth: I like my code to be visually clear. And generating a setter and getter with javadoc is a LOT of code for such a simple thing. I use something similar as he does, a "property divider" in the comments.
    Furthermore I really don't like how the Eclipse generation logic groups my methods alphabetically: first vars, then the getters, then the setters. I group according to scope: everything involved with "date-of-birth" is grouped together. The alphabetic view I can see in the outline window.

    But style is very personal, you should see how I place my comma's! :-)

    Tom
  56. But JavaBeans failed[ Go to top ]

    But if you have different ways to calculate the age
    Ah, indeed, that means that the calculation depends on more that one object (e.g. the context in which the person's age is calculated). In that case the situation is indeed not that simple, interesting case. Since multiple inheritance is not possible (PersonInContext extends Person, Context in which the age calculation is implemented), one could end up with a utility class (having a reference to Person and Context) or a utility method (using parameters).
    How it does that, is of no concern to me, as the user of the object.
    As shown above, it is of concern to you as you expect the age to be calculated in a certain way.
    Unfortunately yes. What I often do is try to have the Context available to the object upon request. So the Person knows it has to calculate in a context and requests the active context within the age method. But out of interest and hopefully to learn some: in your approach, how would you solved this?
    As you mentioned, subclassing is out of question. The possibility to let the Person exist in a given context is IMHO not explicit enough -- you might have set the context at a very different point in the code (or even worse, multiple points in the code) so that you don't know which context is set (and to what effect it is configured) when invoking the getAge() method.

    This leaves the two other options:
      1) pass an AgeCalculator to the getAge() method
      2) or simply have a getDateOfBirth() method which the AgeCalculator can query.
    If you know that the date of birth will only be used to calculate the age of the Person, the first option is okay, even though it might limit extensibility (see below):
    public class Person {
        public int getAge(AgeCalculator calc) {
            return calc.calculateAge(this.dateOfBirth);
        }
    }

    But now suppose you need the date of birth as well to calculate a social security number, the number of workdays until the Person will reach retirement, etc. As this would introduce a new Method for each of these uses, and, even worse, a dependency on AgeCalculator, SSNCalculator, DaysToWorkCalculator, etc., I personally would try to avoid it. Rather, I would choose the second option: Have a Person#getDateOfBirth() method that can be called by any client who wants to calculate anything concerning the date of birth.

    But these are, as always, just my two cents.

    Cheers,
    Lars
  57. But JavaBeans failed.[ Go to top ]

    ... as long as you call them all 'properties' instead of just fields. The result is a set of very, very bad OO practices that have permeated standard Java development, whereby tight encapsulation is a rarity in the Java world.
    The bad OO practices are not caused by getter/setter or 'property' keyword. Unlike pure OO idealists, I do not believe you can hide everything. Something are property and must be exposed in public. The question is still: do people know how to design. Usually, they don't and they won't.

    For JavaBean, I think it is next to impossible to have people start using BeanEdior or BeanProperty classes. The old lesson is that if you don't have to go the hard way, you will pick the short-cut!

    The problem with the Java accessor naming pattern is that it is just not natural in English to convert everything to a set/get/is sentence! A 'property' keyword would relief the problem.
  58. To get or not to set....[ Go to top ]

    I find it pretty amusing that the load of chaps here complains about having to define the get and set methods being the problem and Java annotations-to-the-rescue stuff. Gentlemen, have you ever heard about a decent IDE? Like IDEA? Or JBuilder? Or Emacs? Or Vi?
  59. To get or not to set....[ Go to top ]

    Still clutters up the code with unnessecary statements, they just get generated for you (which might make it even worse!). And don't start about folding please ;-)
  60. To get or not to set....[ Go to top ]

    Karl, it is not about typing, my Intellij-IDEA produces getters/setters in a blink of an eye, but ability to produce crap faster does not change the fact we still produce same crap.
    I think that c/c++ struct was unnecessary dropped from Java and should be introduced again (Java 6 perhaps?). I suspect that it is not possible to replace getter/setter convention by properties, however introduction struct in Java and maybe just allowing reflection to treat public fields as if they had geteer/setters will be good enough.
  61. EJB 3, the New JavaBeans?[ Go to top ]

    Gavin writes
    Remember, in EJB3, a session bean is just a JavaBean with maybe two or three annotations.
    I agree that EntityBeans could well be JavaBeans, but I don't see any reason why I should have to make my SessionBean a JavaBean as it contains only data for internal use. If I store some internals -- most often with SessionBeans this will be a reference to a Policy/Strategy some parts of the implementation of the business interface are delegated to -- I certainly have no inclination whatever to expose these. So why should I?

    Just asking,
    Lars
  62. more compact Information beans[ Go to top ]

    Hi people,

    I'd agree that the getter/ setter conventions, while nice when you need to add behaviours or refactor to an interface api, can be bulky.

    Though the code can be verbose if written with newlines, it's really the JavaDoc which will blow a simple property out to a whole screen of real estate.

    I'm a very big believer in 'Visible Oversight'; as with reading English, a lot of your cues come from being able to scan shapes and overall structure of an algorithm; rather than laboriously decoding it.

    One approach I use to assist readability, is to focus on 'Information' and behaviours; rather than the ground-level approach of Java spacing and JavaDoc conventions. This increases the density of the 'property' methods and sections them up, according to origin & lifecycle of the information.


    eg. for an Order class with more advanced taxation handling...

      // Customer
      public void setCustomer (Customer customer) {this.customer = customer;}
      public Customer getCustomer() {return customer;}
      // - derived details
      public String getCustomerName() {return customer.getName();}

      // Lines
      public void setLines (List lines) {this.lines = lines;}
      public List getLines() {return lines;}

      // Tax
      // - set from deriveTaxDetails() at order entry or analysis
      // - may not be set for other usages
      public TaxInfo getTaxInfo() {return taxInfo;}
      public BigDecimal getTaxableAmount() {return taxTaxable;}
      public BigDecimal getTaxTotal() {return taxTotal;}

      ...


    The point here, is that people can see the structure and behaviour of the data at a logical level - as Information rather than Data - helping giving a better oversight and understanding. This is also useful when you're looking through the class - behavioural methods stand out as distinct chunks of code.

    Anyway, I've got Eclipse setup with some compact templates; and can churn out a property or two very quickly. I tend to interleave this with work on other code requiring said properties - so I don't favour separate 'wizard' dialogs.

    Hope this helps.


    Cheers,
    Thomas

    www.powermapjdo.com
  63. EJB 3, the New JavaBeans?[ Go to top ]

    ..and sees the EJB 3 component model as an enhancement to JavaBeans: JavaBeans with "extra" semantics, defined by the spec's general-purpose annotations.
    This ia a major over-statement. First off, other than Entity beans the other EJBs are not anything close to Java Beans! And secondly, while annotations do simplify the location of the metadata and help with the documentation of the code, dont believe not having this (when metadata was in XMLs) was such a major impediment.

    It is not that the developers find dealing with an XML along with many java files too painful- especially when this XML is mostly modified *only* during the relatively infrequent task of creating new components or new biz methods! While CMP adoption was certainly hampered by the compexities, the other EJB types were well used. And not exactly unweildy to work with. This is well indicated by the good traction that the EJB2 MDBs and Session Beans have today!

    CMP Entity Beans may gain better adoption thru EJB3. But otherwise, EJB3 is not exactly going to create waves in the market! Atleast, not any more than already created :-) (More...)

    Cheers,
    Ramesh
  64. I am new to EJB Can anybody tell me how to Create Simple EJB Application using Eclipse and JBoss Server