Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

How do you define "elegant"?

by Mutant (Priest)
on Aug 16, 2006 at 10:57 UTC ( #567653=perlmeditation: print w/replies, xml ) Need Help??

I was reading an old post by gargle, which links to the Jargon File. Naturally, I went to the entry for Perl, where I read:
Though Perl is very useful, it would be a stretch to describe it as pretty or elegant; people who like clean, spare design generally prefer Python.
I don't really like to participate in language wars, but I've always considered Perl to be one of the more elegant languages. Browsing to the Jargon File's definition of elegant, I found:
Combining simplicity, power, and a certain ineffable grace of design.
(Which, in my opinion, could be a Perl motto!)

Elegance in programming to me is about expressing actions (commands, statements, etc.) in a simple and coherent way. Perl's TIMTOWTDI-ness is (to me) the ideal tool for this.

One example for me in Perl is map. If I have a list of things, and I want to transform them all in some (fairly simple) way, it makes sense to do it all in one line. That is, I would define:
@foo = map { '%'.$_.'%' } @foo;
as more elegant than:
my @new_foo; foreach my $a_foo (@foo) { $a_foo = '%'.$a_foo.'%'; push @new_foo, $a_foo; } @foo = @new_foo;
I'm not just talking about reducing line count, however. If we were doing 10 different things to the items in @foo, and some of them depended on what the individual item was, it would be inelegant to use map, and more elegant to use foreach.

Still, I feel like there's much more to elegant code. There's certainly a "prettiness" factor. I sometimes just have a feeling that this is the "right" way to do it. And I can't really define it any more scientifically than that.

To me Perl allows us to be elegant, simply by offering us many different ways to do something. Of course, this also gives us the opportunity to be even less elegant than other languages, but that seems to be the trade-off with many things in Perl.

Replies are listed 'Best First'.
Re: How do you define "elegant"?
by derby (Abbot) on Aug 16, 2006 at 13:14 UTC

    You have to take the Jargon File with a bit of salt. While it's been around for a long time, the most recent/popular version has been edited/addedto/maintained by Eric Raymond (esr). While esr has contributed greatly to OSS (Cathedral and Bazaar), he was an earlier adopter of python and in his zeal to support python, he's been critical of perl.

    -derby

    Update: You can read esr's side here.

    Update again: From esr's article:

    ``More than one way to do it'' lent flavor and expressiveness at a small scale, but made it significantly harder to maintain consistent style across a wider code base. And many of the features that were later patched into Perl to address the complexity-control needs of bigger programs (objects, lexical scoping, ``use strict'', etc.) had a fragile, jerry-rigged feel about them.

    We need a term similar to truthiness for this ... I suggest robustiness. Doesn't matter what the benchmarks say ... since the code feels more robust then it is, in fact, more robust.

      I don't think that it will make one bit of difference but I contacted Eric about the entries for Perl and Python. My email boiled down to this; if the Jargon Files is supposed to be "a common heritage of the hacker culture" then he needs to loose the bias and personal opinions.
        I hope he takes your comment to heart. Here is the listing for Python:

        Python: /pi:´thon/ In the words of its author, “the other scripting language” (other than Perl, that is). Python's design is notably clean, elegant, and well thought through; it tends to attract the sort of programmers who find Perl grubby and exiguous. Some people revolt at its use of whitespace to define logical structure by indentation, objecting that this harks back to the horrible old fixed-field languages of the 1960s. Python's relationship with Perl is rather like the BSD community's relationship to Linux — it's the smaller party in a (usually friendly) rivalry, but the average quality of its developers is generally conceded to be rather higher than in the larger community it competes with. There's a Python resource page at http://www.python.org. See also Guido, BDFL.


        That is just a bit biased.
Re: How do you define "elegant"?
by holli (Monsignor) on Aug 16, 2006 at 11:24 UTC
    If we were doing 10 different things to the items in @foo, and some of them depended on what the individual item was, it would be inelegant to use map, and more elegant to use foreach.
    Why?
    @foo = map { super_complicated_transform ($_) } @foo; sub super_complicated_transform { #stuff goes here }
    Isn't that elegant, too?


    holli, /regexed monk/
      Well, I guess you've proven my point :)

      I was meaning map would be inelegant if you tried to cram all that logic into the the map block (foreach would be a much better way to lay that out). But obviously your way to do it is also elegant.

      It's fairly easy to give examples of what is/isn't elegant, but I find it harder to come up with an actual definition.
        Wikipedia says
        ... a computer program or algorithm is elegant if it uses a small amount of intuitive code to great effect.
        Pretty much hits the nail on the head, I think.


        holli, /regexed monk/
Re: How do you define "elegant"?
by BrowserUk (Pope) on Aug 17, 2006 at 00:23 UTC

    Elegance, in code, is when it's syntax reflects

    the semantics of the high level operation being performed,
    not the operational construction of how to perform it.

    A simple example, showing how syntax has evolved to do this (using half remembered FORTRAN & C).

    This

    IF not condition THEN GOTO 10 I = 1 GOT0 20 10 I = 2 20

    became this

    INTEGER II; IF condition THEN II = 1 ELSE II = 2 ENDIF

    became this

    int i = ( condition ) ? 1 : 2;

    I worked under C coding standards for a while where the trinary* operator was prohibited as "too advanced"; maintenance programmers wouldn't understand it.

    Another, Perlish, example is;

    { my $temp = $a[ $i ]; $a[ $i ] = $a[ $j ]; $a[ $j ] = $temp; }

    versus

    @a[ $i, $j ] = @a[ $j, $i ];

    The syntax clearly and concisely captures the operation without the extraneous noise of scope levels, temporary variables or the need to push code off into a subroutine somewhere else in the file; much less a different file.

    And a final example from an earlier extended discussion:

    sub isleap { my ($year) = @_; return 1 if (( $year % 400 ) == 0 ); # 400's are leap return 0 if (( $year % 100 ) == 0 ); # Other centuries are not return 1 if (( $year % 4 ) == 0 ); # All other 4's are leap return 0; # Everything else is not }

    This can also be written as

    not $year % 4 xor $year % 100 xor $year % 400;

    Yes, it forces the programmer to know what xor does and it's precedence; but I first used this expression in 1978/9 in Basic Plus, where xor was known as EQV. Encounter it once, look it up, use it and it will become a part of your lexicon.

    Elegance in fashion is often associated with things like "the simple black dress". A simple, unadorned black frock devoid of frills, bows or other extraneous accouterments that flatters it's wearer. Understated is the keyword. The secret of the simple black dress is in the hidden details. The precise cutting and expert tailoring that make it appear simply refined, whilst hiding the knowhow and detail that allow it to fit perfectly and so flatter.

    I would define elegance in code as concealed detail and hidden refinement. Concise syntax that completely captures the semantics of the high level operation whilst concealing it's mechanics.

    *Then trinary, now ternary--though I don't think that our kids ride terncycles; or play ternangles in school bands; or learn about ternceratops; or that the French flag is known as the terncolor; or that some gladiators fought with terndents; Nor do they eat ternfle for pudding :)


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Not sure about the precedence rules, but shouldn't there be a parenthesis around that?
      not($year % 4 xor $year % 100 xor $year % 400);
        I worked under C coding standards for a while where the trinary* operator was prohibited as "too advanced"; maintenance programmers wouldn't understand it.

      Your post made me laugh out loud. I had a similar situation -- I was in a group that had a new leader parachuted in, and he hated it when I used the ternary operator -- too fancy, he said. I was half a dozen years out of Waterloo by then .. I think he was trying to make up for the fact that he had a diploma in Tourism. Or something.

      Alex / talexb / Toronto

      "Groklaw is the open-source mentality applied to legal research" ~ Linus Torvalds

      Personally, I think the long isleap() form is clearer to the maintenance coder, since it will resemble the problem definitions they will find in non-code sources. It's more literate, even without the comments, just for the visual rhythm and the name of the sub. I would deem the one-liner more clever, but cleverness is not a programmers' virtue.

      I otherwise agree with your overall thrust.

      As for the ternary, python has long tried to resist the loud calls for its inclusion, on the same sort of grounds as your C programming team. I think last I heard it was adopted for 2.5, but I could be wrong. Sometimes even Guido must bend to pragmatism.

      --
      [ e d @ h a l l e y . c c ]

Re: How do you define "elegant"?
by tilly (Archbishop) on Aug 16, 2006 at 23:19 UTC
    Perl code can be and often is elegant. But the Perl language is not. Describing it as such is a sign of something wrong with the speaker. Likely possibilities include an overabundance of evangelical zeal, a misunderstanding of what elegance is, or a truly warped sense of aesthetics.

    Perl is simply too big with too much crammed in it and too many weird edge cases to be called elegant with a straight face. C is elegant. Scheme is elegant. Smalltalk is elegant. Perl is not.

    Note: elegant is not the same as good.

Re: How do you define "elegant"?
by tinita (Parson) on Aug 16, 2006 at 12:55 UTC
    i have just another example of elegance.

    before:

    my $num_count_expressions = @$count_expressions; my $count_expression_index; for($count_expression_index = 0; $count_expression_index < $num_count_expressions; ++$count_expression_index) {

    after:
    for my $count_expression_index (0..$#$count_expressions) {

      tinita,
      My response has nothing to do with elegance and you are quite right in your post. I do want to point out that the two snippets are not functionally equivalent.

      In the first inelegant snippet, the index var continues to exist beyond the for loop. In the second elegant snippet, it does not. This is because in Perl 5, an implicit block is defined. Last I heard, this will not be the case in Perl 6 and these two snippets would be functionally equivalent. I would have written it this way in Perl 6:

      for 0 .. $exprs.end -> $index { # ... }

      Cheers - L~R

Re: How do you define "elegant"?
by Maze (Sexton) on Aug 16, 2006 at 17:24 UTC

    I've always considered 'elegant' to be one of those subjective adjectives that indicates that a particular expression of some information (in this context) appeals to a sense of aesthetics. It is subjective since a sense of aesthetics is a element of that which understands/experiences an item, rather than the item it self, ergo something cannot be readily defined as elegant, rather experienced as elegant. (this is actually a simplification, since a trick for defining something without having a definite ascerifiable element that is of the item to identify it, is for a community to put that which is experienced as common within the community within a common definite category that can identify it so that they can define it as an element of their community, creating an outside definition for individuals based on the experiences of the community... my mind is simple really)

    on the subject of languages, there can be many aspects of languages that can tickle the aesthetic quality elegance, ease of understanding, ease of control, pretiness, simplicity, complexity. In fact in any given situation elegance could be a whole load of different things, in order for elegant to be meaningful for more than just a few people (see the little bit above, if you can understand it) requires there to be some kind of consensus on which aesthetics quintessentially 'elegant' (since it is undeniably to do with aesthetics)

    So the question is what can people agree on which means elegance?
    In my mind it's always been about representing in as clear as way possible, the information that it is trying to express, (so that there is no reliance on obscure or simply deceitful other pieces of information), and it fits ideally into the enviroment and role intended for it (a language fits the role of being a bridge between a human and a computer). This might include both the Truthiness factor and a Cleariness factor. In this case you could say think of it as the opposite of obfuscation.

    However methinks it's different when you're talking about a particular piece of code, since this also might involve a cleverness factor, so here Obfuscated code could be elegant if it was a clever piece of obfuscation, this might also add a pretiness factor for specific code.

    The key thing to remember about perl is that it is really about freedom - there is more than one way to do it and some may be more 'elegant' than others, and so with the freedom that perl gives the emphasis is about the individual code rather than just creating a certain implementation within the languages possibile directions. Thus the Obfuscation contests, and games of 'perl golf' since Cleverness is frequently the essence of perl elegance. Not to say that perl code can't be elegant by being a true form representation of the information it contains, or by being easy to understand and fufilling it's role as a bridge between human and computer - you can do it with perl, it's about that freedom!

    although for code in general, I feel elegance, being a subjective adjective, in the community ends up being a bit of a catch all term for a lot of aspects about good languages and good programming, it is difficult isn't it... I will have to think about this...

Re: How do you define "elegant"?
by apotheon (Deacon) on Aug 17, 2006 at 00:47 UTC

    elegant (adj.): characterized by a lack of the gratuitous

    That's a definition I've used before. It's not complete, but it's accurate, I think. To expand upon that notion somewhat, here's a quote from C.A.R. Hoare: "There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies."

    The following is copied from another source (it is entirely, however, my own words):

    There's a long tradition of referring to the elegance of a system. In the IT industry, this tends most commonly to be applied to source code, and it is generally accepted that the more elegant it is, the better. Elegance is differentiated from other superficially good things in a number of ways, including the common assumption that elegance goes deeper, while these other "good" things are only good within certain constraints.

    For instance, "clever" source code is good for its cleverness, but can be bad for maintainability — mostly because clever code is often difficult to understand. Cleverness also falls short because of a simple principle first articulated in an email signature of Brian Kernighan's: "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

    There's a fair bit more where that came from. I make reference to Perl golf, object oriented programming, and the relationship between concise code and elegant code. I even touch on the philosophical theory of aesthetics in the course of my rambling. Ultimately, the point of bringing it up here is my above definition of "elegant".

    print substr("Just another Perl hacker", 0, -2);
    - apotheon
    CopyWrite Chad Perrin

Re: How do you define "elegant"?
by GrandFather (Sage) on Aug 16, 2006 at 22:16 UTC

    I can't define "elegant", but I know it when I see it. :)

    Actually "cool" is often more applicable to Perl code than "elegant".


    DWIM is Perl's answer to Gödel
Re: How do you define "elegant"?
by ForgotPasswordAgain (Deacon) on Aug 17, 2006 at 08:33 UTC

    In whatever definition of "elegant" you come up with, I'm pretty sure that something which calls itself elegant is not. If something is elegant, it speaks for itself, it's something that people who care aesthetically will feel intuitively.

    I think it's for this reason that I've never warmed up to Catalyst.

    Catalyst - The Elegant MVC Web Application Framework

    Maybe "Practical" or "Useful", but elegant?

Re: How do you define "elegant"?
by Happy-the-monk (Abbot) on Aug 16, 2006 at 22:10 UTC

    Defining elegeant would be likely as successful as defining artful or equally worse, tasteful.

    It's a very subjective quality.
    Along the lines of the map example and tinita's post above, elegant programming style in Perl might be something lean and abbreviated yet fully operational that you would not yet have stamped as being ordinary or everyday practice yet.

    Cheers, Sören

Re: How do you define "elegant"?
by radiantmatrix (Parson) on Aug 18, 2006 at 20:10 UTC

    See, to me, elegance has a lot to do with the expressiveness of the language. I'll use your example:

    @foo = map { '%'.$_.'%' } @foo;

    That's pretty cool, but not particularly elegant. People familiar with map (which exists in other languages, too) will wonder why you're mapping a copy and then assigning it back to the original array when you could just:

    foreach (@foo) { $_ = '%'.$_.'%' }

    To me, that's more elegant because it's more expressive. It outright says "for each element in @foo, change it to have '%' on each side". Compare this to the map call, which says "perform this function - add '%' on either side of the parameter - on a copy of each element in @foo, assinging the result back to @foo". That's not elegant, it's complex.

    Of course, it's also just my opinion, and doesn't entirely detract from your premise. Things like $_ are one of the reasons I believe that Perl code can be so elegant.

    But, I disagree that Perl is inherently elegant. What makes Perl so wonderful, to my mind, is that Perl code truly reflects the programmer: if you're a bad programmer, your Perl code will be ugly; if you're good, then it will be beautiful.

    <radiant.matrix>
    A collection of thoughts and links from the minds of geeks
    The Code that can be seen is not the true Code
    I haven't found a problem yet that can't be solved by a well-placed trebuchet
Re: How do you define "elegant"?
by doom (Deacon) on Aug 17, 2006 at 18:24 UTC
    The question isn't how I define elegance, it's how they define it, and usually they're after something like "mathematical elegance". They want languages with an extremely small set of built-in features, a minimal set that can never-the-less be combined to create larger structures that can do all of the usual things.

    The trouble is that "Computer Scientists" are all mathematicians, who want to pretend that they're still doing mathematics, even when they're really off doing other things. Settling issues about language design would require delving into social psychology: you need "useability experts" to design experiments that get conducted on groups of volunteers. This could be done by "Computer Scientists" using the infinite supply of undergraduates flowing through the system, but it isn't because it doesn't sound like something Donald Knuth would do.

      This could be done by "Computer Scientists" using the infinite supply of undergraduates flowing through the system, but it isn't because it doesn't sound like something Donald Knuth would do.

      Hmmm... that would be nice start, but the resultswould indicate what the CS undergraduates themselves want (or think they want) in a programming language.

      I think I'd more interested in how the general populace likes to control their computer: their user interface, or "programming language"; or whatever you'ld like to call it. We have some UI design concepts, but in general, they're poorly studied and user complaints that programmers "don't think like end users" are common. A good start would be trying to get a solid grasp on what people tend to really want.

      Then we could try to design a language that most nicely bridges the gap between what the users actually want, and what the programmers can make the machine can do, and how those programmers like to program. No language I've seen has been designed from psychological principles with both the source creator and end user in mind; I'd be curious to see what the results could tell us, if anything...

Re: How do you define "elegant"?
by shmem (Chancellor) on Aug 18, 2006 at 12:32 UTC
    Elegance is inherent to the appearance of something, and to perceive it, knowledge of this something's being, craft and environment is necessary.

    Elegance is always individual in both subject and object. It is akin to humour - it is some "moisture" on the things which makes them shine. And it falls apart if you try to get a grip on it, like humour does when "explaining a joke".

    That said, elegance is not in a computer language nor a program, but in the attitude of a programmer towards the task (and/or solution) at hand.

    Comparing computer languanges or programs for their elegance and claiming objectivity whilst doing so is just silly.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: How do you define "elegant"?
by gloryhack (Deacon) on Aug 20, 2006 at 09:22 UTC
    Elegant is a woman who looks so good that you don't want to take her clothes off. Elegance in code is just like that.
Re: How do you define "elegant"?
by mreece (Friar) on Sep 10, 2006 at 03:14 UTC
    my @new_foo; foreach my $a_foo (@foo) { $a_foo = '%'.$a_foo.'%'; push @new_foo, $a_foo; } @foo = @new_foo;
    half of those lines are unnecessary!
    foreach my $a_foo (@foo) { $a_foo = '%'.$a_foo.'%'; }
    modifies each element of @foo in place without the extra @new_foo. i love map, but unless you need both lists when you are done, it's rarely the right tool. benchmark the above foreach against the map, and you should find it to be much faster.

    (elegance means ignoring such things when performance is unimportant..)

Re: How do you define "elegant"?
by zgrim (Friar) on Aug 23, 2006 at 01:59 UTC

    Ha ha, so there's ESR discrediting Perl in a public domain hacker-culture dictionary - that he happens to maintain - and the PerlMonks ... what ? have a long debate on what "elegance" means in regard to coding. :)
    _Of course_ he used an abstract fuzzy concept, there's no technical argument in such terms, only bias and illogic {sy,e}mpathy. :) Almost all languages have inherent dormant "elegance", it is within the power of their users whether it is used or not and to which extent. (I guess if the language is a real beastie, than the hacker must really have strong "elegance" foo, but that's not the case with Perl, is it? :) )

    I think Mutant's initial point is valid though. This kindof entries in the Jargon are sad, they seem to turn it into a hacker uncyclopedia. Maybe new maintainership is needed there.

    Just my ¢2.
    --
    perl -MLWP::Simple -e'print$_[rand(split(q.%%\n., get(q=http://cpan.org/misc/japh=)))]'
Re: How do you define "elegant"?
by spiritway (Vicar) on Aug 22, 2006 at 02:46 UTC

    Elegance is one of those elusive words and ideals that means different things to different people. To me, for instance, "elegance" means having a certain beauty; code that is effective, efficient, and somehow beyond that - that does something in a beautiful way (what's beauty?). There seems to be also a sense of the unexpected, as well. Some things are more or less obvious - you can anticipate the next step, see where you can drop some unneeded stuff; that's just workmanship (in my opinion). It's the difference between painting some water lilies, and Monet's Water Lilies. To me it's that feeling I sometimes get of "Yesss!" - just a sense of the rightness of the expression. Elegance seems to be like the US Supreme Court's definition of pornography. "Darned if I can define it, but I know it when I see it".

    When it comes to Perl, I personally think many of the idioms and one-liners are sheer artwork - and many are (to my view) quite elegant.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://567653]
Approved by marto
Front-paged by apotheon
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2018-02-25 22:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When it is dark outside I am happiest to see ...














    Results (315 votes). Check out past polls.

    Notices?