Naming structs with a variable

C

Chris Nahr

No, they shouldn't. They should consider whether they want reference or
value semantics, work out how large the type will be, find out whether
it's actually going to be a bottleneck anyway, whether making it a
value type will actually make it more efficient, etc.

But what are you talking about here other than the (important)
difference between value and refernce semantics? You're talking about
size and speed -- and imply that people should look into structs where
the size of the type is small and speed is a requirement.

Which is exactly what the term "lightweight class" conveys.
No, it's not. They're different beasts, and calling one a lightweight
version of the other doesn't in any way convey the important
differences between them.

I simply disagree here. In my opinion, the term "lightweight class"
nicely conveys both the implementation and the intended use of a
struct. So does the term "struct" itself insofar as structs are used
as simple data containers in C++ which is also the typical struct use.

It's the responsibility of the programmer to figure out any other
important differences. You can't seriously expect to pack the entire
reference documentation in a name or an adjective.

What other name would you suggest, anyway?
I agree it's not very difficult, but it's not aided in any way by
calling structs lightweight classes, any more than learning the
differences between int and float would be aided by calling int a
lightweight float.

That's a poor analogy because floats are stored in the same way as
ints, take up the same storage space, and these days aren't even much
slower than ints...
 
A

Alvin Bruney

I think the lightweightedness terminology is a lot more friendly, al beit,
less technically appealing for the semantic die-hards out there. Generally,
the definition has served its purpose well because it indicates to some
extent that a class should be preferred over a struct except in
circumstances where performance may be a concern. The fact of the matter is
structs and classes are related by blood and so, one is usually described
within the context of the other. Adjusting the literature to define
otherwise is unappealing and fails to take the lineage into account.

--

________________________
Warm regards,
Alvin Bruney [MVP ASP.NET]

[Shameless Author plug]
Professional VSTO.NET - Wrox/Wiley
The O.W.C. Black Book with .NET
www.lulu.com/owc, Amazon
Blog: http://www.msmvps.com/blogs/alvin
-------------------------------------------------------
 
B

Bruce Wood

That's a correct description!
No, it's not. They're different beasts, and calling one a lightweight
version of the other doesn't in any way convey the important
differences between them.

Precisely. Dead on.

I realize that Chris has already responded to Jon's analogy, but it's
so good that I have to repeat it: Does that then mean that it's OK to
refer to ints as "lightweight floats"? Or floats as "heavyweight ints"?

The problem with that description is that it says nothing about what
really matters: why you would choose one over the other. Ints offer
precision but no fractional content. Floating point offers fractional
content but is not precise. Unless the programmer understands both what
they can store _and_ how precise they are, he can't make an informed
decision as to which one he needs.

For me, all of the stuff about structs not participating in
inheritance, and that their "lineage" comes from classes (whatever that
means) is secondary to the principal reason why you would choose one
over the other: value semantics versus reference semantics. Even the
"allocated on the stack" versus "allocated on the heap" distinction
isn't really terribly important. What is terribly important is that
structs are _copied_ constantly, whereas classes aren't.

So far I have _never_ found a situation so compelling that I decided to
use a "struct" for efficiency reasons, or because it doesn't
participate in the inheritance hierarchy. I have several structs in the
system on which I work, and all of them are there because the type
requires value semantics. Jon mentioned _one_ case in which he created
a struct type for efficiency reasons. I assume that he has created
others for other reasons, but perhaps I'm wrong.

This whole conversation reminds me of asking whether databases or flat
files are "more efficient". The question sidesteps the primary reasons
why you would choose one over the other: either answer, yes or no,
would be incomplete and misleading.
 
B

Bruce Wood

The problem is that the mechanism that provides for this lightweight-ness has a few gotchas that C++ people will miss.

Funny. I see it from completely the other way around.

