Function calls

Steven Schveighoffer schveiguy at yahoo.com
Thu Jan 28 20:20:46 PST 2010


Andrei Alexandrescu Wrote:

> Michiel Helvensteijn wrote:
> > Andrei Alexandrescu wrote:
> > 
> >>>> foreach (line; stdin.byLine()) { ... }
> >>>>
> >>>> vs.
> >>>>
> >>>> foreach (line; stdin.byLine) { ... }
> >>>>
> >>>> How do I choose?
> >>> byLine is a property.  It is fetching a range on stdin.
> >>>
> >>> -Steve
> >> Damn. I was sure the answer will be different.
> > 
> > byLine() is a function. It changes the state of stdin. Calling it
> > consecutively will in general result in different return values. If there
> > were two guys: stdin.currentLine (property) and stdin.nextLine(), it would
> > be a different story.

No no no.  byLine returns a struct, it does not modify stdin.  Operating on the struct modifies stdin, but that is outside the call to the property getter.

Look at it this way (although this is not the only way to look at it), could byLine be a field inside stdin?  It could.  You could store a copy of what byLine returns inside stdin, and people could just access it.

> > A property should act very much like a field. The advantages of properties
> > are that they can be derived (not have a one-to-one relation with a storage
> > location) or can do some clever caching/memoizing/logging.
> 
> I agree, but I'll also note that I got contradictory opinions from 
> different supporters of @property. So now it looks all the more like a 
> judgment call, which is exactly what I was worried in the first place.

There are some cases that are judgement calls and some that are obvious.  byLine is obvious.

The difference is that the *author* is making the judgement call, not the *user*.  The difference is important, because when a user complains that your property is doing things a property shouldn't, and then you realize the "property" in question isn't even a property at all, your only solution (with the non-attributed system) is to tell the user not to use it that way.  There is no way to get him to stop, or to get other users to stop.  You have lost control over the semantic meaning of your function, even though you defined it and documented it.

And yes, this did actually happen to me.

> 
> > Omitting parentheses on an action just because you can is stupid. It
> > actually makes the language less readable and less predictable. And all
> > that for saving two keystrokes.
> 
> I found my code to be more readable and just as predictable with the 
> current rule. And it's not about two keystrokes, it's about persistent 
> and ubiquitous syntactic noise.
> 
> Gosh, @property does suck. I was afraid that'd be true.

This is your opinion when reading *your* code.  It doesn't suck if you value being able to read code written by *others*.

-Steve



More information about the Digitalmars-d mailing list