473,466 Members | 1,336 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

On Java and C++

Java programmers seem to always be whining about how confusing and
overly complex C++ appears to them. I would like to introduce an
explanation for this. Is it possible that Java programmers simply
aren't smart enough to understand C++?

This is not merely a whimsical hypothesis. Given my experience with
Java programmers --- the code they write and the conversations they
have --- Occam's Razor points to this explanation. For example,

"Oooh I'm confused about the difference between pointers, references,
and objects! How confusing!"

"Oooh operator overloading confuses me! The expression x + y is so
confusing, who knows what's happening with that? If x and y are
complex numbers, what the hell could x + y mean?"

"Oooh multiple inheritance is so confusing! Though I am both a father
and a programmer, I still find it so confusing how the same object can
be two different things! How confusing!"

"Oooh and virtual bases are so bizarre! I am a student --- myself
'the father' is the same student as myself 'the programmer' --- but
nonetheless the idea of virtual bases is absolutely confounding and
confusing to me!"

Again, Occam's Razor is a valuable tool here. In deciding among
competing hypotheses, choose the simplest one. To impartial observers
of indoctrinated Java programmers, the explanation is simple indeed.

Apr 26 '06
458 20749
Chris Smith wrote:
I find this to be not at all true. In fact, most of what I do for a
living these days is write code (and manage a development team that
writes code) in Java on Windows, and deploy the code on Linux.


Me too. I could have kicked off the list with a less cheap shot. For
example:

"Java : the elegant simplicity of C++ and the blazing speed of Smalltalk."
--Jan Steinman
- adds keywords, like interface, based on
someone else's preconceived notion of good
design. Not keywords like 'virtual', based
on what the hardware will actually do


So you don't like the lack of multiple inheritance. That's fine.
However, the existence of interfaces as a language feature is perfectly
sensible in a language without multiple inheritance. This is not a
separate gripe.


Ooh, I was gonna snip it all, but you finally got thru to me.

I didn't mention MI!!!

When I was a tiny kid, my mom read me a children's book about a rabbit
scolding another rabbit (or something like that) for sneaking into a
garden. The one rabbit complains, "but I didn't sneak in!" "Because you
stopped in time!!" "But I wasn't _gonna_ sneak in!!" etc.

I apologise for just being about to mention MI and stopping in time.
(Noah!;)

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
May 3 '06 #351

Phlip wrote:
I apologise for just being about to mention MI and stopping in time.
(Noah!;)


?

May 3 '06 #352
Noah Roberts wrote:
Mishagam wrote:
Noah Roberts wrote:
Mishagam wrote:

C++ references are not SO different from pointers. Just like Roedy Green
said - one more addressing mode. I doubt any well designed language
(like Java) would have (or has) references.
Java has references.

Excuse me. I meant separate references and pointers with so close
functions. Java has references, but they have also some features of C++
pointers like they can be null.


C++ pointers and references have completely different purposes. The
fact that Java lacks pointers is just another can't.

I can't say Java's, "everything is a reference except when it is not,"
is a move up from having explicit value, reference, and pointer
semantics that operate in a uniform manner.


Java has a thing called 'references'. Its more like a C Pointer than a
C++ reference, as in it can be nulled. The major difference is that no
pointer arithmetic can be done with it.

Java references are passed by value. The objects that they point to does
actually move.

Granted a better name than 'reference' or 'pointer' would have helped -
though I cant think of one.
May 3 '06 #353
Noah Roberts wrote:
Mishagam wrote:
Noah Roberts wrote:
Mishagam wrote:

C++ references are not SO different from pointers. Just like Roedy Green
said - one more addressing mode. I doubt any well designed language
(like Java) would have (or has) references.
.... C++ pointers and references have completely different purposes.


'purpose' is what language designers imagined references would be used
for. Functionaly, as I understand, difference between references and
pointers is little syntax sugar [ -> replaced with . ] + what values
they can hold - references cannot hold null or objects allocated by new.
But you CAN have reference to destructed object out of scope (or field
in deleted object allocated on heap). Also references syntax resembles
value objects enough that is is difficult to distinguish what you are
using now. It is one more way where C++ loses C clarity.
What I meant is difference with pointer is too small to justify
existence of references for well designed language. I think that
designers of C++ just hated C pointers too much to think rationally.

By the way, I have little problem. I Wiki about C++ reference types I read:
"Once a reference is created, it cannot be later made to reference
another object; we say it cannot be reseated. This is often done with
pointers."
But in my VS 2003 C++ compiler you can easily put new value to
reference, like code sample below. Do you know who is correct here?