C# contains something called "struct" that is very useful, but
substantially different from "class" and substantially different from
the "struct" in C++, although it has some passing similarities to the
latter. Unfortunately, by using the same keyword for something new, the
language practically guarantees that C++ programmers will assume that
"struct" in C# is supposed to be like "struct" in C++ and will attempt
to use it as they did before, with less than satisfactory results.

I prefer to think of the C# struct as a way to construct my own value
types that act like "int" or "double". I consider its similarities to
C++'s "struct" to be artifacts of its value semantics and neither
terribly interesting nor terribly useful.
 
L

Lucian Wischik

Bruce Wood said:
I realize that Chris has already responded to Jon's analogy, but it's
so good that I have to repeat it: Does that then mean that it's OK to
refer to ints as "lightweight floats"? Or floats as "heavyweight ints"?

Because structs have value-semantics, if you send a struct to one
thread and also to another, then the two threads will have their own
copies which won't interfere. Therefore, and in the spirit of
misleading terminology, I propose that we call structs
"thread-safe lightweight classes"
:)
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

Note that I suggested to make it a class before adding methods to it. :)

I agree with your clear example of the risks of using structs. They can
be tricky, especially if they contain objects.

As a rule, there is very rarely any reason to make it a struct if it
contains objects, don't you say?
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

Chris said:
Structs _are_ lightweight classes in C#

No, structs are not classes, not even lightweight classes, and they
don't behave like classes. In most aspects structs are more lightweight
than classes, but that doesn't make the struct a leightweight version of
the class.
 
J

