Does Java offer an efficient way of accessing custom class modifiers and methods?
Here is some pseudocode, demonstrating what I'm trying to do:
So what you're telling me is that the only way I can access methods etc. is through typing the full path to said 'whatever'?
There is no shorthand way of doing this?
And thankfully because it created ambiguous and unreadable code. Here's a short blurb on it. Shorter is not always better.
Change all of the setter methods to return this after doing the set action, like this:
Then you can string all of the setters together like this:
Paul Clapham wrote:Then you can string all of the setters together like this:
I like this ... I'll play with the code, but just for clarity in this thread and for future seekers, would this example work as you described?
(ignoring import statements of course)
Bear Bibeault wrote:Be aware that by doing so, the bean pattern is violated and the class may not work in environments (such as JSP) where the bean pattern is mandated.
Michael D Sims wrote:
That code is horrific. First of all, it flouts convention and it's likely to confuse people when they read it. Second, the least you could do to make it readable is to have each chained method call on a separate line, like this:
Third, FirstName and LastName are not classes and just plain reference variables so they should start with lowercase letters, not uppercase.
If you really wanted a "convenient" way to write that without breaking with the JavaBean setter method convention, you can use a variation of the Builder pattern, like so:
You can then write this:
You have to statically import the Person.with() method if you want to be able to write it like that, otherwise, you'd have to write: Person.with(person) instead.
In my opinion, unless you have to write this kind of code in many different places and with a wide variety of sources for field values, it's just way too much effort. It does make the client code less verbose even though your Person.java source file would practically double in size.