int main() {
int aa = 25;
int & ra = aa;
int bb = 323;
ra = bb;
printf("ra= %d\n", ra);
int *ii = new int;
*ii = 999;
ra = *ii;
printf("ra= %d\n", ra);
ii = NULL;
ra = *ii;
......
THis code compiled and run OK on VS 2003
May 3 '06 #354

Mishagam wrote:
Noah Roberts wrote:
Mishagam wrote:
Noah Roberts wrote:
Mishagam wrote:

> C++ references are not SO different from pointers. Just like Roedy Green
> said - one more addressing mode. I doubt any well designed language
> (like Java) would have (or has) references.
...
C++ pointers and references have completely different purposes.


'purpose' is what language designers imagined references would be used
for. Functionaly, as I understand, difference between references and
pointers is little syntax sugar [ -> replaced with . ] + what values
they can hold - references cannot hold null or objects allocated by new.
But you CAN have reference to destructed object out of scope (or field
in deleted object allocated on heap). Also references syntax resembles
value objects enough that is is difficult to distinguish what you are
using now. It is one more way where C++ loses C clarity.
What I meant is difference with pointer is too small to justify
existence of references for well designed language. I think that
designers of C++ just hated C pointers too much to think rationally.


You say that references are little more than syntatic sugar and then
directly quote at least one way in which they are drastically different
below. I guess logic isn't something you are good at.
By the way, I have little problem. I Wiki about C++ reference types I read:
"Once a reference is created, it cannot be later made to reference
another object; we say it cannot be reseated. This is often done with
pointers."
But in my VS 2003 C++ compiler you can easily put new value to
reference, like code sample below. Do you know who is correct here?

int main() {
int aa = 25;
int & ra = aa;
int bb = 323;
ra = bb;
printf("ra= %d\n", ra);
int *ii = new int;
*ii = 999;
ra = *ii;
printf("ra= %d\n", ra);
ii = NULL;
ra = *ii;
.....
THis code compiled and run OK on VS 2003


You obviously don't understand what a reference is. Print out aa and
you will have your answer. Print out bb after your second change and
it may become more clear.

May 3 '06 #355
[followups set to non-Java groups]

Mishagam wrote:
C++ pointers and references have completely different purposes.
'purpose' is what language designers imagined references would be used
for. Functionaly, as I understand, difference between references and
pointers is little syntax sugar [ -> replaced with . ]


Nope. A reference is an alias for an object. Unlike a pointer, you cannot
take the address of the refering thing (the thing that's probably secretly
a pointer). It's secret because the compiler can optimize it away, and go
to the real object if possible.
+ what values
they can hold - references cannot hold null or objects allocated by new.
They can hold heap objects; they just shouldn't.

int & i = *new int;
delete &i;

That's valid but high risk.
But you CAN have reference to destructed object out of scope (or field
in deleted object allocated on heap).
Yep. Even thinking about i after my delete line is illegal.
Also references syntax resembles
value objects enough that is is difficult to distinguish what you are
using now. It is one more way where C++ loses C clarity.
There's a difference between clarity and exposed plumbing...
What I meant is difference with pointer is too small to justify
existence of references for well designed language. I think that
designers of C++ just hated C pointers too much to think rationally.
If they burdened C++ with your misunderstandings of references, then your
point might be valid. References are good because they are the _weakest_
kind of alias or handle we have. Use them in preference to pointers.
By the way, I have little problem. I Wiki about C++ reference types I
read: "Once a reference is created, it cannot be later made to reference
another object; we say it cannot be reseated. This is often done with
pointers."
But in my VS 2003 C++ compiler you can easily put new value to
reference, like code sample below. Do you know who is correct here?

int main() {
int aa = 25;
int & ra = aa;
int bb = 323;
ra = bb;
That copys the value of bb into aa, which ra still refers to.
printf("ra= %d\n", ra);
int *ii = new int;
*ii = 999;
ra = *ii;
Right. Now that copies the 999 to the aa, which ra still refers to.
printf("ra= %d\n", ra);
ii = NULL;
I hope you didn't think that 'delete's ii. It just leaks the memory.
ra = *ii;


And that's undefined behavior.

So the well-defined parts of your sample program do indeed demonstrate how
references are aliases for their target objects. You may want to debug your
program, or even look at its opcodes, to see what's going on. The compiler
might optimize ra away, and the statement ra = bb might produce the same
opcodes as aa = bb.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
May 3 '06 #356
"Andrew McDonagh" <ne**@andmc.com> wrote in message
news:e3**********@news.freedom2surf.net...

Java has a thing called 'references'. Its more like a C Pointer than a
C++ reference, as in it can be nulled. The major difference is that no
pointer arithmetic can be done with it.

Java references are passed by value. The objects that they point to does
actually move.


I'm assuming you mean "does NOT actually move".

- Oliver

May 3 '06 #357
"Chris Smith" <cd*****@twu.net> wrote in message
news:MP************************@news.astraweb.com. ..
- when a smart editor like Eclipse can finish
every line for you, it makes you wonder
what the language is _there_ for!


This is perhaps a useful thing for some to wonder, but only so that they
can get around to knowing the answer. The answer is that we're talking
about two different sets of things:

(1) What can be reasonably guessed, with the assurance that the
programmer will see the guess and correct it if it's wrong?

(2) What is so certain to be the programmers meaning that it can be done
without guessing?

Clearly, there are things that fit into set (1) without also fitting
into set (2). Those things should be implemented with IDE auto-complete
features, and not with the language itself. Whether the boundaries are
drawn correctly is another issue, and there are undoubtedly places where
the boundaries could be drawn better... but criticizing the need for
auto-complete entirely doesn't look reasonable.


Also, when some types in:

public class Foo i

the Eclipse Editor, and just about anyone else who is familiar with
Java, could probably safely assume that the programmer is about to type in
"mplements" to yield:

public class Foo implements

does that mean that the designers of Java should have used the string
"i" instead of "implements" as the keyword? It depends on whether one values
clarity or terseness.

- Oliver

May 3 '06 #358
"Mishagam" <no*****@provider.com> wrote in message
news:na******************@southeast.rr.com...
int main() {
int aa = 25;
int & ra = aa;
int bb = 323;
ra = bb;
printf("ra= %d\n", ra);
int *ii = new int;
*ii = 999;
ra = *ii;
printf("ra= %d\n", ra);
ii = NULL;
ra = *ii;
.....
THis code compiled and run OK on VS 2003


Wow. Noah your point is well taken. I have just been convinced that Java
is a superior programming language for not allowing this kind of BS.

--
LTP

:)
May 3 '06 #359
"Chris Uppal" <ch*********@metagnostic.REMOVE-THIS.org> wrote in message
news:44*********************@news.gradwell.net...
Oliver Wong wrote:
(referring to http://www.tiobe.com/tiobe_index/images/tpci_trends.gif
as of May 2nd, 2006): I wonder what happened in 2004 that made Java drop
considerably, and everything else jump up a bit.


From the TIOBE faq:

Q: What happened to Java in April 2004? Did you change your methodology?
A: No, we did not change our methodology at that time. Google changed its
methodology. They performed a general sweep action to get rid of all kinds
of
web sites that had been pushed up. As a consequence, there was a huge drop
for
languages such as Java and C++. In order to minimize such fluctuations in
the
future, we added two more search engines (MSN and Yahoo) a few months
after
this incident.


It's a flawed method of rating to begin with. I do not believe we can
directly infer that web page occurrences some how indicate usage. It may
provide some kind of vague correlation - I suppose.

--
LTP

:)
May 3 '06 #360
Luc The Perverse wrote:
int aa = 25;
int & ra = aa;
int bb = 323;
ra = bb;
printf("ra= %d\n", ra);
int *ii = new int;
*ii = 999;
ra = *ii;
printf("ra= %d\n", ra);
ii = NULL;
ra = *ii;
Wow. Noah your point is well taken. I have just been convinced that
Java is a superior programming language for not allowing this kind of BS.


Noah's point - between the cheap shots - was that C++ does _not_ allow that
kind of BS.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
May 3 '06 #361

Luc The Perverse wrote:
"Mishagam" <no*****@provider.com> wrote in message
news:na******************@southeast.rr.com...
int main() {
int aa = 25;
int & ra = aa;
int bb = 323;
ra = bb;
printf("ra= %d\n", ra);
int *ii = new int;
*ii = 999;
ra = *ii;
printf("ra= %d\n", ra);
ii = NULL;
ra = *ii;
.....
THis code compiled and run OK on VS 2003
Wow. Noah your point is well taken.


Can't figure out who you're quoting??

I have just been convinced that Java is a superior programming language for not allowing this kind of BS.


Java doesn't allow this huh? Hmm...guess that will be news for some.
Can't exactly function as a language I guess...

May 3 '06 #362
Luc The Perverse schrieb:
It's a flawed method of rating to begin with. I do not believe we can
directly infer that web page occurrences some how indicate usage. It may
provide some kind of vague correlation - I suppose.


I think a simple chart of sourceforge projects by programming languages
would be much more meaningful. It wouldn't be representational because
it's far from complete, but at least you know what you are measuring.
Timo
May 3 '06 #363
In comp.lang.java.advocacy, Noah Roberts
<ro**********@gmail.com>
wrote
on 3 May 2006 09:51:31 -0700
<11**********************@e56g2000cwe.googlegroups .com>:

Mishagam wrote:
Noah Roberts wrote:
> Mishagam wrote:
>
>> C++ references are not SO different from pointers. Just like Roedy Green
>> said - one more addressing mode. I doubt any well designed language
>> (like Java) would have (or has) references.
>
> Java has references.
> Excuse me. I meant separate references and pointers with so close
functions. Java has references, but they have also some features of C++
pointers like they can be null.


C++ pointers and references have completely different purposes. The
fact that Java lacks pointers is just another can't.


Pointers are a means to an end (well, so is everything else in
a computer language, really). Exactly what is it that Java can't
do in this space?

(Especially since java.nio.channels.FileChannel.map() is Java's
answer to C/C++'s mmap() method.)

I can't say Java's, "everything is a reference except when it is not,"
is a move up from having explicit value, reference, and pointer
semantics that operate in a uniform manner.


It would help if "uniform" = "consistent with type declaration".

int a[5];
int * b = a;

just isn't quite kosher to those schooled in Pascal, convenient as it
might be otherwise; it should be:

int a[5];
int * b = &a[0];

(I don't remember the actual Pascal offhand. It's been too long,
and in any event standard Pascal didn't have an addr() method.)

I'm also not all that sure of the usefulness of such things as

const char * p = "A rainy day in Georgia";
const char * q = p + 15; // q="Georgia"

unless q is an index variable stepping through p's string,
usually in a for or while loop:

for(q = p; *q; q++) { ... }

And of course there are the problems with such things as punning:

char * p = "Another rainy day in Georgia";

void routine(const char * p, char * q)
{
for(;*p;p++, q++) *q = (*p) + 1;
}

routine(p,p);

which could confuse maintainers of routine() -- especially
if routine() for some reason frees its arguments without
checking them first.

For its part Java has its own problems with arrays:

int[] s = new int[]{1,2,3};
int[][] a = new int[][]{
s,
new int[]{1,2,3},
s,
new int[]{4,5},
new int[]{6},
null,
new int[]{7,8,9,10,11}
}

can quite easily trip up naive coding in programs; also,
the int/Integer dichtotomy is a bit of a wart, though not
nearly as bad a lesion as it could have been had Integer
been implemented with a setIntvalue() method.

I like the syntax, though. :-)

--
#191, ew****@earthlink.net
Windows Vista. Because it's time to refresh your hardware. Trust us.
May 3 '06 #364
Timo Stamm wrote:
Luc The Perverse schrieb:
It's a flawed method of rating to begin with. I do not believe we
can directly infer that web page occurrences some how indicate
usage. It may provide some kind of vague correlation - I suppose.


I think a simple chart of sourceforge projects by programming languages
would be much more meaningful. It wouldn't be representational because
it's far from complete, but at least you know what you are measuring.


SourceForge is very non random selection, not very representative of all
language usages.
May 3 '06 #365
Oliver Wong schrieb:
"Chris Smith" <cd*****@twu.net> wrote in message
news:MP************************@news.astraweb.com. ..
- when a smart editor like Eclipse can finish
every line for you, it makes you wonder
what the language is _there_ for!

[...]


Also, when some types in:

public class Foo i

the Eclipse Editor, and just about anyone else who is familiar with
Java, could probably safely assume that the programmer is about to type
in "mplements" to yield:

public class Foo implements

does that mean that the designers of Java should have used the string
"i" instead of "implements" as the keyword? It depends on whether one
values clarity or terseness.


No. But maybe it could have looked like this:

class Foo : List

"public" is made default, ":" replaces "implements" (extends could be
replaced by "<").
A better example for superfluous verbosity:

ArrayList<Entry<String, Integer, Object>> l = new
ArrayList<Entry<String, Integer, Object>>();

Wouldn't it be nice to have local type inference here?

def l = new ArrayList<Entry<String, Integer, Object>>();
Getters and Setters are another good example. Sure, the IDE can generate
them. But C#s properties are a lot more elegant. You can start with
simple public members and introduce getters and setters later without
any need to change the clients of the class.
Anonymous classes are also quickly generated by the IDE, but true
closures with a short syntax would certainly make the code more
expressive and readable.
I don't say that these changes should be made. Java sacrifices
flexibility and expressiveness for readability, and that's fine in many
situations. But I think Phlip raised a valid point, even if it was
comically exaggerated.
Timo
May 3 '06 #366
Mishagam schrieb:
Timo Stamm wrote:
Luc The Perverse schrieb:
It's a flawed method of rating to begin with. I do not believe we
can directly infer that web page occurrences some how indicate
usage. It may provide some kind of vague correlation - I suppose.


I think a simple chart of sourceforge projects by programming
languages would be much more meaningful. It wouldn't be
representational because it's far from complete, but at least you know
what you are measuring.


SourceForge is very non random selection, not very representative of all
language usages.


I know my english isn't perfect, but did you even read what you replied to?
Timo
May 3 '06 #367
Timo Stamm wrote:
Mishagam schrieb:
Timo Stamm wrote:
Luc The Perverse schrieb:
It's a flawed method of rating to begin with. I do not believe we
can directly infer that web page occurrences some how indicate
usage. It may provide some kind of vague correlation - I suppose.

I think a simple chart of sourceforge projects by programming
languages would be much more meaningful. It wouldn't be
representational because it's far from complete, but at least you
know what you are measuring.


SourceForge is very non random selection, not very representative of
all language usages.


I know my english isn't perfect, but did you even read what you replied to?

I meant that not only SourceForge doesn't represent all programmers, it
also represents very non random subset of programmers [and this
selection is very potentially dependent from language used], so any
conclusions about SourceForge projects has very little relation to
language use in general world.
Much better (through less "complete") would be to select 1000
programmers in random and ask them.
May 3 '06 #368
Timo Stamm wrote:
Getters and Setters are another good example. Sure, the IDE can generate
them. But C#s properties are a lot more elegant.


A good design that doesn't need them at all is slightly more elegant
there. ;-)

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
May 3 '06 #369
Phlip schrieb:
Timo Stamm wrote:
Getters and Setters are another good example. Sure, the IDE can generate
them. But C#s properties are a lot more elegant.


A good design that doesn't need them at all is slightly more elegant
there. ;-)


That's the point.

The following link explains it better than I did
http://cephas.net/blog/2004/02/16/c_..._and_setx.html
Timo
May 4 '06 #370
Followups set to non-Java groups.

Timo Stamm wrote:
Getters and Setters are another good example. Sure, the IDE can generate
them. But C#s properties are a lot more elegant.
A good design that doesn't need them at all is slightly more elegant
there. ;-)


That's the point.


No it isn't.
The following link explains it better than I did
http://cephas.net/blog/2004/02/16/c_..._and_setx.html


The more elegant design follows "the hollywood principle". That means "tell
don't ask". (Specifically it means "don't call us we'll call you", but with
slightly greater odds of getting called!)

