Coding: Fleeting Thoughts

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
Flumble
Yes Man
Posts: 1990
Joined: Sun Aug 05, 2012 9:35 pm UTC

Re: Coding: Fleeting Thoughts

Postby Flumble » Fri Nov 20, 2015 4:44 pm UTC

Does OOP entail mutable state? Everywhere I look, languages that advertise OOP are imperative ones.
Sure, most functional languages have type classes that allow you to declare behaviour (and have instances define and overload that behaviour) and types can have records, but I haven't heard anyone calling that OOP. No, the buzzword in functional land is reactive programming (as far as I can tell).

User avatar
ahammel
My Little Cabbage
Posts: 2135
Joined: Mon Jan 30, 2012 12:46 am UTC
Location: Vancouver BC
Contact:

Re: Coding: Fleeting Thoughts

Postby ahammel » Fri Nov 20, 2015 5:31 pm UTC

Flumble wrote:Does OOP entail mutable state? Everywhere I look, languages that advertise OOP are imperative ones.
Erlang may be a counterexample.

Common Lisp has a pretty sophisticated object system as well.
He/Him/His/Alex
God damn these electric sex pants!

lalop
Posts: 210
Joined: Mon May 23, 2011 5:29 pm UTC

Re: Coding: Fleeting Thoughts

Postby lalop » Fri Nov 20, 2015 6:04 pm UTC

From viewtopic.php?p=3483288#p3483288:
Kit. wrote:There is no point in "immutable OOP" as the whole idea of OOP is to split the total program state into the islands of nearly-independent micro-states to make program state modifications as local as possible.


ahammel wrote:Erlang may be a counterexample.

Are Erlang's "objects" immutable, though, is what I think Kit's point is. If they are, then it's hard to see why we should be passing messages between them.

DaveInsurgent
Posts: 207
Joined: Thu May 19, 2011 4:28 pm UTC
Location: Waterloo, Ontario

Re: Coding: Fleeting Thoughts

Postby DaveInsurgent » Fri Nov 20, 2015 6:37 pm UTC

Flumble wrote:Does OOP entail mutable state? Everywhere I look, languages that advertise OOP are imperative ones.
Sure, most functional languages have type classes that allow you to declare behaviour (and have instances define and overload that behaviour) and types can have records, but I haven't heard anyone calling that OOP. No, the buzzword in functional land is reactive programming (as far as I can tell).


I think "most" OOP is just crap meant to enable ivory tower consultants to peddle more books to mediocre developers wanting to hone their 'craft' by which I mean learn new ways to produce boring, bloated boilerplate code (sorry, "patterns") in some kind of bizarre fetishism around the ceremony of writing code, not actually programming or performing computation.

In "most" OOP, objects are closures that you can pass around :/

#not-all-oop

commodorejohn
Posts: 1044
Joined: Thu Dec 10, 2009 6:21 pm UTC
Location: Placerville, CA
Contact:

Re: Coding: Fleeting Thoughts

Postby commodorejohn » Fri Nov 20, 2015 6:58 pm UTC

DaveInsurgent wrote:I think "most" OOP is just crap meant to enable ivory tower consultants to peddle more books to mediocre developers wanting to hone their 'craft' by which I mean learn new ways to produce boring, bloated boilerplate code (sorry, "patterns") in some kind of bizarre fetishism around the ceremony of writing code, not actually programming or performing computation.

Careful, if they know you know they'll be coming for you...
"'Legacy code' often differs from its suggested alternative by actually working and scaling."
- Bjarne Stroustrup
www.commodorejohn.com - in case you were wondering, which you probably weren't.

User avatar
ahammel
My Little Cabbage
Posts: 2135
Joined: Mon Jan 30, 2012 12:46 am UTC
Location: Vancouver BC
Contact:

Re: Coding: Fleeting Thoughts

Postby ahammel » Sat Nov 21, 2015 7:37 pm UTC

lalop wrote:
ahammel wrote:Erlang may be a counterexample.

Are Erlang's "objects" immutable, though, is what I think Kit's point is. If they are, then it's hard to see why we should be passing messages between them.
"Objects" in Erlang (actually actors) mutate themselves by generating a new (immutable) private state object and recursing:

Code: Select all

loop(State) ->
  Msg = receive_message(),
  NewState = mutate(State,Msg),
  loop(NewState).
He/Him/His/Alex
God damn these electric sex pants!

troyp
Posts: 557
Joined: Thu May 22, 2008 9:20 pm UTC
Location: Lismore, NSW

Re: Coding: Fleeting Thoughts

Postby troyp » Wed Nov 25, 2015 10:18 pm UTC

I didn't know make would make an executable with no makefile! That's handy. Is that a built-in thing with GCC languages, or does it use some sort of global config/makefile?

EvanED
Posts: 4330
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Wed Nov 25, 2015 10:26 pm UTC

troyp wrote:I didn't know make would make an executable with no makefile! That's handy. Is that a built-in thing with GCC languages, or does it use some sort of global config/makefile?
It has builtin ("implicit") rules for many types of targets. If all it needs to know to build is those rules and to make a target it always knows all the source files by just the extension, then the Makefile itself is superfluous.

On an unrelated note, Google Maps if you have JS disabled is cute:

nojs.png

korona
Posts: 495
Joined: Sun Jul 04, 2010 8:40 pm UTC

Re: Coding: Fleeting Thoughts

Postby korona » Thu Nov 26, 2015 5:56 pm UTC

I never understood why anyone would want implicit rules. Just writing a simple "%.o: %.c:\n\tcc -c -o $@ $(CFLAGS) $<" rule is negligible overhead compared to maintaining the build system of a non-trivial program. But it is so easy to shoot yourself in the foot by triggering an implicit rule (and building with the wrong compiler, wrong flags or wrong source file) because some rule is missing or fails to match. Debugging such problems is often a PITA.

At least there should be a .IGNORE_ALL_IMPLICIT_RULES_IN_THIS_INVOCATION pseudo target.

User avatar
Yakk
Poster with most posts but no title.
Posts: 11077
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Yakk » Thu Nov 26, 2015 6:50 pm UTC

