Using the first form you'd have:
a.firstName
a.lastName
a.getName()
You've complicated matters by now having two styles for accessing
properties, it also has the issue that someone could still access `name`
instead of `getName()`
The historic solution in Java is to make all fields private and add
boilerplate:
a.getFirstName()
a.getLastName()
a.getName()
The better solution is to make the object immutable, using final values:
public class Haha{
public final String firstName;
public final String lastName;
public final String name;
public Haha(final String firstName, final String lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.name = firstName + " " + lastName;
}
}
It's okay to pre-calculate name here, because firstName and lastName can
never change (that's what immutable means...)
and If I want to change a value, I have to copy the object:
Haha haha = new Haha(oldHaha.firstName, newLastName)
Or I could implement a `withFirstName()` method inside Haha that handles
this logic for you - returning a new instance.
This is the same approach that Scala takes, but with Scala all the
construction and copy logic is built in:
case class Haha(firstName : String, lastName : String) {
val name = firstName + " " + lastName
}
On 18 September 2010 09:43, Steel City Phantom <[email protected]> wrote:
> >The client has a requirement that we must be able to sort haha instances
> based on their surnames.
>
> >Now update that definition so that `a.name` is a concatenation of
> `a.firstName` and `a.lastName`, I want >to be able to continue using it as `
> a.name` though.
>
> ok, you got that one. but whats the difference between
>
> public class haha{
> public String firstname;
> public String lastname;
> public String name;
>
> public String getName(){
> name = firstname + lastname;
> return name
> }
>
> and
>
> public class haha{
> public property firstname;
> public property lastname;
> public property name = firstname + lastname;
> }
>
> maybe im just naive but i don't see any real difference between the two.
> sure number of lines decreases but beyond that, whats the difference?
>
> --
> You received this message because you are subscribed to the Google Groups
> "The Java Posse" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected]<javaposse%[email protected]>
> .
> For more options, visit this group at
> http://groups.google.com/group/javaposse?hl=en.
>
--
Kevin Wright
mail / gtalk / msn : [email protected]
pulse / skype: kev.lee.wright
twitter: @thecoda
--
You received this message because you are subscribed to the Google Groups "The
Java Posse" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/javaposse?hl=en.