In the more elegant design, clients tell classes what to do. Clients don't
Get variables (regardless of whatever syntactic sugar is available), then
change data, then call Set variables to push the data back in. Clients
should send messages to servant classes, and these should perform whatever
secret manipulations are required to obey these commands.

Put another way, classes should obey both the physical and logical meaning
of the rule "no public data". Yes, a Get method is slightly more
encapsulated that raw public data. But it's still not fully encapsulated.

The blog you cite quotes Martin Fowler, who assumes we know this before
discussing the C# property system.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
May 4 '06 #371
In comp.lang.java.advocacy, Mishagam
<no*****@provider.com>
wrote
on Wed, 03 May 2006 20:14:11 GMT
<na******************@southeast.rr.com>:
Noah Roberts wrote:
Mishagam wrote:
Noah Roberts wrote:
Mishagam wrote:

> C++ references are not SO different from pointers. Just like Roedy Green
> said - one more addressing mode. I doubt any well designed language
> (like Java) would have (or has) references.
...
C++ pointers and references have completely different purposes.


'purpose' is what language designers imagined references would be used
for. Functionaly, as I understand, difference between references and
pointers is little syntax sugar [ -> replaced with . ] + what values
they can hold - references cannot hold null or objects allocated by new.
But you CAN have reference to destructed object out of scope (or field
in deleted object allocated on heap). Also references syntax resembles
value objects enough that is is difficult to distinguish what you are
using now. It is one more way where C++ loses C clarity.
What I meant is difference with pointer is too small to justify
existence of references for well designed language. I think that
designers of C++ just hated C pointers too much to think rationally.

By the way, I have little problem. I Wiki about C++ reference types I read:
"Once a reference is created, it cannot be later made to reference
another object; we say it cannot be reseated. This is often done with
pointers."
But in my VS 2003 C++ compiler you can easily put new value to
reference, like code sample below. Do you know who is correct here?


You can certainly store through the reference. See below for a
line-by-line description of what this program is actually doing.