They exist to allow you to make things without having to understand makefile syntax.

I'd guess most invocations makefiles are not on build systems of non-trivial programs. Instead, they are toy makefiles for toy programs.

If the initial difficulty of setting up a makefile required writing "%.o: %.c:\n\tcc -c -o $@ $(CFLAGS) $<", fewer people would use make. Possibly your project wouldn't even use it.

The tools we use might have "ease of use" features that get in the way of advanced usage, but tools with only advanced usage abilities *die* by failing to reproduce users.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.

User avatar
Wildcard
Candlestick!
Posts: 251
Joined: Wed Jul 02, 2008 12:42 am UTC
Location: Outside of the box

Re: Coding: Fleeting Thoughts

Postby Wildcard » Sun Nov 29, 2015 8:02 am UTC

On a totally unrelated note, I have now learned bash, sed, and awk thoroughly and using them all the time. (Maybe they don't qualify as "coding" to some purists...but whatever.) Once I finish up learning to use git fully, I'll be diving into perl next.

And, I've decided to learn C. It won't be directly and immediately useful at my job (sysadmin) so it's not a priority; will be a while before I actually start. But would be interested for the best A-Z references/courses on it, preferably online references and free courses. :) Not just the "How do I get started?" beginner tutorials, but "Where can I go to actually inhale the entire language in one fell swoop?"

(Yakk, I'm particularly interested in your input, actually. Everyone's advice welcome, though.) =)
There's no such thing as a funny sig.

User avatar
Yakk
Poster with most posts but no title.
Posts: 11077
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Yakk » Sun Nov 29, 2015 1:34 pm UTC

I am at best middling at C. My instincts are wrong, as I use C++.

They share some syntax, but it is like the difference between UK and US politics.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.

User avatar
ucim
Posts: 6071
Joined: Fri Sep 28, 2012 3:23 pm UTC
Location: The One True Thread

Re: Coding: Fleeting Thoughts

Postby ucim » Sun Nov 29, 2015 3:33 pm UTC

Wildcard wrote: But would be interested for the best A-Z references/courses on it, preferably online references and free courses.
Not an A-Z course, but an extremely helpful reference, "C Programming - Just the FAQs". I have used it when I taught C online (on AOL). At the time I used "The Waite Group's C Primer Plus" as the main textbook; it was also pretty good.

"C Programming - Just the FAQs" is available free online; I also have bound copies left over from my teaching stint if you decide you like the book and want hard copy.

Jose
Order of the Sillies, Honoris Causam - bestowed by charlie_grumbles on NP 859 * OTTscar winner: Wordsmith - bestowed by yappobiscuts and the OTT on NP 1832 * Ecclesiastical Calendar of the Order of the Holy Contradiction * Please help addams if you can. She needs all of us.

User avatar
Jplus
Posts: 1709
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Sun Nov 29, 2015 9:45 pm UTC

@Wildcard

The C Programming Language by K&R is a very decent course.

Also: Bash, Sed and Awk, next Perl, after that C? You really went the old-fashioned Unix way. :)
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
ahammel
My Little Cabbage
Posts: 2135
Joined: Mon Jan 30, 2012 12:46 am UTC
Location: Vancouver BC
Contact:

Re: Coding: Fleeting Thoughts

Postby ahammel » Mon Nov 30, 2015 12:17 am UTC

Learn C the Hard Way, if you must.
He/Him/His/Alex
God damn these electric sex pants!

User avatar
PM 2Ring
Posts: 3624
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Mid north coast, NSW, Australia

Re: Coding: Fleeting Thoughts

Postby PM 2Ring » Mon Nov 30, 2015 8:13 am UTC

Wildcard wrote:On a totally unrelated note, I have now learned bash, sed, and awk thoroughly and using them all the time.

Nice. I hope you're quoting your bash parameter expansions (except when you do explicitly want word splitting etc). :) Just in case you don't know about it, here's a link to the Shellcheck shell script analyzer. It's not perfect, but it can certainly help you to make clean bash scripts.

IME, knowing bash without awk can lead to bad practices, like using the bash read command to process text files. Sure, it's possible to do such things with read, but it's generally not a good idea. read is designed to work with small amounts of text, primarily interactive user input, and it's very inefficient to use it for large slabs of text because it processes its input data bytes one at a time, making a system call for each one. For more info on this topic please see Why is using a shell loop to process text considered bad practice? on Stack Exchange Unix & Linux, especially the answer by Stéphane Chazelas (the man who found & fixed the bash Shellshock bug). FWIW, that site has some great experts on bash, awk, and sed, and well-written questions about scripts in those languages are always welcome there.

Even though I mostly write in Python these days I still use awk and sed frequently, when appropriate. For simple text substitutions sed is just so convenient. And although awk is a bit limited compared to Python it is very fast: for simple text processing tasks awk will nearly always be faster then Python. Although awk has great regex handling one thing I miss in awk that more modern languages have is the ability to call a function when doing regex substitutions.

Wildcard wrote:I'll be diving into perl next.


I guess knowing perl is handy if you need to be able to read existing perl scripts. But I think you'd find Python more enjoyable. :)


ahammel wrote:Learn C the Hard Way, if you must.

I hope that one's better than his Python book...

User avatar
phlip
Restorer of Worlds
Posts: 7550
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: Coding: Fleeting Thoughts

Postby phlip » Mon Nov 30, 2015 12:08 pm UTC

PM 2Ring wrote:(except when you do explicitly want word splitting etc)

Hint: You don't explicitly want word splitting. If you think you do, you probably still don't.

I don't think I've intentionally used word-splitting of a variable interpolation in bash since I learned how to use bash arrays...

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
Yakk
Poster with most posts but no title.
Posts: 11077
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Yakk » Mon Nov 30, 2015 1:15 pm UTC

PM 2Ring wrote:
Wildcard wrote:I'll be diving into perl next.


I guess knowing perl is handy if you need to be able to read existing perl scripts. But I think you'd find Python more enjoyable. :)

Don't be ridiculous. Perl is a write only language.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.