Jon Skeet [C# MVP]

Chris Nahr said:
But what are you talking about here other than the (important)
difference between value and refernce semantics? You're talking about
size and speed -- and imply that people should look into structs where
the size of the type is small and speed is a requirement.

Which is exactly what the term "lightweight class" conveys.

Except that it concentrates on the less important part of it. It's like
describing the difference between a mouse and a planet as "one is
bigger than another". While that's true, it's not the most important
thing by a long shot.
I simply disagree here. In my opinion, the term "lightweight class"
nicely conveys both the implementation and the intended use of a
struct.

It doesn't indicate the value/reference semantics *at all*. Those are
the most important semantics - any description which doesn't indicate
that there is such a difference is misleading IMO.
So does the term "struct" itself insofar as structs are used
as simple data containers in C++ which is also the typical struct use.

It's the responsibility of the programmer to figure out any other
important differences. You can't seriously expect to pack the entire
reference documentation in a name or an adjective.

No - so why try, given that some people *will* take the simplistic
description at face value and try to apply it without going into any
more detail?
What other name would you suggest, anyway?

I would avoid using any simplistic term, preferring to refer people to
an article/book/whatever which explains the difference properly.
That's a poor analogy because floats are stored in the same way as
ints, take up the same storage space, and these days aren't even much
slower than ints...

Except they're fundamentally different in what they store. The biggest
difference between them is conceptual, not performance.
 
J

Jon Skeet [C# MVP]

I think the lightweightedness terminology is a lot more friendly, al beit,
less technically appealing for the semantic die-hards out there.

That's like saying that the following statements are "more friendly"
than the truth:

o "Structs are stored on the stack, classes are stored on the heap"
o "Reference type parameters are passed by reference by default"

Neither of these is correct. Both *have* caused confusion - confusion
which has manifested itself on this very newsgroup, several times. Both
are generally defended on the grounds of being "friendlier", with
similar name-calling of those who view correctness as important as
"semantic die-hards" and the like.

I don't see what's "die-hard" about wanting to give a correct
impression, rather than misleading people. It's not like the difference
between reference semantics and value semantics is an unimportant minor
point.
Generally, the definition has served its purpose well because it
indicates to some extent that a class should be preferred over a
struct except in circumstances where performance may be a concern.

Not for me. I generally prefer lightweight things unless I have a need
for the "heaviness" of the alternative. If I only knew the "structs are
lightweight classes" definition, I'd treat structs as the default. Good
job I know better, isn't it? Why bother with a short description if you
really need a longer one in order to understand the difference at all
in the first place? Why not just refer people to a more detailed
comparison?
The fact of the matter is structs and classes are related by blood

Care to put that in concrete terms?
and so, one is usually described within the context of the other.

It's fine to compare and contrast - but just using such a misleading
description is a really, really bad idea IMO.
Adjusting the literature to define otherwise is unappealing and fails
to take the lineage into account.

I'd prefer to use correct definitions than ones which take lineage into
account and then mislead people.
 
A

Alvin Bruney

Care to put that in concrete terms?
How about spec terms? Spec 1.7 C#
"Like classes, structs are data structures that can contain data members and
function members..."

The preceding implies similarity does it not? The fact that these are both
data structures shows some close family relation.

In fact, spec 11.3 goes so far as to delineate the difference between
structs and classes. Why? Because they are so similar that one may be
confused for the other hence the reason for the literature. (That is my
interpretation of spec 11.3)

I sincerely do not believe that anyone in here thinks that a struct is a
class or a type of class for that matter. I believe it to be a manner of
speaking only. I cannot argue against the technical merit for requiring a
clear distinction in terminology. However, my position is that it is not
sufficiently disturbing to warrant such drastic changes to the literature.
Since the majority of programmers who have a real need for structs do so
because they have a driving need. That need can only be filled firstly if
the programmer has a deep understanding of the difference.

I also fail to see the argument framed to include C++ programmer confusion.
After all, destructor syntax is horribly confusing to C++ programmers. But
we did survive this bout and Jon did not complain about the destructor
syntax either. So why now? We need to focus instead on structs and classes
inside C#. Those migrating to C# need to use an appropriate resource and be
guided accordingly while understanding that material presented in the
newsgroup is not guaranteed accurate and should be taken with a good dose of
salt and a pinch of asprin.
That's like saying that the following statements are "more friendly"
than the truth:
That is a horrible analogy. And for that matter, both sides have presented
horrible analogies that were self-serving. These analogies are without merit
because they were all carefully constructed to eluminate one side of the
argument - this one in particular is equally guilty.
I don't see what's "die-hard" about wanting to give a correct
impression, rather than misleading people.
Because it is tedious. It's the long way around the track when a shorter,
simpler explanation can work just as well for the majority of the 10 million
programmers out there.
I'd prefer to use correct definitions than ones which take lineage into
account and then mislead people.
I'd agree here with you but I believe that the struct vs class argument is
unique and should benefit from certain semantic liberties. Most people
understand classes but few understand structs well. There is merit in
explaining one in terms of the other. Notice this is the approach the
specification takes and then proceeds to differentiate the two. There's
nothing wrong with that. Or would you prefer to rewrite the specs?

--

________________________
Warm regards,
Alvin Bruney [MVP ASP.NET]

[Shameless Author plug]
Professional VSTO.NET - Wrox/Wiley
The O.W.C. Black Book with .NET
www.lulu.com/owc, Amazon
Blog: http://www.msmvps.com/blogs/alvin
 
B

Bruce Wood

As a rule, there is very rarely any reason to make it a struct if it contains objects, don't you say?

No... I have a struct (value type) that contains a reference to an
object (reference type). It's called a Measure, and it is a quantity
(value) coupled with a unit of measure (object instance). The trick is
that the object instance is immutable. This struct allows me to
represent, and perform mathematics and conversions on quantities that
have attached units of measure. So, for example, I can add "5 meters"
to "3 feet" and get a sensible answer.

It's freaky when a value type contains a reference to a changeable
object. That would be a bit weird, because then you would have values
that _could_ change simultaneously when you changed some aspect of one:
sort of hybrid reference and value semantics.

However, holding a reference to an immutable object instance doesn't
present any problems at all.
 
C

Chris Nahr

So far I have _never_ found a situation so compelling that I decided to
use a "struct" for efficiency reasons

I don't believe you. You may have very well never _defined_ your own
structs but you're using them all the time: Int32, Single, Double!

And you can only use them, and not have your program grind to a halt
(as would happen if it was written in Smalltalk) because these data
types are not implemented as regular classes, but as lightweight
variants of regular classes. Also known as structs. QED.
 
C

Chris Nahr

No, structs are not classes, not even lightweight classes, and they
don't behave like classes.

Funny, I could have sworn you could create instances of structs, and
put fields in them, and define methods on them...
 
B

Bill Butler

Chris Nahr said:
I don't believe you. You may have very well never _defined_ your own
structs but you're using them all the time: Int32, Single, Double!

And you can only use them, and not have your program grind to a halt
(as would happen if it was written in Smalltalk) because these data
types are not implemented as regular classes, but as lightweight
variants of regular classes. Also known as structs. QED.

Yes, Bruce already brought this point up in his original argument.
The problem is with the following statement:

"A struct is essentially a lightweight class."

That sentence has a different meaning to a C++ programmer.
So they hear that sentence and ASSUME that it is lightweight in the same
sense as in C++. So then they turn around and write a struct with 20
string members and wonder why it performs like a pig. After all they did
create the struct like this

MyStruct mystruct = new MyStruct()
Foo(mystruct);

This code LOOKS like it should have reference semantics.
Most C++ coders ARE surprised to learn that it doesn't.

So I say "Prefer classes over structs".
Classes are almost always more efficient than structs.
If your class falls into that small minority...go ahead, make it a
struct.
But do it with your eyes open to the gotchas.

Bill
 
J

Jon Skeet [C# MVP]

How about spec terms? Spec 1.7 C#
"Like classes, structs are data structures that can contain data members and
function members..."

The preceding implies similarity does it not?

Similarity, yes. "Related by blood"? That's certainly not backed up by
the spec.
The fact that these are both
data structures shows some close family relation.

Not particularly - partly because "family relation" isn't a well-
defined term in computer science. That's why I asked what you really
meant by it.
In fact, spec 11.3 goes so far as to delineate the difference between
structs and classes. Why? Because they are so similar that one may be
confused for the other hence the reason for the literature. (That is my
interpretation of spec 11.3)

They're certainly similar enough to warrant a comparison. They're not
similar enough to talk about one as being a lightweight or heavyweight
version of the other.
I sincerely do not believe that anyone in here thinks that a struct is a
class or a type of class for that matter. I believe it to be a manner of
speaking only. I cannot argue against the technical merit for requiring a
clear distinction in terminology. However, my position is that it is not
sufficiently disturbing to warrant such drastic changes to the literature.

What literature? I'm talking about people casually referring to structs
as "lightweight classes" as if this passed on any worthwhile
information. Instead, it leaves a misleading impression.
Since the majority of programmers who have a real need for structs do so
because they have a driving need. That need can only be filled firstly if
the programmer has a deep understanding of the difference.

Absolutely - and calling structs lightweight classes does *not* give
that deep understanding or even hint that deeper understanding is
required. People make decisions based solely on the fact that structs
have been described as lightweight classes. They shouldn't, but they
do. That's human nature.
I also fail to see the argument framed to include C++ programmer confusion.
After all, destructor syntax is horribly confusing to C++ programmers. But
we did survive this bout and Jon did not complain about the destructor
syntax either. So why now? We need to focus instead on structs and classes
inside C#. Those migrating to C# need to use an appropriate resource and be
guided accordingly while understanding that material presented in the
newsgroup is not guaranteed accurate and should be taken with a good dose of
salt and a pinch of asprin.

So you're saying that describing a struct as a lightweight class isn't
accurate, but that's okay because no-one should trust what's said on a
newsgroup anyway? Okay then - maybe I should start calling structs
"heavyweight classes" then. After all, it can't do any harm, can it?
That is a horrible analogy.

I don't think so. In all cases:
a) The "simplified" version tells a tiny part of the story
b) The tiny part of the story which is told distracts from the bigger
picture
c) People have been confused by the "simplified" version
And for that matter, both sides have presented
horrible analogies that were self-serving. These analogies are without merit
because they were all carefully constructed to eluminate one side of the
argument - this one in particular is equally guilty.