(assuming #include <cstdio> at the top, for completeness)

int main() {
OK, no runtime arguments expected during invocation.
int aa = 25;
OK, declaration and initialization of auto variable aa.
int & ra = aa;
OK, declaration of reference ra, an alias for aa. Scope is
routine main(). (It is possible to declare a static reference
to a static variable. It is also possible to declare a
local reference to a static variable. It is not possible to
declare a static reference to a local variable, since the local
variable is out of scope.)
int bb = 323;
OK, declaration and initialization of auto variable bb.
ra = bb;
OK, assignment of bb to aa (via ra). aa now contains 323.
printf("ra= %d\n", ra);
OK, "ra= 323\n" is output.
int *ii = new int;
OK, allocation of a dynamic int.
*ii = 999;
OK, *ii is now initialized to the value 999.
ra = *ii;
OK, aa now contains 999.
printf("ra= %d\n", ra);
OK, "ra= 999\n" is output.
ii = NULL;
OK, ii now contains the pointer NULL.
ra = *ii;
NULL pointer dereference, should cause a failure.
Never mind what *ii is trying to assign to; the system
will dutifully load ii into a register, which will then
contain 0. It will then dereference that register,
causing an exception.
.....
THis code compiled and run OK on VS 2003


Then VS2003's generated code may have a problem.
It segfaults on my machine, as expected.

If you really want I can dump the generated code here as
well, to show you what's going on. There's not much in
the way of GCC-generated comments, so I'll put my own in.
This is on an x86/32 machine running Linux; the syntax is a
little different from Intel's standard (e.g., Intel would
write "movl $25, -4(%ebp)" as "MOV LONG PTR -4(EPB),#25"
or some such; the reasons for the flip are historical).

.section .rodata
..LC0:
.string "ra= %d\n"
.text
.align 2
..globl main
.type main, @function
main:
..LFB3:
pushl %ebp ; standard frame
..LCFI0:
movl %esp, %ebp ; ... adjustment code
..LCFI1:
subl $24, %esp ; apparently this is scratch area
; for subroutine calls
..LCFI2:
andl $-16, %esp ; stack alignment
movl $0, %eax ; clear %EAX
subl %eax, %esp ; No-operation, but why??
movl $25, -4(%ebp) ; store 25 into aa
leal -4(%ebp), %eax ; get aa's location into %EAX
movl %eax, -8(%ebp) ; and store it into ra, which makes
; it a de facto pointer which is
; never moved, as far as the code
; generation is concerned -- looks
; fairly straightforward from a
; backend's standpoint, but may be
; slightly misleading here
movl $323, -12(%ebp) ; initialize bb
movl -8(%ebp), %edx ; get ra's location into %EDX
; this looks a little weird but
; remember that ra is supposed to
; be a reference; however, the
; compiler is treating it as a sort
; of const pointer
movl -12(%ebp), %eax ; get bb's value (323) into %EAX
movl %eax, (%edx) ; store 323 into aa, which is what
; ra is (always) referring to
movl -8(%ebp), %eax ; get ra's location
movl (%eax), %eax ; ... then its value
movl %eax, 4(%esp) ; construct ...
movl $.LC0, (%esp) ; ... parameter list for printf()
call printf ; ... and call it.
movl $4, (%esp) ; construct parameter list
call _Znwj ; ... and call global 'operator new'
movl %eax, -16(%ebp) ; stuff the pointer into ii
movl -16(%ebp), %eax ; now get ii back out again (!)
movl $999, (%eax) ; and shove 999 into it
movl -8(%ebp), %edx ; get ra's location (still aa)
; into %EDX
movl -16(%ebp), %eax ; get ii's *value* into %EAX
movl (%eax), %eax ; dereference ii
movl %eax, (%edx) ; ... and store it into aa
movl -8(%ebp), %eax ; now get ra's location again
movl (%eax), %eax ; ... and fetch its value
movl %eax, 4(%esp) ; construct ...
movl $.LC0, (%esp) ; ... parameter list for printf()
call printf ; and call it.
movl $0, -16(%ebp) ; zap ii
movl -8(%ebp), %edx ; get ra's location yet again
movl -16(%ebp), %eax ; get ii's value again
movl (%eax), %eax ; ***CRASH***
movl %eax, (%edx) ; store ii's deferenced value
movl $0, %eax ; compiler-inserted 'return 0'
leave ; bye...
ret

Obviously, the compiler's doing some interesting (and rather dumb)
things in code generation. The comments are mine, of course, and
hopefully illustrative of its "thinking" process. (For those
schooled in compiler theory, I for one find it interesting that
it's not pushing things onto the stack, but using offsets.)

If I turn on the optimizer (-O) the program gets far shorter,
and probably faster (for what it's worth here).

..globl main
.type main, @function
main:
..LFB14:
pushl %ebp ; standard frame ...
..LCFI0:
movl %esp, %ebp ; ... adjustment code
..LCFI1:
subl $8, %esp ; space for parameters
..LCFI2:
andl $-16, %esp ; align/space for aa,bb, and ii,
; presumably
movl $323, 4(%esp) ; aa=323 store directly
; into printf()'s parameter list;
; the compiler has correctly
; concluded that the '25' value is
; never used, and also doesn't
; bother with an explicit store
movl $.LC0, (%esp) ; setup for printf()
call printf ; and call
movl $4, (%esp) ; we do need 4 bytes
call _Znwj ; ... from 'operator new'
movl $999, (%eax) ; initialize *ii = 999
movl $999, 4(%esp) ; and also store it directly into
; printf()'s parameter list again
; since we've really done very
; little here
movl $.LC0, (%esp) ; setup again
call printf ; and call
movl $0, %eax ; store 0 into ii, presumably
movl %ebp, %esp ; ... hey, wait, you're supposed
popl %ebp ; ... to CRASH HERE!
ret

It would appear that gcc's optimizer has eliminated a
store into *ii at the very end, and "saved" the program.
This is actually an optimizer bug. I suspect VC++ is doing
something similar.

I do not advocate depending on this bug, of course.

Your program would probably be more illustrative if you
were to replace your printf("ra= %d\n", ra) calls with
printf("ra= %d aa= %d bb= %d\n", ra, aa, ab) calls.

I'll have to see if 3.4.6 has the same problem. The code is from 3.3.6.

(Note that crackers do this sort of thing on an ongoing basis, looking
for exploitable loopholes in assembly code. No, I'm not a cracker, but
I do know several dialects of assembler, including this one.)

Now....after *all* that, I can throw another problem out at you.
Suppose one has the code

#include <cstdio>
int main() {
int a[2];
int b[2];
int & ra0 = &a[0];
int & ra1 = &a[1];
a[0] = 1;
a[1] = 2;
b[0] = 3;
b[1] = 4;

ra0 = b[0];
ra1 = b[1];

printf("%d %d %d %d\n", a[0], a[1], b[0], b[1]);

return 0;
}

The output is

3 4 3 4

and it should be very clear as to why.

--
#191, ew****@earthlink.net
Windows Vista. Because it's time to refresh your hardware. Trust us.
May 4 '06 #372
"Phlip" <ph******@yahoo.com> wrote in
news:do*******************@newssvr30.news.prodigy. com:
Followups set to non-Java groups.

Timo Stamm wrote:
Getters and Setters are another good example. Sure, the IDE can
generate them. But C#s properties are a lot more elegant.

A good design that doesn't need them at all is slightly more elegant
there. ;-)


That's the point.


No it isn't.
The following link explains it better than I did
http://cephas.net/blog/2004/02/16/c_..._java_getx_and
_setx.html


The more elegant design follows "the hollywood principle". That means
"tell don't ask". (Specifically it means "don't call us we'll call
you", but with slightly greater odds of getting called!)

In the more elegant design, clients tell classes what to do. Clients
don't Get variables (regardless of whatever syntactic sugar is
available), then change data, then call Set variables to push the data
back in. Clients should send messages to servant classes, and these
should perform whatever secret manipulations are required to obey
these commands.

Put another way, classes should obey both the physical and logical
meaning of the rule "no public data". Yes, a Get method is slightly
more encapsulated that raw public data. But it's still not fully
encapsulated.

The blog you cite quotes Martin Fowler, who assumes we know this
before discussing the C# property system.


You are correct that the data should be private.

But I like the IDEA of C# Properties generating functions. I feel it
encourages the use of them to provide non-variable results. For example,
a Square might have a property Area, (get only) that returns the area of
the square. Or a Color Object might have multiple Properties, RGB or CMYK
for example, that translate to different representations. Internally, it
may use some other definition but that state can only be changed by using
the properties you exposed.

Otis

May 4 '06 #373
The Ghost In The Machine wrote:
ii = NULL;
ra = *ii; THis code compiled and run OK on VS 2003
Then VS2003's generated code may have a problem.
It segfaults on my machine, as expected.


I can recall an MS situation where *NULL contained a 0ul in each address
space. That's because so many NULLs were causing problems that MS decided to
make *NULL bizarrely temporarily useful. (char*)0 would appear to be "", for
example.

I could be wrong; all this is both undefined behavior and off-topic, etc...
movl -8(%ebp), %edx ; get ra's location (still aa)
; into %EDX


props!

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
May 4 '06 #374
Phlip wrote:
In the more elegant design, clients tell classes what to do. Clients don't
Get variables (regardless of whatever syntactic sugar is available), then
change data, then call Set variables to push the data back in. Clients
should send messages to servant classes, and these should perform whatever
secret manipulations are required to obey these commands.


Agreed.

Still, an argument could be made that if a program has design errors, then they
should /look/ like design errors too.

So the correct design for the language is for it to provide "properties"
instead of requiring get/set() pairs. And the correct design for any program
written /in/ that language is for it not to use properties at all.

;-)

-- chris


May 4 '06 #375
Phlip schrieb:
Followups set to non-Java groups.

Timo Stamm wrote:
Getters and Setters are another good example. Sure, the IDE can generate
them. But C#s properties are a lot more elegant.
A good design that doesn't need them at all is slightly more elegant
there. ;-) That's the point.