User avatar
ahammel
My Little Cabbage
Posts: 2135
Joined: Mon Jan 30, 2012 12:46 am UTC
Location: Vancouver BC
Contact:

Re: Coding: Fleeting Thoughts

Postby ahammel » Mon Nov 30, 2015 4:00 pm UTC

PM 2Ring wrote:
ahammel wrote:Learn C the Hard Way, if you must.

I hope that one's better than his Python book...
Ouch. Now I'm wondering what bad C habbits I've picked up. Maybe not that one, then.

Of course, vanilla C would not be my language of choice for writing much of anything except OpenSSL vulnerabilities.
He/Him/His/Alex
God damn these electric sex pants!

EvanED
Posts: 4330
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Mon Nov 30, 2015 4:08 pm UTC

PM 2Ring wrote:
ahammel wrote:Learn C the Hard Way, if you must.

I hope that one's better than his Python book...
"Exercise 2: Make Is Your Python Now"

I hate it already. :-) Plain make is a terrible build system for C/C++. Though maybe if you're willingly writing in plain C, you and make deserve each other. (Should I be over in religious wars?) :-)

korona
Posts: 495
Joined: Sun Jul 04, 2010 8:40 pm UTC

Re: Coding: Fleeting Thoughts

Postby korona » Mon Nov 30, 2015 10:46 pm UTC

What is bad about plain make? make is a beautiful program that often gets horribly abused by autotools. autotools are the real cancer. CMake, scons and friends may be easier to use but they are harder to customize.

EvanED
Posts: 4330
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Tue Dec 01, 2015 12:20 am UTC

korona wrote:What is bad about plain make? make is a beautiful program that often gets horribly abused by autotools. autotools are the real cancer. CMake, scons and friends may be easier to use but they are harder to customize.

Implicit dependencies. The solutions for dealing with "this .c file depends on these .h files" range from mediocre to terrible, and IMO the fact that it doesn't work out of the box is inexcusable when we have long had tools that actually work properly. (Or maybe it not working out of the box is fine, and it's just the choice to use when it doesn't work that is inexcusable.) I'm pretty often OK with using make for non-C projects that want a make-like tool, but when it's far easier to write a build script that doesn't work than it is to write one that does... here be dragons.

There are a large number of things that other tools do a lot better (deal properly with changes to the build script, deal with building on multiple platforms, etc.), but that's what disqualifies it from being a reasonable solution IMO.

Incidentally, I also dispute your statement that others are harder to customize. I don't have CMake experience, but SCons is way more customizable and extensible than make is. The one thing it's really missing is pattern rules, and while I think that is a marked deficiency you can get around it in 98% of cases with a glob and for loop, and there's also less need than in make's case. (In particular, you don't need a pattern rule for making an object file from a source file, unless you want to produce a bunch of object files as your end goal.)

Rysto
Posts: 1459
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: Coding: Fleeting Thoughts

Postby Rysto » Tue Dec 01, 2015 12:55 am UTC

I've written a large build infrastructure basically from the ground up with GNU Make, so I can enumerate it's limitations pretty well:

1) There is no way to specify that a single rule generates multiple files
2) There is no notion of namespacing or scoping. The only way to generate multiple scopes is to invoke make recursively, but that is a horrible solution that breaks make's key benefits.
3) It does not scale well to a large number of rules, which also pushes people towards recursive make
4) It's not possible to override the default behaviour for checking whether a target is older than its dependencies. I have hit situations where timestamps are insufficient for this task, and the only thing that I can do in these situations is to shrug my shoulders and tell people to make clean
5) I haven't ever seen any existing, freely available make infrastructures. Everybody seems to roll their own (or use *shudder* autotools). Rolling your own is a significant pain, and you're likely to end up with subtle bugs.
6) Because it's a declarative, in theory you tell it what it can do and it figures out what it actually needs to do. For the most part this works quite well, but make doesn't really try to optimize its task order under the assumption that any ordering of tasks (subject to your dependencies) will be equally efficient. There are times when this is untrue (e.g. some tasks take a really long time to complete -- ideally I'd like to be able to hint that make start those tasks early on in the build rather than leaving it until the end)


Fundamentally, I think that make has a problem that you see in a lot of Unix technologies that are still around from the 70s/80s: it's almost good enough, which makes it very difficult to displace. If it were obviously inferior then people could justify ripping it out and replacing it. You see similar problems with IPv4 and DNS.

EvanED
Posts: 4330
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Tue Dec 01, 2015 1:56 am UTC

Rysto wrote:4) It's not possible to override the default behaviour for checking whether a target is older than its dependencies. I have hit situations where timestamps are insufficient for this task, and the only thing that I can do in these situations is to shrug my shoulders and tell people to make clean
I've actually really come to like SCons's hashing-based dependency checking. (Or should I say, the default option, because you can customize it and it comes with a couple built-in ones you can use just by stating it. :-)) I don't know whether it's a net win or net loss in terms of build speed if you don't have a cache, but its real benefit comes from when you use it with the SCons cache -- it's perfect for that case, and the cache is a huge win. With make, you have to use something like ccache to get that, which lets make's notion of what needs to be rebuild differ from what ccache thinks needs to be rebuilt.

5) I haven't ever seen any existing, freely available make infrastructures. Everybody seems to roll their own (or use *shudder* autotools). Rolling your own is a significant pain, and you're likely to end up with subtle bugs.
Would you consider CMake to be a "make infrastructure"? It's a "makefile generator" as I'd describe it, but I'm not completely sure what you mean by that. I've got mixed impressions of CMake -- one of these days, I'd like to get the chance to actually use it for something and see what I think. The little I've looked into the CMakeList files haven't given me a great impression, but from the "here's a project I want to build, now let me build it" point of view I think it's my favorite C/C++ build tool.

6) Because it's a declarative, in theory you tell it what it can do and it figures out what it actually needs to do. For the most part this works quite well, but make doesn't really try to optimize its task order under the assumption that any ordering of tasks (subject to your dependencies) will be equally efficient. There are times when this is untrue (e.g. some tasks take a really long time to complete -- ideally I'd like to be able to hint that make start those tasks early on in the build rather than leaving it until the end)
This is something I'd love to see as well. My pie-in-the-sky SCons feature here would be for SCons to learn how much time each target takes over time. Learning fits the SCons model better than make because SCons is stateful anyway. (In one sense that's unfortunate, but it is also why SCons works as well as it does and how it lets it do many of the things that make it oh-so-better than make.)

