How to emluate "properties" in Java?

M

Michael Tsang

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

A property is defined as a member that is read and written like a field, but
the read and the write actually calls the getter and setter.

http://en.wikipedia.org/wiki/Property_(programming)

Some languages have native support for property, e.g. C#, Python, PHP.
Although C++ doesn't, I always emulate them by defining helper classes that
overload the copy constructor and the conversion operator. In Java, there is
no operator overloading, how do I emulate them? If I can't do this, I will
have trouble doing OO in Java.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkuGbykACgkQm4klUUKw07CfGgCfbxx86pgfdqbZZX6KemAOOoSW
HCcAniLS80puL8spZxB+mtMaCVzDrIYA
=yRUE
-----END PGP SIGNATURE-----
 
J

Joshua Cranmer

Some languages have native support for property, e.g. C#, Python, PHP.
Although C++ doesn't, I always emulate them by defining helper classes that
overload the copy constructor and the conversion operator. In Java, there is
no operator overloading, how do I emulate them? If I can't do this, I will
have trouble doing OO in Java.

The standard way of implementing properties in Java is with get and set:

public class Foobar {
private String name;

public String getName() { return name; }
public void setName(String newName) { name = newName; }
}

Yes, it requires typing about 4 more characters, but otherwise, it would
be pretty much the same.
 
J

Jean-Baptiste Nizet

Michael Tsang a écrit :
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

A property is defined as a member that is read and written like a field, but
the read and the write actually calls the getter and setter.

http://en.wikipedia.org/wiki/Property_(programming)

Some languages have native support for property, e.g. C#, Python, PHP.
Although C++ doesn't, I always emulate them by defining helper classes that
overload the copy constructor and the conversion operator. In Java, there is
no operator overloading, how do I emulate them? If I can't do this, I will
have trouble doing OO in Java.

Properties are, as you wrote yourself, just syntax sugar in order to
call getters and setters without having to type the get- or the set-
prefix and the parentheses. In Java, there aren't properties. You call
the getters and setters explicitely. I don't see how your code would be
less OO by doing so. I see, however, how your Java code will be easier
to understand, maintain, debug and refactor (no hidden side-effects).

JB.
 
T

Tom Anderson

A property is defined as a member that is read and written like a field, but
the read and the write actually calls the getter and setter.

http://en.wikipedia.org/wiki/Property_(programming)

Some languages have native support for property, e.g. C#, Python, PHP.
Although C++ doesn't, I always emulate them by defining helper classes
that overload the copy constructor and the conversion operator. In Java,
there is no operator overloading, how do I emulate them? If I can't do
this, I will have trouble doing OO in Java.

If you think getters and setters are required for OO, then you will have
trouble doing OO in any language.

tom
 
L

Lew

Don't believe everything you read on the Internet. Certainly you cannot take
such a definition as comprehensive.

Strangely, this link you provide also gives the answer to your question. This
Wikipedia entry, with its narrow and incomplete definition of "property",
tells you how to implement properties in Java.

Properties are a concept of which C# "properties" are an implementation.
Don't confuse the Platonic ideal with the shadows on the cave wall.
 
R

Robert Klemme

Don't confuse the Platonic ideal with the shadows on the cave wall.

LOL Thanks for making my day! Now if I could only get out of this dark
spot... :)

Cheers

robert
 
R

Roedy Green

Some languages have native support for property, e.g. C#, Python, PHP.
Although C++ doesn't, I always emulate them by defining helper classes that
overload the copy constructor and the conversion operator. In Java, there is
no operator overloading, how do I emulate them? If I can't do this, I will
have trouble doing OO in Java.

Gosling is a bottom up the JVM-is-Java man. His philosophy is "if
there is a way to express the solution in Java, the job is done." In
his view, Delphi-like properties would do nothing to the JVM,
therefore they would be frivolous syntactic sugar.

I strenuously disagree. A verbose program is a buggy program hard to
proofread and wasteful of time to compose. Getters and setters are
infantile syntax.

What to do about it?