No it isn't.


Then I misunderstood your point.

I thought that "them" referred to accessor methods. Now I realize that
you referred to public members in general.

The following link explains it better than I did
http://cephas.net/blog/2004/02/16/c_..._and_setx.html


The more elegant design follows "the hollywood principle". That means "tell
don't ask". (Specifically it means "don't call us we'll call you", but with
slightly greater odds of getting called!)

In the more elegant design, clients tell classes what to do. Clients don't
Get variables (regardless of whatever syntactic sugar is available), then
change data, then call Set variables to push the data back in. Clients
should send messages to servant classes, and these should perform whatever
secret manipulations are required to obey these commands.

Put another way, classes should obey both the physical and logical meaning
of the rule "no public data". Yes, a Get method is slightly more
encapsulated that raw public data. But it's still not fully encapsulated.


All agreed. But I don't think that full encapsulation is appropriate in
all cases, even in a clean object oriented design.

I think the following article of Martin Fowler has a balanced view on
the topic:

http://www.martinfowler.com/bliki/GetterEradicator.html
Timo

The blog you cite quotes Martin Fowler, who assumes we know this before
discussing the C# property system.

May 4 '06 #376
In comp.lang.java.advocacy, Phlip
<ph******@yahoo.com>
wrote
on Thu, 04 May 2006 03:24:34 GMT
<St**************@newssvr33.news.prodigy.com>:
The Ghost In The Machine wrote:
ii = NULL;
ra = *ii; THis code compiled and run OK on VS 2003


Then VS2003's generated code may have a problem.
It segfaults on my machine, as expected.


I can recall an MS situation where *NULL contained a 0ul in each address
space. That's because so many NULLs were causing problems that MS decided to
make *NULL bizarrely temporarily useful. (char*)0 would appear to be "", for
example.

I could be wrong; all this is both undefined behavior and off-topic, etc...
movl -8(%ebp), %edx ; get ra's location (still aa)
; into %EDX


props!


I'll admit, I for one would love to see an -S option in Java. Best I
can do is to use BCEL afterwards. :-) Or maybe gcj.

ObOffTopic: It appears gcc has a similar problem. I'll have to see if a
"dead" pointer store is mistakenly optimized away in a non-main()
routine; that could lead to some subtle C++ bugs.

Microsoft may be having a hangover from its DOS days, when 0000:0000
was a valid address of sorts. :-)

--
#191, ew****@earthlink.net
Windows Vista. Because it's time to refresh your hardware. Trust us.
May 4 '06 #377

The Ghost In The Machine wrote:
In comp.lang.java.advocacy, Noah Roberts
<ro**********@gmail.com>
wrote
on 3 May 2006 09:51:31 -0700
<11**********************@e56g2000cwe.googlegroups .com>:

Mishagam wrote:
Noah Roberts wrote:
> Mishagam wrote:
>
>> C++ references are not SO different from pointers. Just like Roedy Green
>> said - one more addressing mode. I doubt any well designed language
>> (like Java) would have (or has) references.
>
> Java has references.
>
Excuse me. I meant separate references and pointers with so close
functions. Java has references, but they have also some features of C++
pointers like they can be null.
C++ pointers and references have completely different purposes. The
fact that Java lacks pointers is just another can't.


Pointers are a means to an end (well, so is everything else in
a computer language, really). Exactly what is it that Java can't
do in this space?


None that matter to Java.

I can't say Java's, "everything is a reference except when it is not,"
is a move up from having explicit value, reference, and pointer
semantics that operate in a uniform manner.


It would help if "uniform" = "consistent with type declaration".

int a[5];
int * b = a;

just isn't quite kosher to those schooled in Pascal, convenient as it
might be otherwise; it should be:

int a[5];
int * b = &a[0];