I'd also like to see memory taken into account for parallel builds. -j is great for "I've got x cores, go build," but it fails if your build is memory-bound (yay C++ templates...) because you either have to micromanage multiple build invocations or let your processing be underutilized during much of the build. I'd love to see a -m or something where -j8 -m16G would run 8 processes, but if all children started taking more than 16 GB total, it would kill a child or two until the memory use drops and restart them later. (I actually started writing a wrapper job-server thing that would do that, but didn't get very far and it's very low on my priority list.)

User avatar
Wildcard
Candlestick!
Posts: 251
Joined: Wed Jul 02, 2008 12:42 am UTC
Location: Outside of the box

Re: Coding: Fleeting Thoughts

Postby Wildcard » Tue Dec 01, 2015 5:23 am UTC

Yakk wrote:I am at best middling at C. My instincts are wrong, as I use C++.

They share some syntax, but it is like the difference between UK and US politics.

Well okay then, thank you for answering. I definitely know that they're different; somehow I had the idea you mainly used C....

Jplus wrote:@Wildcard

The C Programming Language by K&R is a very decent course.
Thanks; I actually hadn't realized that book is online for free. In that case I'll *definitely* be using it; I've heard it referenced all over the place.

Also: Bash, Sed and Awk, next Perl, after that C? You really went the old-fashioned Unix way. :)
Yep. Old tools are often best. (And when not best, at least they don't change all the gorram time and make you relearn everything.) I learned a smattering of Java, but don't really like all the flowery syntax and hand-holding.

I also got about halfway through MIT's open courseware "Mathematics for Computer Science" and an appreciable chunk of Cormen's "Introduction to Algorithms" just for fun.... So I think I'm probably ready for *correctly* programming in C. (i.e. avoiding EBKAC.)

@PM 2Ring: Funny you should mention it. :) I've worked up to about 1200 rep at unix.stackexchange.com in the last couple months and practically live on there now. And I've linked to that answer (about the horror of 'while read' to process text) at least three times.

My response to Python is like Cueball's. "I dunno...dynamic typing? Whitespace?"
There's no such thing as a funny sig.

EvanED
Posts: 4330
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Tue Dec 01, 2015 7:56 am UTC

Wildcard wrote:Thanks; I actually hadn't realized that [K&R] is online for free. In that case I'll *definitely* be using it; I've heard it referenced all over the place.
It's not AFAIK... or, well, it probably is, but only pirated.

(Note that the link in the following post was to "Learn C the Hard Way".)

I learned a smattering of Java, but don't really like all the flowery syntax and hand-holding.
To be fair, Java is the poster child for making you type a lot of BS syntax. There are a lot of great language choices besides those two. I tend to recommend against C and for a high-level language like Python for a significant majority of people -- I think that learning to deal with everything that C makes you deal with is a distraction from learning to actually program -- but there's also something to be said for starting low down and building up instead of the other way around. If you've enjoyed your time with awk etc., it sounds like you might be one of the semi-rare people for whom I think C is a reasonable choice. (I'm also not sure how far along you are in your programming learning. It sounds like you have some experience but not a ton. If there is a general purpose language you could describe yourself as "proficient" at, than C is absolutely a great choice to learn.) Just be aware that, in many ways, the old tools have shortcomings out the wazoo and in many ways will make your life significantly more difficult.

My response to Python is like Cueball's. "I dunno...dynamic typing? Whitespace?"
Dynamic typing has a lot of benefits over static typing. A lot of drawbacks too, but there are a lot of very nice things that it enables. I also think there are a lot of things about Python that make it a great learning language that are at least somewhat independent of its dynamic-typed nature and just came along for the ride. As for the visceral reaction against whitespace sensitivity, I don't understand it. I've come to have a slight dislike of whitespace sensitivity, but that's mostly due to boring issues like making editor operations slightly more annoying and making it lossy if you transmit it via a poor channel that kills the indentation. Because if you treat your code in any other language in a way that leads it so that it's not indented to what would be Python's satisfaction... well, I hope I never have to work on your code. :-)
Last edited by EvanED on Tue Dec 01, 2015 8:37 am UTC, edited 1 time in total.

User avatar
PM 2Ring
Posts: 3624
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Mid north coast, NSW, Australia

Re: Coding: Fleeting Thoughts

Postby PM 2Ring » Tue Dec 01, 2015 8:18 am UTC

Wildcard wrote:
Jplus wrote:@Wildcard

The C Programming Language by K&R is a very decent course.
Thanks; I actually hadn't realized that book is online for free. In that case I'll *definitely* be using it; I've heard it referenced all over the place.

It's an excellent book, and even though I don't use C much these days I still keep my copy of K&R within arm's reach. However, C has changed a little since that book was published and some of the things they recommend are no longer considered best practice (eg, type-casting the return from malloc()). But you can't go far wrong with learning from it & using it as a reference. And being familiar with K&R gives you common ground with all the C old-timers because it was the definitive reference for C for such a long time.

Wildcard wrote:@PM 2Ring: Funny you should mention it. :) I've worked up to about 1200 rep at unix.stackexchange.com in the last couple months and practically live on there now. And I've linked to that answer (about the horror of 'while read' to process text) at least three times.

Rightio. I guess you have a different username on U&L... My participation on U&L is somewhat sporadic, I tend to spend most of my Stack Exchange time on SO, mostly in the Python tag, although I do look at Bash from time to time.
Image

Wildcard wrote:My response to Python is like Cueball's. "I dunno...dynamic typing? Whitespace?"

The whitespace thing kept me from learning Python for 3 or 4 years, but now I love it. Mostly. :) Languages that need braces (or other block-structuring markers) now look cluttered to me in comparison to Python. And you can't get those nasty errors that arise from correct indentation but incorrect braces. Also, because the language virtually enforces a uniform indentation style (and most Python programmers use 4 spaces per indentation level) it makes it a lot easier to read other people's code and to incorporate it into your own code.