Can you refute any of the above points?
Because it is tedious. It's the long way around the track when a shorter,
simpler explanation can work just as well for the majority of the 10 million
programmers out there.

Except it doesn't. We've seen people be confused by calling structs
lightweight classes. Do you really want to contribute to confusion? I'm
not suggesting that you write a huge long explanation every time. I'm
suggesting that you find a resource which explains it properly, and
reference that instead.
I'd agree here with you but I believe that the struct vs class argument is
unique and should benefit from certain semantic liberties.

I don't believe it's unique, but I believe it's so important that it
absolutely *can't* benefit from semantic liberties. It's not that
complicated - it *gets* complicated when people take semantic liberties
so that when someone wants to find out the truth, they've got to
"unlearn" the myths they've heard first.
Most people understand classes but few understand structs well.

And the fact that people keep referring to structs as "lightweight
classes" is one of the contributing factors to that lack of
understanding.
There is merit in explaining one in terms of the other.

I've never disputed that.
Notice this is the approach the specification takes and then proceeds
to differentiate the two. There's nothing wrong with that. Or would
you prefer to rewrite the specs?

You seem to have created a straw man argument, as though I've been
arguing against comparing structs and classes. I never have. I've just
said that calling structs lightweight classes and leaving it at that
creates a misleading impression, and that's a bad thing to do. The
specs *don't* do that, of course - they give details, which is what
I've been arguing for the whole time.
 