1. see http://mindprod.com/project/scid.html

2. use IntelliJ which at least will generate reams of getter/setter
crud for you. http://mindprod.com/jgloss/intellij.html

3. Use JAXB which will also generate getter/setters from XSDs.
http://mindprod.com/jgloss/jaxb.html

4. use C#

5. see http://mindprod.com/jgloss/bali.html
--
Roedy Green Canadian Mind Products
http://mindprod.com

The major difference between a thing that might go wrong and a thing that cannot possibly go wrong is that when a thing that cannot possibly go wrong goes wrong it usually turns out to be impossible to get at or repair.
~ Douglas Adams (born: 1952-03-11 died: 2001-05-11 at age: 49)
 
A

Arne Vajhøj

A property is defined as a member that is read and written like a field, but
the read and the write actually calls the getter and setter.

http://en.wikipedia.org/wiki/Property_(programming)

Some languages have native support for property, e.g. C#, Python, PHP.
Although C++ doesn't, I always emulate them by defining helper classes that
overload the copy constructor and the conversion operator. In Java, there is
no operator overloading, how do I emulate them? If I can't do this, I will
have trouble doing OO in Java.

You use explicit get and set methods and calls.

There is a convention for that. And you should follow
the convention, because various tools will expect that
convention to be followed.

Arne
 
J

Joshua Cranmer

I strenuously disagree. A verbose program is a buggy program hard to
proofread and wasteful of time to compose. Getters and setters are
infantile syntax.

There is some virtue in verbosity: it means you can identify patterns
more easily.

Right now, in Java, "a.b = 5" is always going to set a field in the
object A to 5. If you had properties, the same syntax could also mean to
call a function with an argument of 5, which may or may not set a field
to 5. It could also just decide to sneer in your face for the heck of it.

Let's compare:
a.b = 5;
a.setB(5);

You've saved a grand total of 2 characters at the cost of hiding a
method call, which impairs the ability of a reader to quickly glance
over code and see what is happening. You've also made syntax ambiguous,
since whether or not `b' is a field access or a method call depends on
the type of `a' and the identifier `b' represents. [1]

There is another example of where verbosity is useful. In the English
language, the information entropy is roughly ~1-1.5 bits/letter, so we
actually only theoretically need about 3 letters to keep text on average
the same size. Why don't we? Bcs it enbles us to rd txt whn som letrs r
mssng or malfermed.

[1] I do realize that a.b is already ambiguous syntax, thanks to Java
overloading the meaning of the `.' to be both a scope resolution
operator (e.g., java.io.Serializable) and a member access operator. In
this case, I would classify nested classes as falling under `scope
resolution' (so if we had used '::' for scope resolution, Map.Entry
would be `Map::Entry'). The decision to overload `.' is not one I'm
particularly thrilled with.
 
M

markspace

Peter said:
That said, if all this were was about syntactic sugar and naming
conventions, I'd agree. Properties wouldn't add much, if anything, over
simply having a naming convention in Java.


This much I agree with. Even if Java were to add some sort of first
class property support, I'd still like to see them keep the set/get
naming convention. It's familiar to Java programmers, at least, and as
mentioned it doesn't really save anything. I find it very readable.

Note, however that that's not really the case. Using .NET as the
example again, properties are full-fledged class members uniquely
different from other kinds of members. This enables, for example, a
more robust data binding model, where you can specify the name of the
property and be assured that you are really getting a property, rather


I'm not familiar with .net forms or WPF. Could you give an example
where this matters?

What if a "property" doesn't correspond to an actual field? How would
you incorporate that into this robust data binding?
 
A

Arne Vajhøj

How does the second line of code in any way tell you what the method is
doing? If anything, a property carries with it a strongly implication
that the _object_ itself will be modified. A method named "setB()" could
do anything.

They have the same abilities and they causes the same expectations.
Granted, in Java we have the convention that a method named "setX" is
going to set some property-like state in the object. But then you're
just back to the whole property thing.

Yes.

We are back to the problem that a property is adding a new
syntax feature, but is still relying on a convention just like
getters and setters.

