×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Metaprogramming Ruby

samzenpus posted more than 4 years ago | from the read-all-about-it dept.

Programming 84

scottl writes "Metaprogramming Ruby is the first book to give an in-depth and readable explanation of how dynamic programming works in Ruby. It is both readable and accurate and will be a valuable resource to intermediate and probably advanced Ruby programmers for some time to come." Keep reading for the rest of scottl's review.Metaprogramming Ruby is not a book for programmers new to Ruby, but would make an excellent follow on book to either Programming Ruby by Dave Thomas, Chad Fowler, and Andy Hunt or The Ruby Way by Hal Fulton. Both of the above books have chapters on or at least mention metaprogramming, but this is the first full length exposition of it. The book itself is broken into two sections and four appendices. In the first section, you (the reader) is paired with a more experienced programmer for a week, a chapter for each day, and as the week progresses you cover different topics in metaprogramming after being given tasks by your boss. The second section has two chapters on the design and implementation of ActiveRecord from Rails as well as a chapter on safe metaprogramming. Finally, there are three very useful appendices and a bibliography. One other note is that the book has the concept of "spells". Each concept as it is discussed in the book will have a spell associated with it. There will be a note in the sidebar with the name of the spell and the third appendix has the spells listed in alphabetical order, a short example of the spell, and a page number linking back to the extended discussion of the spell.

The first chapters are an informal introduction to metaprogramming where the reader, just starting a new job, is paired with Bill, an experienced developer, for a week. Each day is a chapter and each chapter covers a specific topic. The topics, as might be expected, increase in complexity as the week goes on. This more informal style actually works quite well. I had expected to be a bit irritated with the "schtick", but it turns out that Perrotta does not use it to excess. The topics covered here are Monday: The Object Model, Tuesday: Methods, Wednesday: Blocks, Thursday: Class Definitions, and Friday: Code That Writes Code.

Chapter 1 on Monday starts out with you meeting Bill, your experienced pair programmer, on a Monday morning and then goes straight into the Ruby object model. It discusses reopening classes to add additional methods including predefined Ruby classes such as String. It follows up with Monkey Patching (opening an existing class and redefining an existing method) and the pitfalls therein.

In Chapter 2, methods are examined. Perrotta goes over a problem with duplicated code and how to reduce this code by generating and calling code dynamically. He then moves to showing the same example using method_missing(), followed by adding a change to respond_to? to make sure the methods show up.

Wednesday's topic in Chapter 3 covers blocks, lambdas, and procs all of which are really just "callable objects". The chapter starts with a review of blocks. This is followed by a discussion of scopes and how to carry variables through scopes using blocks as closures. Perratto shows how to use instance_eval() to receive blocks and then use them to manipulate scopes. Next, converting blocks into "callable objects", lambdas and Procs, and then calling them later is covered. Finally, there's a short introduction to domain specific languages (DSL) using the the techniques from this chapter.

Chapter 4 or Thursday covers class definitions. A discussion of self and the current class open the chapter. There's also a section on singleton methods and eigenclasses. There are class instance variables, variables that belong to the class and not to a particular object. Examples of class macros, such as attr_reader, attr_writer, and attr_accessor, and how to write them are shown. Finally he covers around aliases where method names can be renamed and then redefined but the original is still available.

The final day of the week, Friday, Chapter 5, goes deep into Ruby metaprogramming with code that writes code. In this chapter, Perrotta shows how to implement an "attr_checked" attribute in a few different ways starting with a kernel method using eval and moving on to passing the validation attributes in a block. Then this gets moved to a class macro (from Chapter 4), and finally moving on to using a module with hooks. This last is a pattern that's seen in many Ruby projects including Rails and two I'm familiar with, Sequel and Ramaze.

The second section, Metaprogramming in Rails, consists of two chapters on ActiveRecord and a final chapter on metaprogramming safely. In the first two chapters, Perrotta takes a tour through

ActiveRecord, the Rails object relational mapper (ORM) and shows how ActiveRecord uses the tips and techniques from the previous chapters. The final chapter on safe metaprogramming discusses how to test metaprogramming and working around and with to make sure that monkey patching doesn't cause problems.

Finally, there are three appendices. The first shows common Ruby idioms that are seen pretty much in all Ruby code. They provide a good review, but I'm not sure how useful they really are for the audience that this book is aimed at. The second appendix is one DSLs. This is also a nice to have, but there's probably not enough to let you program a DSL if you don't have additional help from somewhere. The final appendix really is almost worth the price of the book. It contains a list of metaprogramming "spells". Each of the spells contains a short programming example as well as the page number with the longer explanation. This is incredibly useful when looking at code from any of the major frameworks (some mentioned above) and you don't understand a piece of it. Just by scanning through the spells you can often find a simple version of what you're looking at and then read a longer explanation.

All in all, this is one of the better, more readable programming books that I've read in a long while. Perrotta keeps it to around 250 pages including the appendices and it's packed full of useful information. As I noted above, this book is highly recommended as a second Ruby book. The presentation of metaprogramming is both enjoyable and useful and the book itself is well written.

You can purchase Metaprogramming Ruby from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

cancel ×
This is a preview of your comment

No Comment Title Entered

Anonymous Coward 1 minute ago

No Comment Entered

84 comments

Mac fags vs Ruby fags (-1, Flamebait)