However, I will admit that it makes it a PITA to do quick one-off things as one-liners in the command line, in contrast to bash or awk. Also, trying to debug newbie's Python code on Stack Overflow can get painful when they've screwed up their indentation during the process of pasting code into their question. Sometimes you can guess the correct indentation, but it's generally not wise to fix it for them, since you might accidentally edit the problem away.

As for dynamic typing, I was also concerned about that, coming from C, but I soon grew to appreciate it. Although Python has dynamic typing the way it works is rather different from most other languages that have dynamic typing because Python objects are strongly typed.

Python has a different data model to that of many traditional languages. In the traditional model you have variables which are are essentially named locations in memory that can hold a value (or a collection of values), with a type associated with that location that signifies how many bytes the value occupies and how to interpret those bytes. In Python's data model, everything is an object. The type information is essentially associated with the object itself, not with its location in RAM. A Python object may be bound to one or more names, and it's often convenient to call such names variables, but they really aren't like the variables of the traditional data model, and treating them as if they were can lead to confusion and bugs.

So, in a sense, it's a bit misleading to say that Python's variables are dynamically typed, because it really doesn't have those traditional style variables. A name is just a name, and you can bind it to any type of object as the need arises.

A common pattern in Python is to re-use the same name as you transform some data. Eg, you might start with a string of integer numeric values read from a text file. Let's say you bind that string to the name data. You then split data into a list of strings, binding that list to data because you don't need the single string any more, and by binding data to a new object the old object gets marked for deletion. You then loop over that list, converting each string into an integer object, so you now have a list of integers, which you (once again) bind to the name data. It's obvious to anyone reading the code that the data has simply undergone some straight-forward transformations, and so it's perfectly natural to refer to it by the same name. This pattern means that you don't have to come up with a plethora of names for what's essentially the same data in various stages of transformation, so the code's both easier to write and to read.

Sure, there are disadvantages in this approach, but most Pythonistas feel that the advantages outweigh the disadvantages. OTOH, recent versions of Python have added type hinting for function arguments, for those who want that facility, but that doesn't seem to be a hugely popular thing among the Python old guard.

Anyway, I guess that's enough ranting & raving about Python, for the time being. :)

User avatar
Wildcard
Candlestick!
Posts: 251
Joined: Wed Jul 02, 2008 12:42 am UTC
Location: Outside of the box

Re: Coding: Fleeting Thoughts

Postby Wildcard » Thu Dec 03, 2015 1:35 am UTC

EvanED wrote:
Wildcard wrote:Thanks; I actually hadn't realized that [K&R] is online for free. In that case I'll *definitely* be using it; I've heard it referenced all over the place.
It's not AFAIK... or, well, it probably is, but only pirated.

You tell me. It's on a Brazilian site so I have no idea of the legalities: http://www.ime.usp.br/~pf/Kernighan-Rit ... -Ebook.pdf

I tend to recommend against C and for a high-level language like Python for a significant majority of people -- I think that learning to deal with everything that C makes you deal with is a distraction from learning to actually program -- but there's also something to be said for starting low down and building up instead of the other way around. If you've enjoyed your time with awk etc., it sounds like you might be one of the semi-rare people for whom I think C is a reasonable choice. (I'm also not sure how far along you are in your programming learning. It sounds like you have some experience but not a ton. If there is a general purpose language you could describe yourself as "proficient" at, than C is absolutely a great choice to learn.)

I think I am one of the people who will enjoy C. We'll see. :) As far as high-level languages go, I think that perl will cover that pretty nicely. Perhaps I will eventually learn C++, but as I'm actually employed as a sysadmin, learning to code at all isn't directly pertinent to my immediate job.

I'm interested in what you consider to be "learning to actually program", though. Care to expand on that? (Do you mean things like designing and implementing algorithmic approaches to programming problems? Properly refactoring code for cleanness and reusability? Dealing with memory management...? Well, obviously not that last one, if you think C is a distraction from actually programming.)

Likewise, I'm not sure what would qualify as a "general purpose language". As far as compiled languages go (and disregarding Java's in-between status), I don't think I am proficient in any. But I understand precisely what bash is for and what it isn't for, and I can write efficient, clean, readable and maintainable code in bash or awk, and even write advanced code in sed (though it's impossible to describe sed as maintainable).

Understood about the Python stuff, by the way. I did only a tiny bit of perl about 8 years ago, before I had enough grounding in computer science in general to have a clue what I was doing, but the one thing I learned really well is perl regexes. I can read ridiculously long, obtuse regexes almost as fluently as I read English, and I've always wondered why people call short regexes (say 25 chars) "unreadable" or "line noise". So I suspect that even if I learned both Python and perl with extreme proficiency, I would still prefer perl.

Regarding indentation—I do use proper indentation for everything, except for short one-liners embedded in bash scripts.
There's no such thing as a funny sig.

EvanED
Posts: 4330
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Thu Dec 03, 2015 1:53 am UTC

Wildcard wrote:I think I am one of the people who will enjoy C. We'll see. :) As far as high-level languages go, I think that perl will cover that pretty nicely.
You have a weird sense of "nicely" ;-)