more syntax + same problems = bad solution
That said, if all this were was about syntactic sugar and naming
conventions, I'd agree. Properties wouldn't add much, if anything, over
simply having a naming convention in Java.

Note, however that that's not really the case. Using .NET as the example
again, properties are full-fledged class members uniquely different from
other kinds of members. This enables, for example, a more robust data
binding model, where you can specify the name of the property and be
assured that you are really getting a property, rather than just a
method that happens to look like the method that would exist had that
property actually been present.
>
Going the other direction, it enables in GUI designers (don't even get
me started at the vast gulf between designers for .NET Forms and WPF
applications, as compared to those available in Java) the ability to
confidently display property values to be initialized as part of a
designed object, again without worrying about whether something is
displayed because it just happened to look like a property when it
wasn't, or failing to display something because it's still basically a
property but for some reason someone failed to follow the correct naming
convention.

Have you ever heard of a problem being caused by that?

Arne
 
S

Stefan Ram

Tom Anderson said:
If you think getters and setters are required for OO, then you will have
trouble doing OO in any language.

Thank you, I enjoyed reading the quoted sentence!

Getters and setters are indeed required for /Java/
programming, because sometimes one is forced to use them by
certain APIs, like the Beans-API.

This shows that Java programming is only partially related
to object-oriented programming. Actually, in reality, there
is no »object-oriented programming« at all, only programming
in Java, C++, Smalltalk, Lisp and so on. »Object-oriented
programming« is an abstraction, concrete programming is done
in a specific language with specific libraries and a
specific culture.
 
W

Wojtek

Peter Duniho wrote :
How does the second line of code in any way tell you what the method is
doing? If anything, a property carries with it a strongly implication that
the _object_ itself will be modified. A method named "setB()" could do
anything.

And if Java had properties, an implied function (um, method) would be
called which: "could also just decide to sneer in your face for the
heck of it."

The difference is that a.b=5 WILL set b to 5, whereas having properties
it may or may not. Exactly as a setB() could do.

I do not like implied actions (and I really do not like operator
over-loading).

By contract setB() will eventually set b to 5, though it may do some
other processing along the way. And that is just fine, as the class has
the right (and responsibility) to make sure that the 5 is a valid
value. It may also decide to add 5 to some other internal field which
is hidden from view.

Consider: a.setName("Wojtek");

A.setName(String theName)
{
this.theName = theName;
}

The class is distributed, then users complain that the values sort
funny. Investigation shows that a sort value is never set by some end
programmers (silly people).

So now you can send out a strongly worded letter to all the programmers
using your class, OR:

A.setName(String theName)
{
if(getSort().length()==0)
setSort(theName);

this.theName = theName;
}

The class ensures that if a name is set, and a sort value has not
already been set, that there will be a sort value. You send out an
update and the issue is fixed.

Using a.theName="Wojtek" would completely prevent you from issuing a
fix and you would need to rely on the goodness of the end programmer to
use your class "properly".

And if the sort is case insensitive:

A.setSort(String sortValue)
{
this.sortValue = sortValue.toLower(sortValue);
}

No. I greatly prefer using get/set for ALL changes to class properties.
 
M

markspace

Peter said:
markspace said:
[...]
Note, however that that's not really the case. Using .NET as the
example again, properties are full-fledged class members uniquely
different from other kinds of members. This enables, for example, a
more robust data binding model, where you can specify the name of the
property and be assured that you are really getting a property, rather

I'm not familiar with .net forms or WPF. Could you give an example
where this matters?

I'm not entirely sure I understand the question. But, for example,
consider method names like "setTable()" or "setBrake()", where "table"
actually refers to an actual tabletop (or a data structure modeling
one), or "brake" refers to the brake of some vehicle.


What I mean is, given the methods setTable() or setBrake(), what
constitutes "more robust data binding" (your words from above) and how
does this make a difference in programming?

So far you've only really given examples were C# is the exactly same as
Java, except for one point of syntactic sugar. The ability to type =
instead of "set" doesn't strike me as any sort of useful data binding at
all, let alone "more robust." Is there more that I'm missing?