You can use this syntax if you wish and believe it makes more sense.
Nothing stopping you there. You can even establish a coding standard
to say the former is not allowed. Nothing stopping you there. Since
C++ doesn't make pointless artificial restrictions just to enforce a
policy that is really a developer side issue you can also do the former
if it makes sense to you, and it does to most C++ programmers (who
cares about programmers in another language...code in the language you
are using).
(I don't remember the actual Pascal offhand. It's been too long,
and in any event standard Pascal didn't have an addr() method.)
Hmmm...I don't see Pascal used for a lot of stuff.
I'm also not all that sure of the usefulness of such things as

const char * p = "A rainy day in Georgia";
const char * q = p + 15; // q="Georgia"

unless q is an index variable stepping through p's string,
usually in a for or while loop:

for(q = p; *q; q++) { ... }
Umm...yeah, that is one use....why did you say you weren't sure of its
usefulness??!!
And of course there are the problems with such things as punning:

char * p = "Another rainy day in Georgia";

void routine(const char * p, char * q)
{
for(;*p;p++, q++) *q = (*p) + 1;
}
Well that function is bad for numerous reasons, not the least of which
is its use of char* instead of string. There are numerous ambiguities
that need be established that can only be so by looking at that code.
For one, who owns q?

Also, even a java programmer should see that it blows up. If you are
familiar with pointers enough to even know what that does you can see
that it doesn't work.
routine(p,p);

which could confuse maintainers of routine() -- especially
if routine() for some reason frees its arguments without
checking them first.
Yes, who owns q?

That routine is just poorly designed and even poorly implemented. Yes,
you can write bad code in any language and C++ is certainly no
exception to that.
For its part Java has its own problems with arrays:

int[] s = new int[]{1,2,3};


Ick, and you say C++ has ugly syntax.

int s[] = {1, 2, 3};

May 4 '06 #378

"Timo Stamm" <ti********@arcor.de> wrote in message
news:44**********************@newsread2.arcor-online.net...
Oliver Wong schrieb:

does that mean that the designers of Java should have used the string
"i" instead of "implements" as the keyword? It depends on whether one
values clarity or terseness.
No. But maybe it could have looked like this:

class Foo : List

"public" is made default, ":" replaces "implements" (extends could be
replaced by "<").


Not sure "<" is the best choice, as it might be mistaken for a generic
type argument, but otherwise the idea is sound.


A better example for superfluous verbosity:

ArrayList<Entry<String, Integer, Object>> l = new
ArrayList<Entry<String, Integer, Object>>();

Wouldn't it be nice to have local type inference here?

def l = new ArrayList<Entry<String, Integer, Object>>();
I had forgotten about this feature in C++, and I can see the utility of
it. These two syntactic-sugar changes sound harmless enough that I think you
could (relatively) easily write a compiler that compiles from this new
language back to "plain" Java, and from there run the standard java compiler
to get the class files (or gcj for executables or whatever).

Getters and Setters are another good example. Sure, the IDE can generate
them. But C#s properties are a lot more elegant. You can start with simple
public members and introduce getters and setters later without any need to
change the clients of the class.


The language could forbid public fields altogether, and have

<code>
public int foo;
</code>

be syntactic sugar for

<code>
private int foo;

public int foo {
get { return foo; }
set { foo = value; }
}
</code>

assuming the language had some sort of mechanism for disabiguating between
the public property and the private field.

- Oliver

May 4 '06 #379

Timo Stamm wrote:
No. But maybe it could have looked like this:

class Foo : List

"public" is made default, ":" replaces "implements" (extends could be
replaced by "<").
Don't know if you meant to imply that C++ works that way but it
doesn't. "public" is not the default inheritance mode, private is.

A better example for superfluous verbosity:

ArrayList<Entry<String, Integer, Object>> l = new
ArrayList<Entry<String, Integer, Object>>();

Wouldn't it be nice to have local type inference here?

def l = new ArrayList<Entry<String, Integer, Object>>();
You mean like this?:

typedef ArrayList<Entry<String, Integer, Object> > AL;

AL l1;
AL l2;

VERY commonly done.

Getters and Setters are another good example. Sure, the IDE can generate
them. But C#s properties are a lot more elegant. You can start with
simple public members and introduce getters and setters later without
any need to change the clients of the class.


Getters and Setters are just poor design indicating that perhapse a
class is not the best data type to represent your data or that your
classes are lazy.

May 4 '06 #380
"Noah Roberts" <ro**********@gmail.com> wrote in message
news:11**********************@j73g2000cwa.googlegr oups.com...

char * p = "Another rainy day in Georgia";

void routine(const char * p, char * q)
{
for(;*p;p++, q++) *q = (*p) + 1;
}


Well that function is bad for numerous reasons, not the least of which
is its use of char* instead of string. There are numerous ambiguities
that need be established that can only be so by looking at that code.
For one, who owns q?

Also, even a java programmer should see that it blows up. If you are
familiar with pointers enough to even know what that does you can see
that it doesn't work.


I think to grok the above code, you have to know certain things that you
might never learn if you programmed only in Java, such as the idea that char
strings are terminated by 0.

- Oliver

May 4 '06 #381

Oliver Wong wrote:
"Noah Roberts" <ro**********@gmail.com> wrote in message
news:11**********************@j73g2000cwa.googlegr oups.com...

char * p = "Another rainy day in Georgia";

void routine(const char * p, char * q)
{
for(;*p;p++, q++) *q = (*p) + 1;
}


Well that function is bad for numerous reasons, not the least of which
is its use of char* instead of string. There are numerous ambiguities
that need be established that can only be so by looking at that code.
For one, who owns q?

Also, even a java programmer should see that it blows up. If you are
familiar with pointers enough to even know what that does you can see
that it doesn't work.


I think to grok the above code, you have to know certain things that you
might never learn if you programmed only in Java, such as the idea that char
strings are terminated by 0.


If you don't understand that you never would have written it.

You might not understand the following if you programmed only in
QBasic:

class X implements Y {}

May 4 '06 #382
In article <11**********************@j73g2000cwa.googlegroups .com>,
Noah Roberts <ro**********@gmail.com> wrote:

The Ghost In The Machine wrote:

For its part Java has its own problems with arrays:

int[] s = new int[]{1,2,3};


Ick, and you say C++ has ugly syntax.

int s[] = {1, 2, 3};


This exact line will also work as expected in Java.

Cheers
Bent D
--
Bent Dalager - bc*@pvv.org - http://www.pvv.org/~bcd
powered by emacs
May 4 '06 #383
Noah Roberts wrote:
Wouldn't it be nice to have local type inference here?

defÂ*lÂ*=Â*newÂ*ArrayList<Entry<String,Â*Integer ,Â*Object>>();


You mean like this?:

typedef ArrayList<Entry<String, Integer, Object> > AL;

AL l1;
AL l2;

VERY commonly done.


By the programmer instead of the compiler.

Computers exist to automate rote tasks.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
May 4 '06 #384
In article <mj********************************@4ax.com>,
my******************************@munged.invalid says...

[ ... ]
I wonder if someday we will have a language that lets you write like
Ruby, but that does all kinds of inferencing to tell you additional
info like types, potential bounds etc. but only when you want to see
it.


Yes. It'll be called APL.

--
Later,
Jerry.

The universe is a figment of its own imagination.
May 5 '06 #385
In article <1146755237.231059.87100
@g10g2000cwb.googlegroups.com>, ro**********@gmail.com
says...

[ ... ]
Don't know if you meant to imply that C++ works that way but it
doesn't. "public" is not the default inheritance mode, private is.


In C++, private inheritance is the default for classes,
but public inheritance is the default for structs. Lots
of people routinely write:

class X : public Y {
public:
// ...
};

which is equivalent to:

struct X : Y {
// ...
};
Getters and Setters are another good example. Sure, the IDE can generate
them. But C#s properties are a lot more elegant. You can start with
simple public members and introduce getters and setters later without
any need to change the clients of the class.


Getters and Setters are just poor design indicating that perhapse a
class is not the best data type to represent your data or that your
classes are lazy.


Or that your variables aren't really of the correct type
to start with. From what I've seen, the majority of
getters and setters don't really do anything, and are
exactly equivalent to public data with a really ugly
syntax.

Of the (small) minority that really do something, most do
nothing more than enforce the variable being within a
fixed range (e.g. an integer restricted to the range
0..1024). Some languages (e.g. Ada) provide that
capability directly, and exposing the data publicly works
just fine, because the compiler enforces the constraint
without explicit help beyond the definition of the
variable's range.

Other languages (e.g. C++) have the flexibility to allow
the programmer to do the job by defining the correct type
for the variable in question, and enforcing its
constraints explicitly (but still centralizing the
enforcement). For the simple range constraint, for
example, you can write a small template like:

template <class T, T lower, T upper, class less=std::less
<T> >
class bounded {
T val;

static bool check(T const &value) {
return less()(value, lower) ||
less()(upper, value);
}

public:
bounded() : val(lower) { }

bounded(T const &v) {
if (check(v))
throw std::domain_error("out of range");
val = v;
}

bounded(bounded const &init) : val(init.v) {}

bounded &operator=(T const &v) {
if (check(v))
throw std::domain_error("Out of Range");
val = v;
return *this;
}

operator T() const { return val; }

friend std::istream &
operator>>(std::istream &is, bounded &b)
{
T temp;
is >> temp;

if (check(temp))
is.setstate(std::ios::failbit);
b.val = temp;
return is;
}
};

With this, we can make a data member public, keep (even
tighter) encapsulation, and still get nice syntax that's
easy to read and use. At least as it stands right now, I
don't see a way to do this in Java, but Java is close
enough now that I can imagine enough being added at some
point to support it...

--
Later,
Jerry.

The universe is a figment of its own imagination.
May 5 '06 #386
In article <1m************@sirius.tg00suus7038.net>,
ew***@sirius.tg00suus7038.net says...

[ ... ]
However, I have no idea what

{

std::ifstream ifs1("pathname");
std::ifstream ifs2(ifs1);
doSomething(ifs1);
doSomething(ifs2);
}

or

{

std::ifstream ifs1("pathname");
std::ifstream ifs2("path2");

ifs1 = ifs2;

doSomething(ifs1);
doSomething(ifs2);
}


What they do is produce compiler errors -- nothing more
and nothing less. streams cannot be either copied or
assigned. Many years ago (pre-standard) there were
versions of C++ iostreams that included an
iostream_withassign, but that's ancient history.

You can make two iostreams refer to the same external
file if you wish, but the code isn't anything like the
above, and it leaves little room for question for what it
would mean. The most obvious is simply:

std::ifstream ifs1("pathname");
std::ifstream ifs2("pathname");

At least if memory serves, you can also tell two
iostreams to use the same stream buffer. In the iostreams
model, the iostream itself deals primarily with
formatting. The stream buffer is what deals with things
like the storage of the data.

--
Later,
Jerry.

The universe is a figment of its own imagination.
May 5 '06 #387
Most of the messages in this thread appear to be written by people who
only know one programming language. Have you not discovered that most
programming languages have their strengths as well as their weaknesses?
I occasionally do some maintenance in F77 and every time I am surprised
at some of the number crunching power that has been built into this
version of Fortran. I am currently writing software to control
equipment in real time and, even though I llike Java a lot, it is not
the appropriate language because of the rapid respnses required to
control equipment. Consequently C++ is more useful. You haggle about
things that are not worth haggling about. Kind regards, Willem Ferguson.

May 5 '06 #388
In article <MP************************@news.sunsite.dk>,
Jerry Coffin <jc*****@taeus.com> wrote:

Or that your variables aren't really of the correct type
to start with. From what I've seen, the majority of
getters and setters don't really do anything, and are
exactly equivalent to public data with a really ugly
syntax.


The primary advantage to encapsulating otherwise public data into
accessors that don't actually add anything is that access to this data
can later be easily changed to do something interesting.

It is a poor man's encapsulation, but it's still better than just
having public data fields.

Cheers
Bent D
--
Bent Dalager - bc*@pvv.org - http://www.pvv.org/~bcd
powered by emacs
May 5 '06 #389
> Most of the messages in this thread appear to be written by people who
only know one programming language.


in chronological order:

C64 BASIC
ARM BASIC
ARM Assembler
Motorola Assembler
Pascal
C
Modula 2
Opal (ugly)
VisualBasic
Java.

Andrey

--
http://uio.imagero.com Unified I/O for Java
http://reader.imagero.com Java image reader
http://jgui.imagero.com Java GUI components and utilities
May 5 '06 #390

Bent C Dalager wrote:
In article <MP************************@news.sunsite.dk>,
Jerry Coffin <jc*****@taeus.com> wrote:

The primary advantage to encapsulating otherwise public data into
accessors that don't actually add anything is that access to this data
can later be easily changed to do something interesting.


Yes,

One can change the value (if later computation is required) without
changing the interface. Resolution requirements change come to mind.
All said, how about the client specifying what he want.
template <class T>
struct IfToData //Or model from MVC
{
virtual const T& get( boost::void_<T> ) = 0;
};

....now the one getting specifies what he wants - his data now could
become:
boost::weak_ptr<IfToData<int> > myDataModel_;

This also makes him independent of the client from whom he receives
data...

Regards,

W


It is a poor man's encapsulation, but it's still better than just
having public data fields.

Cheers
Bent D
--
Bent Dalager - bc*@pvv.org - http://www.pvv.org/~bcd
powered by emacs


May 5 '06 #391
In article <e3**********@orkan.itea.ntnu.no>,
bc*@pvv.ntnu.no says...
In article <MP************************@news.sunsite.dk>,
Jerry Coffin <jc*****@taeus.com> wrote:

Or that your variables aren't really of the correct type
to start with. From what I've seen, the majority of
getters and setters don't really do anything, and are
exactly equivalent to public data with a really ugly
syntax.
The primary advantage to encapsulating otherwise public data into
accessors that don't actually add anything is that access to this data
can later be easily changed to do something interesting.


If you'd read what I posted (the code in particular)
you'd realize that the same is possible when you DO use
public variables.
It is a poor man's encapsulation, but it's still better than just
having public data fields.


No, it's really not.

--
Later,
Jerry.

The universe is a figment of its own imagination.
May 5 '06 #392
"Bent C Dalager" <bc*@pvv.ntnu.no> wrote in message
news:e3**********@orkan.itea.ntnu.no...
In article <MP************************@news.sunsite.dk>,
Jerry Coffin <jc*****@taeus.com> wrote:

Or that your variables aren't really of the correct type
to start with. From what I've seen, the majority of
getters and setters don't really do anything, and are
exactly equivalent to public data with a really ugly
syntax.


The primary advantage to encapsulating otherwise public data into
accessors that don't actually add anything is that access to this data
can later be easily changed to do something interesting.

It is a poor man's encapsulation, but it's still better than just
having public data fields.


The code I'm working with has two classes that do almost the same thing,
because the code was built by merging two other programs together.

<Java>
class NodeToken {
public int beginColumn, endColumn;
}

class Token {
public int startColumn, endColumn;
}
</Java>

I'm trying to merge these two classes together. If they had used accessor
methods, I could have a methods setStartColumn(int) and setBeginColumn(int)
affect the same private field, so that the changes would be seen by either
interfaces. Unfortunately, they didn't use accessor methods, and instead
used public fields, so now I've got to start by adding the accessor methods
to each seperate classes, mark the fields as deprecated, check for all
access to those fields, change those to invoke the accessor methods, then
merge the class, then simplify the API.

- Oliver

May 5 '06 #393

Oliver Wong wrote:
"Bent C Dalager" <bc*@pvv.ntnu.no> wrote in message
news:e3**********@orkan.itea.ntnu.no...
In article <MP************************@news.sunsite.dk>,
Jerry Coffin <jc*****@taeus.com> wrote:

Or that your variables aren't really of the correct type
to start with. From what I've seen, the majority of
getters and setters don't really do anything, and are
exactly equivalent to public data with a really ugly
syntax.


The primary advantage to encapsulating otherwise public data into
accessors that don't actually add anything is that access to this data
can later be easily changed to do something interesting.

It is a poor man's encapsulation, but it's still better than just
having public data fields.


The code I'm working with has two classes that do almost the same thing,
because the code was built by merging two other programs together.

<Java>
class NodeToken {
public int beginColumn, endColumn;
}

class Token {
public int startColumn, endColumn;
}
</Java>

I'm trying to merge these two classes together. If they had used accessor
methods, I could have a methods setStartColumn(int) and setBeginColumn(int)
affect the same private field, so that the changes would be seen by either
interfaces. Unfortunately, they didn't use accessor methods, and instead
used public fields, so now I've got to start by adding the accessor methods
to each seperate classes, mark the fields as deprecated, check for all
access to those fields, change those to invoke the accessor methods, then
merge the class, then simplify the API.


Interestingly one thing the Java camp never brought up was the tools
they have available to them to make them more productive. Among those
tools are much more sofisticated refactoring tools. The only one I
have been able to find for C++ has been Ref+ and though it does a lot
it is still missing a lot of refactors you get with just about every
version of Java or .Net refactor tool out there. I'm going to blame
this on parsing.

Encapsulate Member is a very common refactor and comes in most tools,
including Ref+, and makes the above process completely automatic. Pop
up a wizard, set a couple of values, and let it go do its thing. They
usually work quite well and I suspect the Java version to be even more
accurate. You use this refactor when you find a public variable that
needs to be encapsulated in a getter and/or setter so that you can
alter behavior or when you need to change the variable to some other
form and you use it even internally to your class.

May 5 '06 #394
In article <MP************************@news.sunsite.dk>,
Jerry Coffin <jc*****@taeus.com> wrote:

If you'd read what I posted (the code in particular)
you'd realize that the same is possible when you DO use
public variables.


My comment was largely based on language neutrality. I would rephrase
it to only cover languages that do not have other means of
accomplishing the same effect.

Data encapsulation is the goal. Trivial getX/setX accessors are a
means to reach that goal, and quite defensible in languages that
provide no other (better) means of getting there.

I need to add that in the context of the original suggestion (that
being able to directly access another object's state is wrong in
itself), your operator-based approach would be equally wrong, only
with a nicer syntax. It remains a poor man's approach to
encapsulation: Any algorithms that need to alter an object's state
should be internal to that object itself, not external to it.

According to this philosophy, you would never write
employee.wage *= 1.1;
You would write
employee.raiseWagePercent(10);

Cheers
Bent D
--
Bent Dalager - bc*@pvv.org - http://www.pvv.org/~bcd
powered by emacs
May 5 '06 #395
In article <11**********************@e56g2000cwe.googlegroups .com>,
Noah Roberts <ro**********@gmail.com> wrote:

Interestingly one thing the Java camp never brought up was the tools
they have available to them to make them more productive. Among those
tools are much more sofisticated refactoring tools. The only one I
have been able to find for C++ has been Ref+ and though it does a lot
it is still missing a lot of refactors you get with just about every
version of Java or .Net refactor tool out there. I'm going to blame
this on parsing.


xref-tech.com has XRefactory. I have only used it on C and Java but I
understand they now support C++.

It's quite expensive for hobby users though, and I blame _that_ on
parsing :-)