(OK, I'll try to do one post without any more snarky digs at various languages and tools. :-))

I'm interested in what you consider to be "learning to actually program", though. Care to expand on that? (Do you mean things like designing and implementing algorithmic approaches to programming problems? Properly refactoring code for cleanness and reusability? Dealing with memory management...? Well, obviously not that last one, if you think C is a distraction from actually programming.)
The hard part of learning programming, to me, is learning how to figure out how to decompose problems in to parts that you can express in a precise and correct way. It's conceiving of the weird edge cases you have to handle, learning how to figure out how you think through carrying out a task, etc.

The next level down is some of the things you name -- like how to structure code and such. But to some extent those are language-specific, or at least specific to the language class, and they don't help you if you don't learn the top level.

The next level down is how figure out how to express those things in your actual language of choice. This is things like the concrete data structure you choose, memory management, and stuff like that. This is all the stuff that C makes you actively think about and handle yourself that I assert is a distraction from learning the higher levels. (E.g. want a dictionary in C? Well, it doesn't provide one. Want a resizable vector? You're on your own. And you can't even write a type-generic container in a way that isn't pretty crappy.)

Likewise, I'm not sure what would qualify as a "general purpose language". As far as compiled languages go (and disregarding Java's in-between status), I don't think I am proficient in any. But I understand precisely what bash is for and what it isn't for, and I can write efficient, clean, readable and maintainable code in bash or awk, and even write advanced code in sed (though it's impossible to describe sed as maintainable).
I use it as a fairly broad but very imprecise term, though narrower than, say, "turing complete." If you could write most any kind of program in it (e.g. numeric programs, text processing, network servers, perhaps GUI programs though you could perhaps argue the necessity of this) and not be rather pulling your fingernails out, it probably qualifies. It wouldn't have to be the best choice at a particular task, and it may be relatively poor at some. It easily covers anything from C through Perl. Bash is borderline at best, and something like sed or awk is right out, even though they are technically Turing complete. (Or not so "technically" in the case of awk.)

Other people may disagree where the dividing line goes exactly, but that's what I'd say.

Understood about the Python stuff, by the way. I did only a tiny bit of perl about 8 years ago, before I had enough grounding in computer science in general to have a clue what I was doing, but the one thing I learned really well is perl regexes. I can read ridiculously long, obtuse regexes almost as fluently as I read English, and I've always wondered why people call short regexes (say 25 chars) "unreadable" or "line noise". So I suspect that even if I learned both Python and perl with extreme proficiency, I would still prefer perl.
Short regexes are usually pretty decent, but I think you have to agree that they are incredibly dense. (This isn't a good/bad judgement, to be clear; their denseness is part of their utility too.) I consider myself reasonably proficient at regexes, but it's not hard to write a single regex that would qualify as "short" that takes as much mental power to think through and understand as many entire 15-25 line functions.

That's still a win, of course, if it would take more than 15-25 lines to do the same thing the regex does. :-)

User avatar
ahammel
My Little Cabbage
Posts: 2135
Joined: Mon Jan 30, 2012 12:46 am UTC
Location: Vancouver BC
Contact:

Re: Coding: Fleeting Thoughts

Postby ahammel » Thu Dec 03, 2015 2:26 am UTC

Wildcard wrote:I think I am one of the people who will enjoy C. We'll see. :) As far as high-level languages go, I think that perl will cover that pretty nicely. Perhaps I will eventually learn C++, but as I'm actually employed as a sysadmin, learning to code at all isn't directly pertinent to my immediate job.
There's a great deal of demand for people who have both systems administration and Python or Ruby skills at the moment, FYI. My current work would murder for a few such employees.
He/Him/His/Alex
God damn these electric sex pants!

User avatar
PM 2Ring
Posts: 3624
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Mid north coast, NSW, Australia

Re: Coding: Fleeting Thoughts

Postby PM 2Ring » Thu Dec 03, 2015 12:09 pm UTC

Wildcard wrote:Understood about the Python stuff, by the way. I did only a tiny bit of perl about 8 years ago, before I had enough grounding in computer science in general to have a clue what I was doing, but the one thing I learned really well is perl regexes. I can read ridiculously long, obtuse regexes almost as fluently as I read English, and I've always wondered why people call short regexes (say 25 chars) "unreadable" or "line noise". So I suspect that even if I learned both Python and perl with extreme proficiency, I would still prefer perl.


Ok, I see the attraction for perl, then. Of course, you can still do regex stuff with Python, but you do it with standard module functions & objects; regex isn't an integrated feature of the core language, like it is with perl, awk, and sed. If you know regex in one language it's pretty easy to pick up in other languages, although there will often be minor variations in how you do character classes, and various extensions or shortcuts in the syntax that can make the regexes cleaner and easier to read, eg named groups, and the ability to put whitespace and comments into a regex. (I don't know perl, so I don't know what its full regex syntax is like. My regex knowledge comes from grep, bash, awk, sed, JavaScript, and Python).

My attitude to regex is that it's a great tool, but the density of regexes (especially when they don't have embedded comments) is more of a disadvantage that it is an advantage. Certainly, they are compact and succinct, so in some ways they can be easier to read than multiple lines of equivalent non-regex code. But that density does slow you down when you're reading code, even when you're fluent with regex, and it's easier to make mistakes when writing regexes than almost anything else in a program, although that can be ameliorated to a degree with the use of a regex analysis tool.

When I do anything complicated with regex I tend to do it in multiple stages rather than trying to write a single humongous regex that I won't be able to read in 6 months. When working with regex I always bear in mind Kernighan's Maxim:
Brian Kernighan wrote:Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?
"The Elements of Programming Style", 2nd edition, chapter 2

So in Python I tend to avoid regex in favour of simpler string-processing tools, unless the regex approach is relatively easy to read or it has a clear speed advantage in a program that needs the speed.

korona
Posts: 495
Joined: Sun Jul 04, 2010 8:40 pm UTC

Re: Coding: Fleeting Thoughts

Postby korona » Fri Dec 04, 2015 3:34 pm UTC

EvanED wrote:
korona wrote:What is bad about plain make? make is a beautiful program that often gets horribly abused by autotools. autotools are the real cancer. CMake, scons and friends may be easier to use but they are harder to customize.

Implicit dependencies. The solutions for dealing with "this .c file depends on these .h files" range from mediocre to terrible, and IMO the fact that it doesn't work out of the box is inexcusable when we have long had tools that actually work properly.

Implicit dependencies require an additional call to the C compiler after compiling the object file and a -include line. I wouldn't say that that is particularly terrible.

Rysto wrote:1) There is no way to specify that a single rule generates multiple files

There is a very simple workaround for this: Assume x.generated.h and x.generated.c are built by a single command. Create an empty x.generated.tag file (e.g. via touch), add the two rules "x.generated.h: x.generated.tag" and "x.generated.c: x.generated.tag" and build all three files in the recipe of x.generated.tag.