Just as in Java, a property in a language like C# has no need to
correspond to an actual field.


So if I declare some class in C#

class C# {
setN( int n ) {
... do anything I want ...
}
}

Then I invoke that method on an instance like this

instance.N = 42;

that's no different from calling the method name? And that's all that
this "data binding" provides me? If so then I truly don't see the
usefulness. It's not worth the extra effort on the part of the compiler
to bother in my opinion, and I can see why folks wouldn't want this
ported over to Java.

But, that's the main point of a high-level programming language: to
abstract concepts to make them more accessible and usable.


See, I don't see this as "abstraction." What I've described is
literally just syntactic sugar, the mere substitution of one phrase for
another. And it doesn't save a lot of characters, either, so I can't
really say that I'd consider this feature useful.

I was hoping to discover some interesting facts of C# and language
design, but so far I'm disappointed.

Just to lead the discussion a bit, what does a C# class with these sorts
of methods look like under reflection? Do properties appear differently
than just method names?
 
L

Lew

Peter said:
Honestly, it seems to me that you ought to learn the language and
actually understand the feature before you dismiss it out of hand.

How do you consider what he's doing dismissing it out of hand? He's asked you
what he doesn't understand so that he can grok the value. If he dismissed it
out of hand, he'd've not asked what he's missing.

Telling him he has to learn the whole language instead of answering the
focused question is rather weasely. Maybe he is trying to learn the language,
or at least understand it well enough to interact with C# folks as we
benighted Java dweebs occasionally must do. It's fine if you don't want to
answer his question, but there's no reason to be condescending about it.
 
M

Michael Tsang

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