Anonymous Coward | more than 4 years ago | (#31572782)

Who do you think spews more smug? Mac fags or ruby fags?

Hmm (1, Informative)

Anonymous Coward | more than 4 years ago | (#31572870)

I don't think most people give a crap about Ruby in general. Why not just use a programming language that does it right?

Re:Hmm (0)

Anonymous Coward | more than 4 years ago | (#31573038)

Is that you, Zed?

Re:Hmm (0)

Anonymous Coward | more than 4 years ago | (#31573260)

Speaking as an AC with authority on the subject, I say yes.

Re:Hmm (1)

Jane Q. Public (1010737) | more than 4 years ago | (#31580028)

Methinks I smell a Python aficianado.

(Whitespace? Really? Are you kidding?)

All I have to say is: being the fastest-growing programming language right now, Ruby must have something going for it.

Great book but... (0)

Anonymous Coward | more than 4 years ago | (#31572910)

the narrative style can drive you nuts.

Why, do they start typing in the subject.. (4, Funny)

AndrewNeo (979708) | more than 4 years ago | (#31573344)

and finish their sentence in the paragraph?

A: Because it breaks the flow of a message (2, Insightful)

DNS-and-BIND (461968) | more than 4 years ago | (#31579148)

Q: Why is starting a post in the "Subject" line incredibly annoying?

Re:Why, do they start typing in the subject.. (1)

junjie_1024 (1773516) | more than 4 years ago | (#31580448)

Hundreds of fabulous girls from forty different countries kicked off Teen Vogue’s annual Fashion University with Juicy Couture [juicycouturecvs.com].The launch cocktail party was hosted by Juicy at their 5th Ave Flagship in New York City. The energy in the line outside the party was an indication of what was to come and that excitement exploded when the Girls hit the store floor. They sipped on smoothies and pink lemonade, devoured treats from silver platters all as they experienced the colorful and insanely fun world of Juicy Couture bags [juicycouturecvs.com]. There was a DJ spinning and NY band Lion of Ido added to the frenzy. All had an amazing NY night, meeting new friends, taking photos, exchanging emails and of course a little retail therapy. Juicy [juicycouturecvs.com]was thrilled to be host to these up and coming trendsetters that will surely make up the next generation of fashion mavens. [juicycouturecvs.com]

juicy couture bags

juicy couture handbags

juicy couture wallets

juicy couture clothing

juicy couture Tracksuits

juicy couture hoodies

juicy couture Jewelry

juicy couture Necklace

juicy couture Earrings

juicy couture Bracelet

juicy couture shoes

juicy couture t-shirts

juicy couture coats

juicy couture swimwear

juicy couture Bikini

juicy couture set

Wholesale juicy couture

Re:Why, do they start typing in the subject.. (1)

c79106428 (1774496) | about 4 years ago | (#31594886)

new era hats [topbrandhats.com]

new era hats

new era caps

one industries hats

Rockstar Energy Hats

rockstar energy hats

monster energy hats

Red Bull Caps

The Hundreds Hats

nfl hats

Supreme Hats

DC Comics Hats DC Comics Hats[/url]

Not dynamic programming... (3, Informative)

TheCycoONE (913189) | more than 4 years ago | (#31572944)

The summary mentions dynamic programming; but this book contains nothing about dynamic programming. (A particular method suitable to problems with optimal substructure that can be used in a subset of cases where recursion can be used and typically generates results very quickly.)

The author, who I've seen speak, instead writes about "metaprogramming" which in my personal opinion is a silly catch phrase to sell talks and books when actually he's just talking about using some of the advanced functionality present in Ruby (and also JavaScript) to do things that would be done with macros or can't be done at all in traditional object oriented and procedural languages.

If you're buying this book thinking it contains some new breakthrough paradigm, and you're already familiar with the ins and outs of Ruby prepare to be disappointed. If your background is Java or C++ and you've just learned enough to get by until now it'll probably be an eye-opener.

Re:Not dynamic programming... (0)

Anonymous Coward | more than 4 years ago | (#31572988)

Agreed that the summary is inaccurate, as dynamic programming is a (mathematical) technique for finding optimum solutions to some problems.

Re:Not dynamic programming... (3, Informative)

Lunix Nutcase (1092239) | more than 4 years ago | (#31573076)

When the author said dynamic, he was using it to refer to the dynamic language [wikipedia.org] features of Ruby, not dynamic programming.

Re:Not dynamic programming... (0)

Anonymous Coward | more than 4 years ago | (#31574072)

When the author said dynamic, he was using it to refer to the dynamic language [wikipedia.org] features of Ruby, not dynamic programming.

Perhaps he shouldn't have used the phrase "dynamic programming", then.

These techniques are horrid for maintainability. (0)

Anonymous Coward | more than 4 years ago | (#31573112)

These "metaprogramming" techniques, regardless of whether they're done in Ruby or JavaScript or Lua or some other language, cause nothing but problems when it comes to maintainability.

Sure, they might help the programmer write the code in slightly less time, but then they make it damn near impossible to debug later on.

Errors are missed because they only happen in obscure cases at runtime, but would have otherwise been caught when using less-dynamic techniques. Even working code becomes unnecessarily complex, and really can only be understood by stepping through it, line by line, using a debugger.

When I catch my developers using these techniques, we have a nice little chat about writing maintainable code, and then their code gets reworked. Far too often, what small amount of time might be saved in the first place ends up being lost 50 or 100 times over while debugging. We don't play that game.

Re:These techniques are horrid for maintainability (1)

clampolo (1159617) | more than 4 years ago | (#31573406)

When I catch my developers using these techniques, we have a nice little chat about writing maintainable code, and then their code gets reworked.

God, nothing is more annoying than an opinionated boss that starts sticking his fingers in your code.

cause nothing but problems when it comes to maintainability

Yes, because it's much more maintainable to keep repeating the same code everywhere and having it scattered throughout the source than to use some metaprogramming to make a useful (and efficient) macro.

Re:These techniques are horrid for maintainability (1)

Lunix Nutcase (1092239) | more than 4 years ago | (#31573470)

Yes, because it's much more maintainable to keep repeating the same code everywhere and having it scattered throughout the source than to use some metaprogramming to make a useful (and efficient) macro.

Then extract the repeated code into another method. Much more maintainable than a macro.

Re:These techniques are horrid for maintainability (1)

clampolo (1159617) | more than 4 years ago | (#31573534)

I agree with you for most cases, which is why you only use metaprogramming in extreme cases. But sometimes speed or some other factor (maybe the code is just cleaner by adding a new language construct) and metaprogramming is the correct method.

Re:These techniques are horrid for maintainability (1)

the_lesser_gatsby (449262) | more than 4 years ago | (#31573906)

So can you give a example of an extreme case where metaprogramming (i.e. dynamically generating code) has an advantage over just using a good old-fashioned precompiled abstraction? (Does it really only work in extreme cases?)

Re:These techniques are horrid for maintainability (1)

bsDaemon (87307) | more than 4 years ago | (#31574216)

I think an example (I just started learning Ruby a few weeks ago, coming from Perl and C but I'm already in love with it) is when setting 'attr_accessor' in a class definition to automatically create getters and setters if you don't intend on doing anything fancy with regards to an attribute but don't want it accessed directly. Also, I think Rails pretty much relies on this as well, as is my understanding, but as I said, I've only had a brief association with the language.

Re:These techniques are horrid for maintainability (3, Informative)

GreyWolf3000 (468618) | more than 4 years ago | (#31575286)

ActiveRecord.  Let's say you have a database table called "products" with three fields, "name," "description," and "price."  This code:

class Product < ActiveRecord::Base
end

Instantiates a class called 'product' which is a subclass of ActiveRecord::Base (AR::Base).  As soon as the <i>act</i> of subclassing AR::Base, occurs, AR::Base has code that infers the name of the database table (in this case 'products') as the singular, lower case version of the subclass' name (Product).  Then, it reads the table 'products' from the database, and dynamically adds getters and setters for the name, description, and price attributes.

In addition, AR::Base knows how to respond to a lot of methods whose names aren't known until runtime.  Product.find_by_name("Table") will internally invoke "SELECT * FROM PRODUCTS WHERE name = 'Table'" and fetch a Product whose name, description, and price are reflected in the output of that SQL query.

Hence, you can do this on the Ruby console:

>> product = Product.find_by_name("Table")
>> puts product.name
"Table"
>> puts product.description
"This is a table (my description was living inside the database)"
>> puts product.price
$4.29

It's greatly simplified, but metaprogramming allows you to construct classes and objects who <i>present</i> behavior based on run time state.

You really have to dig in and use a language like Ruby for a while to see how powerful this is.  If you're worried about the lack of maintainability, then write good tests :)

Re:These techniques are horrid for maintainability (0)

Anonymous Coward | more than 4 years ago | (#31576122)

Hmm, I've always thought of metaprogramming as code that produces code, not dynamically interpolating objects in an ORM (as nifty as that might be).

C++ template classes are a Turing-complete meta-language that, to me, really sum up metaprogramming. See this very interesting and horrifying book: http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315 [amazon.com]

Re:These techniques are horrid for maintainability (1)

AlXtreme (223728) | more than 4 years ago | (#31581006)

It's greatly simplified, but metaprogramming allows you to construct classes and objects who present behavior based on run time state.

Your example doesn't seem like metaprogramming in the typical sence, I don't see anything special about it. But that might be due to excessive exposure to Python.

I suppose you could see any ORM layer as a form of metaprogramming [wikipedia.org] (as you're generating and executing SQL at runtime), but I'd argue that SQL isn't a programming language but rather a database language.

Thus this book isn't about metaprogramming, but "metadatabasing" (ugh).

Re:These techniques are horrid for maintainability (0)

Anonymous Coward | more than 3 years ago | (#31584408)

The book only uses ActiveRecord as one example of many. Please don't let a single example define an entire work. :/

Re:These techniques are horrid for maintainability (1)

GreyWolf3000 (468618) | more than 3 years ago | (#31591526)

The actual implementation of the functionality I described involves tons of calls to instance/module_eval, define_method, etc. that are available to every Ruby object which allow you to modify an object's methods at runtime.  The amount of code that is generated on-the-fly is both substantial and essential.  How can that not be metaprogramming?

Re:These techniques are horrid for maintainability (1)

elnyka (803306) | more than 3 years ago | (#31584826)

So can you give a example of an extreme case where metaprogramming (i.e. dynamically generating code) has an advantage over just using a good old-fashioned precompiled abstraction? (Does it really only work in extreme cases?)

Meta-programming can help when creating frameworks and platforms for a generalized audience (.ie. Rails WRT developers that want to develop apps following a specific architectural pattern). The variables of generality can be captured in *meta-patterns* (I just puked a little by typing that clique - useful, but still a clique).

Meta-programming should not be used for application-specific code where more traditional approaches should suffice.

In other words, if your team is developing a platform or a framework, then meta-programming is ok (perhaps necessary.)

For developing business-specific code, application-specific functionality, then yeah, I'd agree with the anonymous poster above in that I would not want them to be meta-hacking away instead of using less esoteric means, not unless it is something very specific and required (.ie. a meta-programming artifact expected by the underlying framework.)

Re:These techniques are horrid for maintainability (1)

K. S. Kyosuke (729550) | more than 4 years ago | (#31574358)

Then extract the repeated code into another method. Much more maintainable than a macro.

But this *is* a case of extracting repeated code into another method already.

Re:These techniques are horrid for maintainability (1, Insightful)

Anonymous Coward | more than 4 years ago | (#31573578)

God, nothing is more annoying than an opinionated boss that starts sticking his fingers in your code.

Except programmers who leave you with a mess once they're gone or do things in a way that is resistant to future changes, or don't follow your coding guidelines and produce code very different from your other programmers, or, ...... I could go on all day with good, valid reasons why a boss (or someone) should be doing code reviews.

You clearly haven't worked on any major projects or in a real development shop.

Re:These techniques are horrid for maintainability (1)

kirillian (1437647) | more than 4 years ago | (#31573938)

There are multiple kinds of development shops - i assume that you are referring to the kind of shop where you are given ample time (or at least sufficient time) to complete projects and where quality and few bugs are valued over having it done in a short period of time. There are other kinds of shops (like the one I've worked in for quite a while), where the management is less organized and goals include - get it done yesterday! Code tends to become a little less maintainable anyway in these types of situations...to the developers working on these types of projects, sometimes, well-documented macros and other such meta-programming aids become the only means of keeping the code-base they maintain organized for themselves under their time constraints. Unfortunately for management, the skilled programmers who are capable of succeeding in these types of environments tend to want to leave as they feel abused, overworked, and underpaid. Sadly, I think these kinds of shops are actually becoming more and more common. so, these techniques may, one day, even become almost the norm...

Re:These techniques are horrid for maintainability (1)

nextekcarl (1402899) | more than 4 years ago | (#31573820)

Boy am I glad I don't work for you. While metaprogramming certainly isn't right for every case, it is literally perfect for some. Best tool for the job, and all.

Re:These techniques are horrid for maintainability (1, Interesting)

Anonymous Coward | more than 4 years ago | (#31574460)

I'm glad you don't work for me, too.

We hired a Ruby guy once. He was the most immature "professional" I've ever had to deal with. He couldn't take any form of criticism, he was always "right", and couldn't work well with others at all.

Aside from his lack of interpersonal skills, his work was complete shit. Instead of just writing code to get it done, he'd insist on using every design pattern he could. 10-line functions became 50-class "frameworks" using every Ruby trick available.

We will NEVER hire a Ruby fellow like that again. We've had much better success hiring Perl and Python programmers, and having them learn Ruby on the job.

Re:These techniques are horrid for maintainability (1)

K-Mile (906254) | more than 4 years ago | (#31576354)

Why mention "Ruby" so explicitly? It appears that you just had bad luck hiring a overzealous developer not capable of writing good enough software precisely fit for the problem, with the best tools for the job.

You'll find these guys in every type of language or programming paradigm...

Re:These techniques are horrid for maintainability (1)

IAmGarethAdams (990037) | more than 4 years ago | (#31578714)

Right, but *this* book review is about a book about Ruby. So it's probably pretty suitable to talk about Ruby here.

If the book was about LISP then you'd probably see a lot more LISP discussion going on.

Re:These techniques are horrid for maintainability (5, Insightful)

SanityInAnarchy (655584) | more than 4 years ago | (#31574424)

These "metaprogramming" techniques, regardless of whether they're done in Ruby or JavaScript or Lua or some other language, cause nothing but problems when it comes to maintainability.

If done poorly, sure.

Sure, they might help the programmer write the code in slightly less time, but then they make it damn near impossible to debug later on.

Then your debugging tools suck, or the metaprogramming was abused. Banning it isn't like banning goto, it's like banning exception handling. Just because you can abuse it and ignore all errors doesn't mean you should never be able to intercept an exception.

Errors are missed because they only happen in obscure cases at runtime,

Can you give an example of such an "obscure" case?

I can see errors being missed because they only happen at runtime, but guess what? Them's the breaks. If you don't like it, you need to stop using Ruby or JavaScript or Lua, and stick to languages like Java, and make sure you always used checked exceptions, and you still won't catch all of them.

Runtime errors happen. That's what unit tests are for.

Even working code becomes unnecessarily complex,

Metaprogramming can make code much shorter, more readable, and more maintainable. If there's some additional complexity at runtime, so be it.

When I catch my developers using these techniques, we have a nice little chat about writing maintainable code, and then their code gets reworked.

If I was working for you (and I'm glad I'm not), I'd look forward to educating you on maintainability.

Let's look at an example: attr_accessor. It wouldn't be Ruby without it. You probably allow it, and it probably makes sense to you to allow it. It's also an example of metaprogramming -- while it's built into the language, and probably hand-tweaked in C for speed, it really makes much more sense once you understand that logically, attr_accessor itself could have been written using define_method.

How about another example: Any decent ORM. Either it's going to use metaprogramming to define your schema (like DataMapper does with 'property'), or it's going to use metaprogramming to expose your existing schema (like Rails does by reading your database). Tell me that's not more "maintainable" than hundreds of lines of XML config files.

Or I'll use a real-world example from the appengine-jruby project:

.
        def parent_property(name)
          define_method("#{name}_id") do
            k = key.first
            k.kind_of?(AppEngine::Datastore::Key) && k.parent
          end
 
          belongs_to_entity(name, false)
        end

And in actual code:

class Foo
...
  parent_property :parent
end

That defines a method 'parent_id' which returns the current id of the 'parent' of the current record (an Appengine-specific concept), and a method 'parent' which returns the actual entity of the parent. But notice I passed the symbol :parent explicitly -- I could just as easily have passed something else. (Why would I want to? Because maybe I need a parent method for some other reason, but I don't want to lose this functionality.)

Metaprogramming techniques can be abused. So can anything. Goto is harmful, but sometimes it's useful to be able to return a value from the middle of several nested loops without having to terminate each explicitly. Perl can look like line noise, and while it won't ever really be beautiful, you can write maintainable, readable Perl. You can write COBOL in any language.

So yes, it can be abused, but it's also an extremely powerful technique, and you are crippling your programmers and taking a hit on both productivity and maintainability by banning it.

Programmer trust and empowerment (1)

jonaskoelker (922170) | more than 4 years ago | (#31580344)

you are crippling your programmers and taking a hit on both productivity and maintainability by banning it.

I think it'd be a bit off-putting too. You're hired for a certain expertise, then you have that expertise overridden for arguably factually incorrect reasons.

I recently read an article about why video games are addictive (http://www.cracked.com/article_18461_5-creepy-ways-video-games-are-trying-to-get-you-addicted_p2.html); short story, they fill a void that would be much better filled by our jobs, if our jobs gave us (1) autonomy; (2) complexity and (3) feedback. It sounds like a good idea to not strip any of these away if it can be avoided.

Re:Programmer trust and empowerment (1)

SanityInAnarchy (655584) | more than 3 years ago | (#31585966)

That might help motivation... I'm not sure it would help actual productivity.

For example, I agree that people shouldn't micromanage programmers, and should examine the output based on how effective, readable, maintainable it is, not based on how well it conforms to the way things have been done in the past. On the other hand, coding standards are there for a reason -- not everything needs to be unit tested, but if you've got a new guy who just doesn't like writing tests, maybe even has some philosophical objections to them, that could be a problem.

I mean, it'd be nice if you could just give him a problem to solve on his own, but chances are, you're all working on a big system together, and his lack of tests affects everyone else's ability to work with the entire codebase, not just his part.

So it's not that I disagree with ever impinging on someone's autonomy, but I definitely disagree with doing it for the wrong reasons. In this case, it simply does not result in better code to ban metaprogramming, and if anything, will result in driving away the better programmers.

I'd say similar things about complexity. I like working on complex, intricate, and elegant systems, but in the real world, what's often needed is much more mundane. In fact, metaprogramming can make things much simpler, and that's a win. I don't think it's a huge problem for motivation, in that if you can solve the same problem with a tenth of the complexity in a tenth of the time, you can solve ten problems instead of just one, which is probably a lot more satisfying. (Imagine trying to defeat one huge insanely complex boss for an entire game -- not fun.)

In fact, that probably helps with feedback -- and I do agree, feedback is good.

You might have implied that with "if it can be avoided", but it can always be avoided -- the question is whether it leads to a better or worse result.

Re:Programmer trust and empowerment (1)

jonaskoelker (922170) | more than 3 years ago | (#31590550)

I'd say similar things about complexity.

I realize I have been unclear: the quote I gave was said (IIRC) by a psychologist, and psychologists talk weird.

In this case, the psychologese word "complex" translates (I think) into the enginereese phrase "non-trivial". As in the opposite of assembly line work, or data entry, or of "write the exact same program again". Programming is always complex/nontrivial---when done with a bare minimum of good architecture tools and people---because you never do the same thing twice.

Whoops. (1)

SanityInAnarchy (655584) | more than 3 years ago | (#31586046)

Tell me that's not more "maintainable" than hundreds of lines of XML config files.

Now that I think about it, those hundreds of lines of XML config files are going to have to be interpreted by something to turn them into method calls -- so again, it's going to result in metaprogramming, unless you define your schema again by repeating all those methods and properties inside your model source as method and property definitions.

Re:These techniques are horrid for maintainability (1)

K. S. Kyosuke (729550) | more than 4 years ago | (#31574710)

Sure, they might help the programmer write the code in slightly less time, but then they make it damn near impossible to debug later on. Errors are missed because they only happen in obscure cases at runtime, but would have otherwise been caught when using less-dynamic techniques. Even working code becomes unnecessarily complex, and really can only be understood by stepping through it, line by line, using a debugger.

I guess that when you're working with shitheads who don't know the limits of their competency, you're screwed anyway. No matter what language is involved, they always creep up. I once noted an apparently incompetent programmer - that is incompetent in general as a programmer - who, despite this fact, never forgot to remark that he "absolutely loves C++ templates and tries to do anything with them". You can imagine the results. Java incompetents will probably abuse threads. Good programmers know that there are both safe tools in their language meant to be used daily, and powerful, but attention requiring tools to solve difficult problems when they arise. Sane people don't just go about abusing Lisp macros, Forth parsing words and Java reflection "because they can".

Re:Not dynamic programming... (1)

bunratty (545641) | more than 4 years ago | (#31573194)

If it's at all like Higher-Order Perl [plover.com], it certainly isn't some new breakthrough paradigm. It's LISP re-invented. I hope the author understands LISP (or better yet, Scheme) so he doesn't re-invent it poorly.

Re:Not dynamic programming... (1)

thms (1339227) | more than 4 years ago | (#31573348)

The summary mentions dynamic programming; but this book contains nothing about dynamic programming. (A particular method suitable to problems with optimal substructure that can be used in a subset of cases where recursion can be used and typically generates results very quickly.)

Yes, "calling code dynamically" is not the classic dynamic programming approach: Think of Pascal's triangle [wikipedia.org], each field is the sum of it's two predecessor in the previous row. You could calculate such a field by calling a recursive function, as parent suggests, but that is very inefficient: Consider the first two calls, to the top-left and top-right. These then do another call, and they overlap (rhombus-like): The top-right of the left with the top-left of the right. Here you could re-use the result if you had cached it, but since you start from the bottom you can't do that. And the redundancies become worse and worse the higher you go up.

So a dynamic programming approach is to start from the top and remember the result for a row, then start the next one. It is used where recursion might describe the problem properly, but makes it's implementation inefficient. Doing long Levenshtein distance calculations (transforming one string into another with a minimum of steps) is done in this way as well, resulting in O(n^2) runtime instead of, err, something like O(2^n) runtime IIRC because you have to do a recursive call for an insertion, a deletion or a replacement, i.e. 3 calls, while navigating through all possible character substitution paths in the string1 vs string2 matrix.

Re:Not dynamic programming... (2, Insightful)

shutdown -p now (807394) | more than 4 years ago | (#31573466)

The author, who I've seen speak, instead writes about "metaprogramming" which in my personal opinion is a silly catch phrase to sell talks and books when actually he's just talking about using some of the advanced functionality present in Ruby (and also JavaScript) to do things that would be done with macros or can't be done at all in traditional object oriented and procedural languages.

"Metaprogramming" [wikipedia.org] is an old term with a well-established definition, and if simplified to C/C++ audience, that definition would by and large look like "things that are done with macros". So I'm not sure what your problem is. So far as I can see, he is using the term correctly.

Re:Not dynamic programming... (0)

Anonymous Coward | more than 4 years ago | (#31574050)

What Ruby usually "metaprogramming" is typically hardly even that. Sticking methods on base classes is not metaprogramming. Metaprogramming is writing programs that produce or manupulate programs. Stuff like template programming in C++ for example, or program-transforming lisp macros, or the weird CPS-transformation stuff Seaside does for Smalltalk.

But hey whatever sells a book. And because it's about Ruby, it automatically is better than all that old busted corporate crap like using static types or following actually modular design.

Re:Not dynamic programming... (2, Informative)

JanneM (7445) | more than 4 years ago | (#31576560)

"dynamic programming" is an overloaded term in the English language. All natural languages have many such terms. Sometimes the meanings are related, sometimes they are completely different. When you have learned a meaning of a term, do not assume that is the sole correct meaning. You risk sounding like a pedant or a fool as a result.

Re:Not dynamic programming... (1)

daver00 (1336845) | more than 4 years ago | (#31576738)

The 'programming' in dynamic programming does not refer to writing computer programs, it is a branch of mathematics that grew out of the original convex optimization problems. Dantzig was a military 'programmer' in the 40s, the simplex algorithm was developed as a solution to problems that could be posed as a linear objective function with linear constraints. Programming in this sense was a word used by the military to describe how operations would be organised. Dynamic programming is an extension of linear programming and refers to mathematics, not computer code.

know your audience (2, Funny)

Lord Ender (156273) | more than 4 years ago | (#31572962)

valuable resource ... for some time to come.

These are some carefully-chosen words. Ruby is evolving faster than any other language, it seems. You blink your eyes and the XML parser you were using is out-of-favor; everyone has switched to the new one which really is much improved. This can be frustrating in that you must work to keep up with the Ruby world, but all these changes really to seem to be bringing the best of the best ideas to the surface.

Combine this rapid change with Ruby's metaprogramming ability and you see a programming language ecosystem in which evolution is sure to favor that little OO language from Japan...

Re:know your audience (-1, Troll)

Anonymous Coward | more than 4 years ago | (#31573030)

And yet it's still dog slow and Ruby on Rails still gulps down dog penises by the truckload.

Re:know your audience (1)

Lord Ender (156273) | more than 4 years ago | (#31573128)

While I can't speak to Rails (never used it) or to dog penises, I can say that the newest version of Ruby (1.9) is much faster than the previous versions. Its performance is similar to that of python or perl, and it outperforms these similar languages in some benchmarks. It was the slowest of the mainstream dynamic languages, but that is no longer the case.

Re:know your audience (1)

tweek (18111) | more than 4 years ago | (#31573224)

And to some degree, while Rails is the poster child for the power of Ruby it's also an albatross around its neck. It sucks in that regard and I love Ruby.

Re:know your audience (1, Informative)

Anonymous Coward | more than 4 years ago | (#31573398)

Its performance is similar to that of python or perl, and it outperforms these similar languages in some benchmarks.

I have put the key word of your quote, benchmarks, in bold.

Whatever benchmarks you've seen, they're probably useless. They don't apply to the real world even in the slightest.

We had to endure the same crap with Java years back. Java advocates would bring out some microbenchmarks showing "huge" performance wins over C and C++. Then we'd deploy some real world Java applications, and they'd be as slow as molasses, and require significant hardware upgrades just to run sort of shitty, rather than full-out complete shitty.

Now we see the Ruby community doing the same thing. Instead of just admitting that their platform is slow, they try to play these mind games with those of us who have real work to get done.

The only thing slower that Java and slower than Ruby is JRuby, which combines the slowness and overhead of both platforms into one of the worst programming environments I've dealt with in years (including far too many years writing COBOL, FORTRAN and PL/1 code).

Re:know your audience (1)

Lord Ender (156273) | more than 4 years ago | (#31573812)

Perhaps you didn't read what I wrote, Mr. Coward. The performance of Ruby 1.9 is what is improved. I am not referring to JRuby, or Rails, or Java, or whatever else you imagined. I really was talking about the latest version of Ruby, the programming language.

Reading comprehension is important.

Re:know your audience (1)

elnyka (803306) | more than 3 years ago | (#31584870)

Perhaps you didn't read what I wrote, Mr. Coward. The performance of Ruby 1.9 is what is improved. I am not referring to JRuby, or Rails, or Java, or whatever else you imagined. I really was talking about the latest version of Ruby, the programming language.

Reading comprehension is important.

Dude, you forgot that this is /. - we don't need reading comprehension, we have straw man frameworks and patterns and meta-patterns for that!!

Re:know your audience (-1, Troll)

Anonymous Coward | more than 4 years ago | (#31573142)

And anonymous trolls on Slashdot still make outrageous, baseless statements.

The more things change, the more they stay the same...

Use a real programming language, nubtard (-1, Troll)

Anonymous Coward | more than 4 years ago | (#31573382)

Aww, did I hurt the whittle feelings of a Ruby script writer? And yes, you are a script writer and not a programmer. Have fun with your little, kiddy, toy language while the real men do real programming.

Re:Use a real programming language, nubtard (0)

Anonymous Coward | more than 4 years ago | (#31573518)

When did programming become something that is "manly"? How does sitting at a computer bashing out code (Or more likely in your case, copy/pasting code) constitute being manly in any sense of the word?

Go be a lumberjack/pirate and then we can talk manly, boy.

Re:Use a real programming language, nubtard (-1, Flamebait)

Anonymous Coward | more than 4 years ago | (#31573520)

drive a Hummer, do you?

Re:Use a real programming language, nubtard (-1, Flamebait)

Anonymous Coward | more than 4 years ago | (#31573892)

Nope, I don't have a small penis that I need to compensate for. Maybe you should go buy one? From what I hear, even CmdrTaco's famed micropeen looks like a behemoth next to your's.

Re:Use a real programming language, nubtard (0)

Anonymous Coward | more than 4 years ago | (#31573904)

How else would be compensate for his unusually small penis?

Re:Use a real programming language, nubtard (1)

LOLLinux (1682094) | more than 4 years ago | (#31573982)

That's easy. Put it next to your penis. Everyone looks like Mandingo in comparison to you.

Re:Use a real programming language, nubtard (-1, Flamebait)

Anonymous Coward | more than 4 years ago | (#31574048)

Excellent - a thoroughly well worded, meticulously cited and incontrovertibly supported argument.

Ass.

The ecosystem is, not the language. (1)

Peter Cooper (660482) | more than 4 years ago | (#31574956)

Ruby's ecosystem evolves very quickly, sure, but the underlying language doesn't. Ruby written 10 years ago isn't significantly different to that written now. It's the libraries that are being used that have changed, but Perl has become susceptible to that in the last few years too (consider Perl5i and all the Perl 6-isms that are entering Perl 5).

FYI (1)

tweek (18111) | more than 4 years ago | (#31573252)

Pragprog has an AWESOME book coming out that I can't wait to see reviewed called "SQL Antipatterns". Check out the sample chapter on selecting a random row from the database. Freaking brilliant stuff.

Re:FYI (0)

Anonymous Coward | more than 4 years ago | (#31574518)

Pragprog has an AWESOME book coming out that I can't wait to see reviewed called "SQL Antipatterns".

I bought the beta PDF, but haven't read it all the way through, I mostly skipped to the part about trees and learned a lot about algorithms I had never even thought of to replace ye olde adjacency list (i.e. foo.parent_id) that works well until you want multiple levels or you need to know how many descendants node X has.

It's generally easy to read, and for most of the cases it looks like enough description and/or code is given to figure out how to replace your antipattern with the "right way" of doing things. It generally works to remain platform neutral but does have sections that say "in Oracle or PostgreSQL you can do this, in MySQL you can do that" especially in the descriptions of antipatterns.

Some of the stuff discussed aren't really antipatterns, they're just wrong. For instance, one of the subsections is about what happens when you try to aggregate several different loosely-associated tables at once, for instance SELECT a.name, SUM(b.value), SUM(c.value) where b and a are linked and c and a are linked, but there's no guarantee of a relationship between b and c (say, for instance, a=customer, b=invoice, and c=support calls and you wanted to know for each customer how much they've paid you and how long you've spent on the phone with them, when you aren't charging them for support calls).

Smalltalk and LISP for the History Major (3, Insightful)

Anonymous Coward | more than 4 years ago | (#31573714)

I develop in Ruby more than I'd like now and here's what I've seen as a past and present programmer who's used Java, C#, PHP, Perl, Smalltalk, LISP, C++, C, Python, Lua, and Visual Basic amongst others on real projects. Generally, I prefer Ruby to most languages, but only because it reminds me of other languages I'd yet still rather work with instead of Ruby ironically.

It's good to see Ruby improve and gain popularity, but like so many other languages lately (C#, Java, etc.), it seems to want to imitate Smalltalk poorly. Rather I'd like to see Ruby library authors, language devs, and framework zealots pay a little more attention to what is already out there. It reminds me of high school when you hang out with that friend who thinks whenever they discover something for the first time, they must have invented it. Ruby on Rails unfortunately gives the language a lot of bad press and needs to turn down the idiot volume.

Ruby also seems to have some diarrhea of the programming language where it wants to mix paradigms from so many other languages. It is like the kid who can't make up its mind. Even when it tries to emulate, it does it poorly, for example with hashes as hacks on named parameters in Obj C and Smalltalk (and .NET 4 now). This leads to wildly inconsistent libraries, methodologies, etc. Are you Perl? Are you Python? Are you CL or Haskell? I love a lot of things from all the languages I work with, but at some point you need focus, direction, and a firm point of view. This is one reason I love Smalltalk and Common Lisp. The two are wildly different in many ways, but share a strong stance of what is acceptable and useful in the language. In other words, these languages are well designed and have a good crap filter.

Ruby comes off amateurish at best in comparison and makes me feel like I'm working with the new web 3.0 PHP crowd. It's really sad because I love a good language or two, but it's just dumb to try to accomplish such lofty tasks without proper knowledge, leadership, and vision. When you think about it, you have to be kind of an asshole to want to create a new language with all that we have out there. It'd be one thing if it was so radically different as that would represent revolution, but Ruby is so derivative that I often wonder what value added. I tell myself when people do something like this, it must be curiosity + the inner nerd, but that still does not make it ok in my mind. What I wouldn't give if those same people would learn to actually understand and grasp more established languages in Smalltalk and Lisp, or hell even C++. It's not that I fear change, it's just that there's something to be said for experience and well tested languages that have gone through the growing pains already for better or worse. If there was something truly different, that made even functional programming seem trite, then I'd definitely hop on it to learn if nothing else, but Ruby isn't like that.

Finally, I have a problem in the fact that Ruby is not defined in itself. There's a lot of discussion about this if you google so I won't go into it, but historically, strong languages are able to do this because the internal mechanisms are fast enough and adequately expressive to allow for this. It is definitely a strength of a language if it can be built from the ground up in itself due to elegant design. Smalltalk is probably the best example of this, but owes a lot to earlier effort. Why can't Ruby do the same (too late)?

Generally, I am rather happy people are discovering Ruby. It allows me to keep certain languages like Lisp and Smalltalk largely my secret. While people build glorified Microsoft Access apps and then later are let down by scalability, performance, inconsistencies, lack of proper internationalization support, deployment tools, stability, etc., I'm happily being 10x more productive in my languages of choice. Unfortunately the world is a cruel place and employers love jumping on the bandwagon. I had the pleasure of seeing this with Java, where everyone thought it was thor's magic unicorn wand made of skittles. We had to convert a 10-year old Smalltalk system that had experienced only downtime once in its entire existence to Java. There was no point in this exercise, no net gain. A few years later, we got everything working but the system was far more complex, slower, and really was 0 net gain. We ended up porting it back again to Smalltalk and it runs to this day beautifully. It has nothing to do with the language, but rather the process and buzz. I see the same ridiculousness around Ruby.

So to all you Ruby'ers out there....I hope you enjoy it. I ask you to not get stuck in your existing paradigms because it is just that much like php or java to make you feel comfortable. Learn something new and pick the right language for the task. Don't trust the buzz and instead, branch out and learn some new paradigms as it will help you the next time reality forces you to dive in to some client's old PHP mess. In the end, it's the programmer, not the language and sadly, most people suck at programming period.

And Good job improving Ruby, the 1980s (or even 50s) welcomes you!

Re:Smalltalk and LISP for the History Major (1)

cowdung (702933) | more than 4 years ago | (#31574168)

Very true. Smalltalk is a better Ruby than Ruby.. Ruby is still clunky by comparison.

What we need is to create a new language called.. hmm.. Diamond.. that works like this:

object.message

(instead of ST's: object message)

then you can pass parameters like so:

object.message(key1:value, key2:value)
(instead of ST's: object key1:value key2:value)

etc..

Ie.. just redefine the syntax so nobody can tell that its just ST (because people fear ST).

The problem w/ST was that it was ahead of its time. In some respects it is still ahead of THIS time!

Re:Smalltalk and LISP for the History Major (1)

abigor (540274) | more than 4 years ago | (#31576350)

then you can pass parameters like so:

object.message(key1:value, key2:value)

This exists already - it is called Python.

Smalltalk never caught on largely because of fragmentation in its various implemented versions, and because it's not file-based. Rather, you modify an image, which is too weird and unwieldy for most people.

Re:Smalltalk and LISP for the History Major (1)

MichaelSmith (789609) | more than 4 years ago | (#31577466)

then you can pass parameters like so:

object.message(key1:value, key2:value)

This exists already - it is called Python.

And Ada.

Re:Smalltalk and LISP for the History Major (1)

Brian Feldman (350) | more than 4 years ago | (#31574774)

-1 Troll

Writing a wall of text doesn't

Re:Smalltalk and LISP for the History Major (1, Interesting)

Anonymous Coward | more than 4 years ago | (#31575016)

Care to elaborate? I don't even understand what your comment means.

I use Ruby every single day. I can't think of another language that for instance forces me to write C extensions to makeup for broken or slow parts of the language. I can't think of a language used at this level that can't support internationalization properly in this day and age. It's threading model is to put it lightly, abysmal. There are no great editors or deployment tools. The language itself cannot even fully support any sort of intellisense type feature for developer productivity because of its dynamic nature and lack of something akin to a Smalltalk VM. It can't parse things easier than lisp. And back to the topic, its meta programming facilities are actually unnecessary in many languages because the design and nature makes them a bad design decision (and make no mistake, Smalltalk in particular has a hefty meta layer, which is partially what confuses and scares most devs).

An opinion with some basic facts is not trolling. I'd like to see Ruby improve and lose the aforementioned dog penis taste, but facts are facts. Look at all the changes in Ruby from 1.0 to 1.9. From a purely computer science point of view, I don't see how you can view any of that as a troll.

Can you tell me a reason why Ruby should not learn from its predecessors? Can you tell me one thing Ruby does "better" than its predecessors? While language wars are largely subjective, the mechanics of a language are hard to ignore. As much as I hate certain languages, they are clear, consistent, and have a direction, opinion, and clear goal. Ruby is quickly becoming the king of the "me too" approach.

Here's also some food for thought...why is one of the current fastest Ruby implementations modeled exactly off a Smalltalk style VM (see maglev). Frankly, I'd rather use C# even most days because even Microsoft gets it more than the Ruby people.

Re:Smalltalk and LISP for the History Major (1)

metamatic (202216) | more than 4 years ago | (#31576190)

Ruby also seems to have some diarrhea of the programming language where it wants to mix paradigms from so many other languages.

You make it sound like that's a bad thing.

I prefer multi-paradigm languages because they let me pick the paradigm that best suits the problem.

Re:Smalltalk and LISP for the History Major (1, Interesting)

Anonymous Coward | more than 4 years ago | (#31576296)

Ruby wasn't intended to be an "enterprise ready" language or anything like taking over the world and become popular whatsoever (the Rails guys are solely responsible for Ruby notoriety). Ruby is about the fun in programming, a hobby. Ruby supports all of the programming paradigms it can because it makes it more fun, nothing more, nothing less. You can write extremely perl-ish code in Ruby, you can write purely procedural code too even if the underlying mechanism is OO, you can write Smalltalk-ish code using all of its object facilities and the hash hack you mentioned to act like named parameters and so on. It's not acting in a professional and serious manner, and I don't think people should use Ruby in production-ready code but it's a little fun language that can be made to fit your mind, instead of fitting your mind to a straight-jacket. Don't diss it because the Rails people have been bullshitting their way into selling a novelty language to ignorant sheeps, the creator of Ruby, Matz, never tried to "sell" his language and make it the new buzzword of the tubes.

Re:Smalltalk and LISP for the History Major (2, Insightful)

Endymion (12816) | more than 4 years ago | (#31576672)

Ruby has its (serious) faults, but the multi-paradigm nature of it is not one of them. It's probably the main reason I like the language. Yes, it's not perfect in any given programming style, but the mix of styles is a huge convenience. It's nice to be able to use LISP-like features at times, but still be able to bank out quick, traditional imperative-style code when it's appropriate.

This isn't to say they shouldn't take more from Smalltalk and LISP. Those rough edges are just slightly bad enough to bet in the way. I have high hopes that these problems will be fixed in the future, though.

What's particularly nice about Ruby, over the theoretically nicer LISP/Smalltalk/etc, is that Ruby is actually used fairly often...

Most invisibly used language: lisp? (1)

jonaskoelker (922170) | more than 4 years ago | (#31580370)

What's particularly nice about Ruby, over the theoretically nicer LISP/Smalltalk/etc, is that Ruby is actually used fairly often...

Every move-to-column you make
Every gdb-point you break
Every file you save
Every font-lock-keyword you say
I'll be ru-u-unning you

From the Song of Emacs

Re:Smalltalk and LISP for the History Major (1)

soliptic (665417) | more than 3 years ago | (#31590426)

As someone who is not an experienced programmer in all those languages, merely someone who has dabbled in a handful of them and read about programming much more than he's actually done it... Well, in the abstract, your argument is enticing, convincing even. However there is one glaring counterargument which stands out to even a peon like me, which you have apparently not addressed. It's this:

When you think about it, you have to be kind of an asshole to want to create a new language with all that we have out there. It'd be one thing if it was so radically different as that would represent revolution, but Ruby is so derivative that I often wonder what value added.

If Smalltalk Already Did It (Better)®, and Smalltalk has been around for x decades, then how come Ruby has come into widespread use in a way that Smalltalk never managed in all that time?

I don't pretend to know the answer to that. I just think whatever the answer is, there's your answer to what value Ruby added.

If your answer is merely "hype and marketing, -sneer-" then I'm afraid you immediately lose credibility in my eyes. For one thing, perhaps I'm naive but I'd like to think there has to be more to it than that. (It's not like developers make a habit of choosing their stack based on lifestyle ads in colour supplements.) For another, it's not an answer anyway, because there was nothing stopping Smalltalk advocates employing the same hype and marketing.

fu0ck... (-1, Troll)

Anonymous Coward | more than 4 years ago | (#31573890)

are 7He important

6do7l (-1, Offtopic)

Anonymous Coward | more than 4 years ago | (#31575456)

Software lawyers sImilarly 6risly
Check for New Comments
Slashdot Account

Need an Account?

Forgot your password?

Don't worry, we never post anything without your permission.

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>
Sign up for Slashdot Newsletters
Create a Slashdot Account

Loading...