Rysto wrote:2) There is no notion of namespacing or scoping. The only way to generate multiple scopes is to invoke make recursively, but that is a horrible solution that breaks make's key benefits.

Define a variable $c that evaluates to the directory containing the makefile. Now you can prefix all variables by $c and use non-recursive makefiles. Recursive make is indeed a horrible solution. I agree that this is not a very good namespacing solution, but hey, at least its not worse than C. :D

Rysto wrote:3) It does not scale well to a large number of rules, which also pushes people towards recursive make

I cannot reproduce that. In fact switching to non-recursive make usually decreases build time (in projects with 100s of nested folders) because fewer processes need to run.

Rysto wrote:4) It's not possible to override the default behaviour for checking whether a target is older than its dependencies. I have hit situations where timestamps are insufficient for this task, and the only thing that I can do in these situations is to shrug my shoulders and tell people to make clean

Well, you could use a "update-sha1-on-change.sh" script to do that but I agree that this could be done better.

User avatar
Jplus
Posts: 1709
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Fri Dec 04, 2015 7:45 pm UTC

Wildcard wrote:I'm interested in what you consider to be "learning to actually program", though. Care to expand on that? (Do you mean things like designing and implementing algorithmic approaches to programming problems? Properly refactoring code for cleanness and reusability? Dealing with memory management...? Well, obviously not that last one, if you think C is a distraction from actually programming.)

Likewise, I'm not sure what would qualify as a "general purpose language". As far as compiled languages go (and disregarding Java's in-between status), I don't think I am proficient in any. But I understand precisely what bash is for and what it isn't for, and I can write efficient, clean, readable and maintainable code in bash or awk, and even write advanced code in sed (though it's impossible to describe sed as maintainable).

Understood about the Python stuff, by the way. I did only a tiny bit of perl about 8 years ago, before I had enough grounding in computer science in general to have a clue what I was doing, but the one thing I learned really well is perl regexes. I can read ridiculously long, obtuse regexes almost as fluently as I read English, and I've always wondered why people call short regexes (say 25 chars) "unreadable" or "line noise". So I suspect that even if I learned both Python and perl with extreme proficiency, I would still prefer perl.

From what you are saying here, my impression is that there is still a whole world waiting for you to be discovered. I'm not sure you actually want to know this, because you say programming is not your main interest as a sysadmin. But since you're asking what could be considered "learning to actually program", let me give you a few hints.

Firstly, you have seen only a narrow selection of concepts, abstractions and techniques that are applicable to programming. Examples of what you haven't seen (yet) include closures, coroutines, modules, auto-iconicity, object orientation (even though you've probably heard about that one), templates, continuations and event handling. Most of these concepts and techniques you'll only encounter if you learn a reasonably modern, feature-rich language such as Lisp, Haskell, C++, Python/Ruby or JavaScript/Lua (not an order of preference). All of the concepts I just mentioned are absent in C.

Secondly, you have seen only a narrow selection of problems that programming can be used for. It's not just all string processing and command invocation. There's networking, parallelism, writing a library that is useful for other people, defining tests to check the validity of your program, composing user interfaces, maintaining programs that consist of more than a couple of files (sometimes thousands), and many other things. Most of the techniques that you don't know about (yet) can be very helpful when you tackle one of those problems.

So these are the things EvanED (or me, or Yakk) is thinking about when he recommends against C in favour of some other language. Which doesn't mean you shouldn't learn C, by all means. I'm just explaining the sentiment. :)
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

heatsink
Posts: 86
Joined: Fri Jun 30, 2006 8:58 am UTC

Re: Coding: Fleeting Thoughts

Postby heatsink » Sat Dec 05, 2015 7:56 pm UTC

I want to run an action and notify another thread when it has completed, even if the action throws an exception. Kind of like this:

Code: Select all

try { return myAction.run(); }
finally { receiver.send(tag); }


C++ doesn’t have “finally”. RAII is the way to make sure that code runs on either normal or exceptional return. That is, you formulate the action as cleanup of a resource associated with an object:

Code: Select all

class WhenDone {
  Channel<Tag> &receiver;
  Tag tag;
public:
  WhenDone(Channel<Tag> &_receiver, Tag _tag) : receiver(_receiver), tag(_tag) {}
  ~WhenDone() { receiver.send(tag); }
} whenDone(receiver, tag);

return myAction.run();


The two important statements are in the reverse of their actual execution order, and the message send is hidden within a bunch of object-oriented distractions. C++’s insistence on RAII makes me unhappy.

heatsink
Posts: 86
Joined: Fri Jun 30, 2006 8:58 am UTC

Re: Coding: Fleeting Thoughts

Postby heatsink » Sat Dec 05, 2015 10:01 pm UTC

korona wrote:What is bad about plain make?


Everything is a string, which makes data structures and program structures hard to understand. Functions work by string substitution. To make data structures, you use formulaic global variable names so the location of the data you want can be computed by string substitution.

I've fought with this to write loops that create rules for each build target in a list. For example, a project may have multiple libraries or benchmarks that each has to be built. The code ends up looking like this:

Code: Select all

BENCHMARKS=hello io

hello_BIN=hello
hello_SOURCE_NAMES=hello

# ... other benchmarks ...

define benchmark_rules
$(1)_SOURCES=$(foreach f,$(1)_SOURCE_NAMES,$(1)/$f.c)

$($(1)/$(1)_BIN) : $($(1)_SOURCES)
        $(CC) $(CFLAGS) $$^ -o $$@

endef

$foreach(bmk,$(BENCHMARKS),$(eval benchmark_rules,$(bmk)))


In one of my projects, I used the shake library as a replacement for make. Working in a general-purpose programming language made it dramatically easier to construct build rules. I don't have enough experience with other build tools like CMake or SCons to say if they help.

User avatar
raudorn
Posts: 351
Joined: Mon Jun 13, 2011 11:59 am UTC

Re: Coding: Fleeting Thoughts

Postby raudorn » Sat Dec 05, 2015 10:16 pm UTC