It is the programmer's responsibility to use things correctly. A good
programming language should allow programmers to write anything they want.
For example, in C#, you can declare a property called "name" but instead set
the age. In Java, you can also declare a method called setName but set the
age. The lack of properties, along with some features (like operator
overloading, references (as the meaning in C++), make the life of a library
programmer difficult. Consider a math library, how do the library provide
the "add" operation in Java? There is no standard way to do so. In C++, the
standard way is to overload the "+" operator. It is the library's
responsibility to correctly overload the "+" operator.

The differentiation between primitives and classes is also a big mistake in
the design of Java, making writing generics that act on primitives and
classes the same impossible. In C++, you can write a class that behaves
nearly the same as a primitive, the user need not care whether the algorithm
acts on a class or on a primitive, and happily write a template for it.

In some situation, it is impossible to avoid properties/getter or setter
completely. A good example is a GUI library.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkuIkjIACgkQm4klUUKw07C5sQCfYcLEkcNs0IakjQq4iqJLzJwY
AUcAoIMBZKVB19pDCkJk68AGTANtcgc9
=/zlQ
-----END PGP SIGNATURE-----
 
M

markspace

Peter said:
I have not been condescending at all. However, it is true that I'm
frustrated by the attitude that one can make judgments about a language
before they have actually learned the _facts_ about that language.


You've been a little condescending, imo. And I've poked at you and your
opinions too, so we'll call it even. Really I'm just trying to get some
information, but you seemed to stop giving out any information after
your first post on the subject.

There might be something important with properties, but what I've read
so far just makes me go "meh." And yes, saying "learn the language
yourself instead of asking me" was a little rude. You've obviously used
C# far more than most of us here, and I thought I was asking an expert.
If your going to just be defensive, that diminishes the value of your
expertise, doesn't it?

The best thing I've seen so far was the abbreviated syntax for declaring
getters and setters. In Java I guess it might look something like this:

class PropertiesExample {
@ReadWrite @Synchronized
int N;
@ReadOnly
final String Value = "hmm";
}

LOC is directly proportional to development costs and maintenance. This
syntax does appear to reduce LOC and therefore it might be worth looking
at. But I'm still confused what "robust data binding" does here.
 
S

Stefan Ram

Michael Tsang said:
In some situation, it is impossible to avoid properties/getter or setter
completely. A good example is a GUI library.

It is always possible to avoid getters and setters when
designing a library. To avoid properties is really nearly
impossible, because a property is just a part of the state
of an object, so it conceptually exists for all but the most
trivial objects - even without methods to set or get it.

A getter returns the value of a field by its contract, it is
not a method named »get...«. So to avoid getters, you do not
have to change the code, but the contract/documentation.

A getter:

/** Returns the value of the private field a.
@return the value of the private field a. */
public int f(){ return a; }

Not a getter:

/** Returns the value of the property a.
@return the value of the property a. */
public int f(){ return a; }

The code for the getter and not-a-getter is the same.
Just the documentation (contract) differs.
 
A

Arved Sandstrom

Peter said:
markspace wrote:
[ SNIP ]
Ironically, that's the least useful aspect of properties in C#. It's
helpful in defining simple classes, especially immutable data
containers. But most non-trivial classes will have additional logic,
especially in the setter. And of course, the abbreviated syntax is not
useful if one needs to provide any specific implementation.

Pete

That abbreviated syntax, which for you is the least useful aspect of
properties in C#, may well be the most useful aspect of properties for
most C# programmers. I doubt very much that the majority of C# writers
are doing anything but jamming in those { get; set; } pairs for each
field they want to expose.

Even MS in its API doesn't claim more for properties than:

"Properties are members that provide a flexible mechanism to read,
write, or compute the values of private fields. Properties can be used
as if they are public data members, but they are actually special
methods called accessors. This enables data to be accessed easily and
still helps promote the safety and flexibility of methods."

There really isn't anything deeper going on here.

My opinion is that C# properties would have more of the usefulness that
you impart to them, apart from the easier syntax (which as I've stated
is what I think most C# programmers get out of properties), if the
properties did *not* access other member fields. To me the following
snippet (I borrowed it because a lot of people use it) shows off
properties (and of this specific form I've seen very few examples):

class Accounting
{
public double Price { get; set; }
public int Quantity { get; set; }

public double Total
{
get { return Price * Quantity; }
}
}

and this (which I've seen many examples of) does not:

class Accounting
{
private double price;
private int quantity;

public double Price
{
get { return price; }
set { price = value; }
}

public int Quantity
{
get { return quantity; }
set { quantity = value; }
}

public double Total
{
get { return price * quantity; }
}
}

The second example to me is no different than Java accessors: entirely
up to the programmer what they access with these methods. Using the
classic form, with backing fields, has no real extra value at all. IMO.

I'm also of two minds about the property Total in this example. I
suppose if one were making a declaration about object state, and held
that the derived read-only value Total is as much a primary component of
Accounting object state as Price or Quantity, I could live with it.
Myself though I'd keep Total a method, and drop the property syntax.

AHS
 
D

David Lamb

Arved said:
... I doubt very much that the majority of C# writers
are doing anything but jamming in those { get; set; } pairs for each
field they want to expose.

Even MS in its API doesn't claim more for properties than:

"Properties are members that provide a flexible mechanism to read,
write, or compute the values of private fields. Properties can be used
as if they are public data members, but they are actually special
methods called accessors. This enables data to be accessed easily and
still helps promote the safety and flexibility of methods."

There really isn't anything deeper going on here.

This is one of several points where I might have jumped in, so it's
really a reply to lots more people than just Arved, and I'm not really
disagreeing with anybody...

I have no opinion yet about whether "properties" are important in
current languages. However, back in the Bad Old Days, when we had to
pack a 7-bit integer, a binary flag, and two 3-bit integers into a
16-bit word (with 2 bits left over for future expansion), the ability to
write a.b = c and have inline get/set methods called would have been a
big deal. At least back then, we had the attitude that assignment/fetch
of "fields" was enough easier for humans to understand than a.setB(c)
that it was worth having.

It might be worthwhile having some sort of annotation for a get/set pair
that says "this is really meant to be a pseud-field, so a code
walkthrough should verify it really behaves that way instead of doing
the arbitrary munging around any old method could have done."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top