J

Jon Skeet [C# MVP]

Chris Nahr said:
Funny, I could have sworn you could create instances of structs, and
put fields in them, and define methods on them...

There are similarities - but there are big differences too. Calling one
a lightweight version of the other gives a false impression as to how
similar they are.

I repeat: this description has confused people in the past. Many
people, in fact. Why continue using a description which has proved to
be confusing?
 
B

Bruce Wood

From my point of view, the answer to this whole "should we call structs
'lightweight classes'?" argument is this very newsgroup.

I haven't been here long... maybe a year or so. In that time, every two
weeks at most someone posts here asking, "Why not use structs all the
time, since they're more efficient?" (Where "more efficient" is, at
least in these posters' minds, equivalent to "lighter weight".) or "Why
doesn't my program work...? I'm using structs." (Invariably
incorrectly, as a result of thinking of them as "lightweight classes"
and nothing more.) In the last while we had two such questions within a
week. I have no statistics, but my impression is that it's one of the
FAQ's in this newsgroup.

Every time the problem is that the poster thought that structs were
just "classes-lite" and didn't understand that there was anything more
to know than that.

Do I believe that calling structs "lightweight classes" is utterly
without merit? No, I don't: the two-word definition does contain some
truth. However, in the context of all of this confusion (and there's
plenty of confusion out there)... where the number one misconception
about structs is that they are "classes lite" _and that's all they
are_... do I think that calling them "lightweight classes" is a
_helpful_ definition? No, I do not: it contributes to the already
rampant confusion.

Myself, I prefer another two-word definition: structs are "value
types". This at least gives newbies pause: "Hey, I don't know what that
means." Well, then it's time to do some digging and find out. The
problem with "lightweight classes" is that newbies say to themselves,
"Oh, I know what that means" when in fact they don't. I'd rather save
them the pain of finding out the hard way (like I did).
 
C

Chris Nahr

Now we're splitting hairs. You know what I meant.

Sure, but what you meant is unrelated to the question of calling
structs "lightweight classes" or pointing out their greater efficiency
as small data containers.

Even though you never saw a reason to create a _user-defined_ struct
for performance reasons, you're still constantly profiting from all
the _predefined_ structs that were created for performance reasons.
Your programs might well be unusably slow if not for those structs!
 

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

Top