Cheers
Bent D
--
Bent Dalager - bc*@pvv.org - http://www.pvv.org/~bcd
powered by emacs
May 5 '06 #396
Walter Bright <wa****@digitalmars-nospamm.com> wrote:
Mishagam wrote:
I think the fact that nobody uses D means suggests that it has not only
one stupid feature, but a lot of stupid features.


For a stupid language nobody uses, the D programming language is doing
remarkably well, having moved up to number 19 on
http://www.tiobe.com/tpci.htm


That means it's a language people mention on web pages, not that it's a
language people use.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
May 5 '06 #397
Oliver Wong <ow***@castortech.com> wrote:
For a stupid language nobody uses, the D programming language is doing
remarkably well, having moved up to number 19 on
http://www.tiobe.com/tpci.htm


(referring to http://www.tiobe.com/tiobe_index/images/tpci_trends.gif as
of May 2nd, 2006): I wonder what happened in 2004 that made Java drop
considerably, and everything else jump up a bit.


If you read the FAQ, they point out that it was a change in the way
Google indexed web pages. I won't speculate (though, clearly, I'm okay
with implying) about what it means when the single biggest point made by
this index turns out to just be an artifact of their methodology.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
May 5 '06 #398
peter koch <pe***************@gmail.com> wrote:
So e.g. Swing, JDBC and Vector are all implemented in Java? Without a
single JNI-call in the code? It seems my knowledge of Java needs an
update.