So I've been thinking: In any given existing programming language, is there a way, possibly in another language, to express what a function should calculate without having to implement the function in the first place? Say I want to construct a function to calculate the square of a number. One way to describe this function is in standard mathematical notation: f(x) = x². Given that "standard mathematics" already "implements" exponentiation, I already did the work and would save nothing in terms of work to be done.

So it stands to reason that for any given minimal1 function f in language L, the best you can do is find some domain specific language G where the implementation is easier for the programmer. You can't cheat and invent a general language that defines what functions should calculate without also defining the implementation. Dang, there goes another attempt at automating my job to the point where I get paid for doing nothing.

Then again the vast majority of software I write calculates absolutely nothing and is just an exceedingly complicated data filter. I can't remember the last time I actually implemented an algorithm.

1 Meaning that you cannot further reduce the implementation for some arbitrary measurement of complexity. It's as simple/efficient/small as it gets.

EvanED
Posts: 4330
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Sat Dec 05, 2015 11:33 pm UTC

raudorn wrote:So I've been thinking: In any given existing programming language, is there a way, possibly in another language, to express what a function should calculate without having to implement the function in the first place?
What you're talking about is called program synthesis. There's active research in the area, but limited success so far. (Reasoning usefully about the semantics of a given program is undecidable in general and haaaaaard in practice.)

korona
Posts: 495
Joined: Sun Jul 04, 2010 8:40 pm UTC

Re: Coding: Fleeting Thoughts

Postby korona » Sun Dec 06, 2015 12:47 am UTC

heatsink wrote:
korona wrote:What is bad about plain make?


Everything is a string, which makes data structures and program structures hard to understand. Functions work by string substitution. To make data structures, you use formulaic global variable names so the location of the data you want can be computed by string substitution.

I've fought with this to write loops that create rules for each build target in a list. For example, a project may have multiple libraries or benchmarks that each has to be built. The code ends up looking like this:

Code: Select all

BENCHMARKS=hello io

hello_BIN=hello
hello_SOURCE_NAMES=hello

# ... other benchmarks ...

define benchmark_rules
$(1)_SOURCES=$(foreach f,$(1)_SOURCE_NAMES,$(1)/$f.c)

$($(1)/$(1)_BIN) : $($(1)_SOURCES)
        $(CC) $(CFLAGS) $$^ -o $$@

endef

$foreach(bmk,$(BENCHMARKS),$(eval benchmark_rules,$(bmk)))


In one of my projects, I used the shake library as a replacement for make. Working in a general-purpose programming language made it dramatically easier to construct build rules. I don't have enough experience with other build tools like CMake or SCons to say if they help.

To be honest that example doesn't look bad to me. But I've been using make for quite a bit of time and I understand that it may look cryptic to people that try to learn makefile syntax.

raudorn wrote:So I've been thinking: In any given existing programming language, is there a way, possibly in another language, to express what a function should calculate without having to implement the function in the first place? Say I want to construct a function to calculate the square of a number. One way to describe this function is in standard mathematical notation: f(x) = x². Given that "standard mathematics" already "implements" exponentiation, I already did the work and would save nothing in terms of work to be done.

There are two cases you can consider here:

  • You write a specification, the computer finds an algorithm that follows the specification. That's what Prolog does. I don't know about the state-of-the-art in this area but there are theoretical reasons (i.e. the problem is not decidable) that imply that this will never be possible in full generality.
  • You write a specification andan algorithm and prove that the algorithm obeys the specification. That is what Coq and similar languages do.

User avatar
raudorn
Posts: 351
Joined: Mon Jun 13, 2011 11:59 am UTC

Re: Coding: Fleeting Thoughts

Postby raudorn » Sun Dec 06, 2015 8:28 am UTC

EvanED wrote:What you're talking about is called program synthesis. There's active research in the area, but limited success so far. (Reasoning usefully about the semantics of a given program is undecidable in general and haaaaaard in practice.)

Yeah, I already expected that it's most likely hard and full of limits, otherwise we'd be doing it already. I'm just baffled by the unreasonable effectiveness of creating programs by writing lines in a text file. There were many crazy ideas of how we could be programming "in the future", but none of them turned out to be better. Why? I don't know.

korona wrote:
  • You write a specification, the computer finds an algorithm that follows the specification. That's what Prolog does. I don't know about the state-of-the-art in this area but there are theoretical reasons (i.e. the problem is not decidable) that imply that this will never be possible in full generality.
  • You write a specification andan algorithm and prove that the algorithm obeys the specification. That is what Coq and similar languages do.

I'll have to look into both, but thanks for providing search terms. Prolog seems exactly like what I was thinking about.

User avatar
Jplus
Posts: 1709
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Sun Dec 06, 2015 4:17 pm UTC

heatsink wrote:[...]
C++ doesn’t have “finally”. RAII is the way to make sure that code runs on either normal or exceptional return. That is, you formulate the action as cleanup of a resource associated with an object:

Code: Select all

class WhenDone {
  Channel<Tag> &receiver;
  Tag tag;
public:
  WhenDone(Channel<Tag> &_receiver, Tag _tag) : receiver(_receiver), tag(_tag) {}
  ~WhenDone() { receiver.send(tag); }
} whenDone(receiver, tag);

return myAction.run();

The two important statements are in the reverse of their actual execution order, and the message send is hidden within a bunch of object-oriented distractions. C++’s insistence on RAII makes me unhappy.

The good news is that you can write code that is much more general without it being object-oriented, and make your function shorter as well:

Code: Select all

template <class F>
struct finally_t {
    F f;       
    ~finally_t() { f(); }
};

template <class F>
finally_t<F> finally(F&& f) {
    return finally_t<F>{forward<F>(f)};
}

auto my_function(Channel<Tag> & receiver, Tag tag) {
    auto on_scope_exit = finally([&]{ receiver.send(tag); });
    return myAction.run();
}

To be honest, the statements are still in the wrong order, but hopefull the wording is sufficiently clear on the order in which things happen. I somewhat agree that a try/finally syntax would still be clearer, but I agree more with the language design philosophy of not introducing new language features if they aren't stricly necessary.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 5 guests