Considered in turn:

Swing: The major part of Swing is written in Java. There are some small
pieces (the only one that comes to mind is the FileSystemView class)
that are not. Of course, Swing depends on AWT, which is implemented
partly in other languages.

JDBC: The JDBC API is completely written in Java. It would have been
silly to use native code for something that is basically just a bunch of
glue. Whether JDBC drivers are written entirely in Java depends on the
driver. About 90% of them are, but a few are not. Oracle, for example,
provides both a pure Java driver and a driver that uses JNI, but I don't
know of anyone using the latter. The only driver that I've contributed
to and thus worked with closely was PostgreSQL, and that's certainly
100% Java.

Vector: Yes, it's all in Java. Again, it would be silly to implement
this in native code. The result would perform poorly and be harder to
maintain.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
May 5 '06 #399

"Noah Roberts" <ro**********@gmail.com> wrote in message
news:11**********************@e56g2000cwe.googlegr oups.com...

Oliver Wong wrote:
"Bent C Dalager" <bc*@pvv.ntnu.no> wrote in message
news:e3**********@orkan.itea.ntnu.no...
> In article <MP************************@news.sunsite.dk>,
> Jerry Coffin <jc*****@taeus.com> wrote:
>>
>>Or that your variables aren't really of the correct type
>>to start with. From what I've seen, the majority of
>>getters and setters don't really do anything, and are
>>exactly equivalent to public data with a really ugly
>>syntax.
>
> The primary advantage to encapsulating otherwise public data into
> accessors that don't actually add anything is that access to this data
> can later be easily changed to do something interesting.
>
> It is a poor man's encapsulation, but it's still better than just
> having public data fields.
The code I'm working with has two classes that do almost the same
thing,
because the code was built by merging two other programs together.

<Java>
class NodeToken {
public int beginColumn, endColumn;
}

class Token {
public int startColumn, endColumn;
}
</Java>

I'm trying to merge these two classes together. If they had used accessor
methods, I could have a methods setStartColumn(int) and
setBeginColumn(int)
affect the same private field, so that the changes would be seen by
either
interfaces. Unfortunately, they didn't use accessor methods, and instead
used public fields, so now I've got to start by adding the accessor
methods
to each seperate classes, mark the fields as deprecated, check for all
access to those fields, change those to invoke the accessor methods, then
merge the class, then simplify the API.


Interestingly one thing the Java camp never brought up was the tools
they have available to them to make them more productive. Among those
tools are much more sofisticated refactoring tools. The only one I
have been able to find for C++ has been Ref+ and though it does a lot
it is still missing a lot of refactors you get with just about every
version of Java or .Net refactor tool out there.


It might be that the Java camp assumes that this ease of refactoring is
completely natural, and that all developers have access to the technology.
As others have said, the people best suited to claim one language is
"better" than another, for some definition of "better", are those that have
actually used both languages.

Encapsulate Member is a very common refactor and comes in most tools,
including Ref+, and makes the above process completely automatic.


In my specific case, the code accessing the public field is generated
(I'm working with parser generators, and hence the "Token" class), so I'd
have to actually edit the code that generates the code that accesses these
fields. I think the automated wizards aren't smart enough to deal with that
yet.

- Oliver

May 5 '06 #400

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Ravi Tallury | last post by:
Hi We are having issues with our application, certain portions of it stop responding while the rest of the application is fine. I am attaching the Java Core dump. If someone can let me know what...
1
by: ptaz | last post by:
Hi I'm trying to run a web page but I get the following error. Ca anyone please tell me a solution to this. Thanks Ptaz HTTP Status 500 - type Exception report
11
by: DrUg13 | last post by:
In java, this seems so easy. You need a new object Object test = new Object() gives me exactly what I want. could someone please help me understand the different ways to do the same thing in...
0
by: mailkhurana | last post by:
Hii , I am trying to use a type 2 driver to connect to DB2 0n AIX 5 I have a small java test to class to establish a conneciton with the db .. I am NOT using WAS or any appserver When I try to...
1
by: David Van D | last post by:
Hi there, A few weeks until I begin my journey towards a degree in Computer Science at Canterbury University in New Zealand, Anyway the course tutors are going to be teaching us JAVA wth bluej...
12
by: Mark Fink | last post by:
I wrote a Jython class that inherits from a Java class and (thats the plan) overrides one method. Everything should stay the same. If I run this nothing happens whereas if I run the Java class it...
0
by: jaywak | last post by:
Just tried running some code on Linux (2.4.21-32.0.1.EL and Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_04-b05)) and Windows XPSP2 (with Java HotSpot(TM) Client VM (build...
1
by: jaimemartin | last post by:
hello, I want to validate an xml by means of a schema (xsd). To do that first of all I´m using a SchemaFactory. The problem is that if I run the code in Windows all works fine, but If I run it in...
0
oll3i
by: oll3i | last post by:
package library.common; import java.sql.ResultSet; public interface LibraryInterface { public ResultSet getBookByAuthor(String author); public ResultSet getBookByName(String name);
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.