Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

The logical companion to the Which do you hate most question. What's your favorite syntax element in a programming language- what nicety to you like best? I'm sticking with the 'syntax' specification to avoid broader answers like "dynamic typing" or "is interpreted."

share|improve this question
1  
This seems like a good candidate for CW. – greyfade Sep 3 '10 at 3:24
1  
@Greyfade: Why's that? (consider meta.programmers.stackexchange.com/questions/8/…) – Fishtoaster Sep 12 '10 at 17:53
show 1 more comment

closed as not constructive by Aaronaught, Walter, Mark Trapp Jul 1 '11 at 17:42

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or specific expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, see the FAQ for guidance.

43 Answers

1 2
up vote 32 down vote accepted

The ternary operator (or for pedants, the conditional operator):

<boolean expression> ? expression result if true : expression result if false

Unfortunately, some languages make it difficult to use due to strict restrictions on what conversions can be performed in order to produce a consistent type from both possible outcomes. Nevertheless, it is a wonderful example of a language taking an extremely common pattern and providing a concise, readable means of representing it in code.

share|improve this answer
3  
True that. Of course, it's tempting to make some really stupidly complex lines out of that, especially when you start nesting them. :/ – Fishtoaster Sep 3 '10 at 2:27
1  
You guys might enjoy this then: programmers.stackexchange.com/questions/610/… – back2dos Sep 12 '10 at 17:19
6  
A true pedant might take issue with the word "pendants"... ;) – wrt Sep 15 '10 at 9:01
1  
@wrt: HA! Well, I guess that settles which camp I fall into... – Shog9 Sep 15 '10 at 11:25
1  
I love it as well, and yet many organizations I've worked for have banned its use because it is "too cryptic". – Marcel Lamothe Sep 15 '10 at 13:32
show 8 more comments

I'm still on the new language high for C#, so:

Properties

public bool IsCold { get; set; }

public bool IsHot
{
    get { return !IsCold };
    set { IsCold = !value };
}

A simple way to have the benefits of accessors (the ability to modify the implementation without changing the interface) and the benefits of public variables (brevity).

share|improve this answer
4  
Auto-properties are definitely useful in C#. However, other languages (e.g. Python) let you start with a regular field then change to a getter/setter without breaking compatibility. – Matthew Flaschen Sep 3 '10 at 2:50
3  
@Fish, yes, auto-properties work fine if you always remember to use them (there may be a slight overhead, but that's fine). But if you don't, for whatever reason, you may have to break compatibility. In Python, you don't have to do anything special initially. – Matthew Flaschen Sep 3 '10 at 3:13
show 8 more comments

In VB.NET I love the With statement which acts as a shortcut to an object's properties and methods within it's block. It saves typing, and I find it makes some code much more cleaner in the case of very long variable names:

With TransactionDialog.TransactionDatagridView.SelectedRows(0) 
    .Cells(0).Value = Something
    .Cells(0).Value = SomethingElse
    '...
    .Frozen = True
End With

versus:

TransactionDialog.TransactionDatagridView.SelectedRows(0) 
TransactionDialog.TransactionDatagridView.SelectedRows(0).Cells(0).Value = Something
TransactionDialog.TransactionDatagridView.SelectedRows(0).Cells(0).Value = SomethingElse
'...
TransactionDialog.TransactionDatagridView.SelectedRows(0).Frozen = True
share|improve this answer
3  
Couldn't you just assign TransactionDialog.TransactionDatagridView.SelectedRows(0) to a variable, like row, and then do rows.Cells(0).Value = Something? Seems like the same number of lines, a similar number of characters, and about the same readability without a special feature. – Fishtoaster Sep 3 '10 at 2:48
1  
@Fishtoaster: With has the added advantage of scoping access. In C++ or C#... and especially in C... you would probably just drop a block in and use a local variable for the alias. But VB is... awkward... in some respects when it comes to scope. With is actually a very clean way to do this. – Shog9 Sep 3 '10 at 3:44
3  
+1. By the way, Pascal also has with. – Pavel Shved Sep 9 '10 at 20:28
1  
Yeah, I like with. Stashing something in a variable so I can avoid something like Heather's second example just seems a little messy. I tend not to use VB, but this is one of the things that I wish C# had. – JohnL Dec 6 '10 at 20:11
1  
I've seen With be abused as well. I'm talking 200 lines of Delphi all encased in a with and if you forgot which variable the with was using, you had to go back up and figure it out. I can definitely see the use of it in 4-8 lines, but it can easily be abused. – Earlz Jan 10 '11 at 6:44
show 5 more comments

Haskell

The syntax for "point-free style," in which, ironically, one uses the point (.) to denote composition. "Point-full" style:

fn x = f ( g ( h x ))

Point-free:

fn :: a -> b
fn = f . g . h

The functions are equivalent, but the latter is considered "cleaner."

share|improve this answer
3  
Kind of ironic since point-free is more like a lack of syntax. Very cool in action. – CodexArcanum Dec 7 '10 at 2:08
1  
Due to Haskell's lazy evaluation there are not many keywords or much syntax. It's mostly only functions. The dot in the above example is in fact the function with signature "(.) :: (b -> c) -> (a -> b) -> a -> c". – LennyProgrammers Dec 7 '10 at 9:11
1  
@j_random_hacker: In a word, composition. I find the pointless style a pig to read, but the functions written in them are far easier to compose into larger, even more unreadable messes... I've lost my train of thought now. – JUST MY correct OPINION Jan 9 '11 at 12:04
show 5 more comments

The C# Extension Method.

It's a great way to make static method use a little cleaner and clearer:

public static string DoubleUp( this string toDouble ){
    return toDouble + toDouble
}

//elsewhere...
string result = "Ha".DoubleUp().DoubleUp();
//result = "HaHaHaHa"
share|improve this answer
show 4 more comments

Perl 5

Perl 5 absolutely abounds in fantastic syntactic sugar I miss elsewhere, starting with sigils to quickly group variables by type ($scalar, @array, %hash). My absolute favourite is unless, which removes the need to rewrite a complex expression as it's negative or to add an easy-to-overlook not (or, horrors, !) at the start of the expression. Compare:

    if(($x < 10_000) || ($x > 20_000)) { .. }

or

    if(not ($x >= 10_000 and $x <= 20_000)) { .. }

with the elegance of:

    unless($x >= 10_0000 and $x <= 20_000) { .. }
share|improve this answer
1  
Interesting that you mention this feature. The Perl Best Practices strongly suggests not to use this particular aspect. The idea being that negated logic like unless is more difficult to comprehend. – Danny Sep 15 '10 at 11:48
show 1 more comment

Interfaces.

I was introduced to them when I first learned Java in 1997, but I think something similar had existed in other languages (Objective-C?) for a while.

Not everybody likes them, but they have some big advantages:

  • They give you more control over the order in which you write classes. You can program against the interface (using mock implementations) hours or even months before the implementing class is written.
  • They solve the multiple inheritance problem, even allow inheritance to be dispensed with (e.g. Go)
share|improve this answer
6  
Not really a syntax element. – Timwi Sep 4 '10 at 20:29
show 2 more comments

SQL

Throwing a SELECT statement inside a JOIN.

e.g.

SELECT * 
FROM
   foo f
   INNER JOIN (SELECT * FROM Goo WHERE a = 1)  subset
   ON f.id = g.id

Update Removed the C# one

-

share|improve this answer
1  
I love derived tables as well. – HLGEM Dec 6 '10 at 19:54
show 1 more comment

LINQ in C#

What could be cooler than creating both simple and complex logic using natural language?

from item in items
where item.IsActive
group item by item.Category
    into itemCategory
where itemCategory.Count() > 5
orderby itemCategory.Key
select itemCategory
share|improve this answer
2  
Amen. seeing other devs re-implement a lot of the functionality that linq already has built in is sad and prone to bugs. I wish it was more widely understood that LINQ is not equivalent to LINQ->SQL. – Evan Plaice Sep 12 '10 at 1:28
show 4 more comments

Python

Array slicing is very elegant.

>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:5] # first 5 elements
[0, 1, 2, 3, 4]
>>> a[5:] # last 5 elements
[5, 6, 7, 8, 9]
>>> a[::2] # every other element
[0, 2, 4, 6, 8]
>>> a[1::3]
[1, 4, 7]
share|improve this answer
4  
gotta love it. as well as list comprehensions. – Evan Plaice Sep 12 '10 at 1:27
show 2 more comments

Python

Python's comparison syntax is brilliant. I wish all languages had this. In Python, instead of

if x>0 and x<100:
    #do stuff

you can do

if 0<x<100:
   #do stuff
share|improve this answer
4  
learned a new trick. thanks! – linjunhalida Sep 20 '10 at 0:34
1  
Lisp had that for a long time. COBOL had constructs like IF PAY-RATE IS > 30 AND < 50, which at least elided the PAY-RATE. I think the language dropped those constructs, as being too hard to parse. – David Thornley Dec 6 '10 at 20:34
2  
SQL has BETWEEN, that kind of test is so common, you would think more languages would include it - though I agree with Mr Thornley, the grammar does become significantly harder to parse. – Orbling Dec 6 '10 at 22:36
show 4 more comments

C++

C++0x lambda syntax very quickly grew on me despite its odd use of symbols:

std::vector<int> vec, vec2;
vec.push_back(stuff);
std::transform(vec.begin(), vec.end(), std::back_inserter(vec2),
      [](int x)->int { return (x*x); } );

Unfortunately, it doesn't work in all compilers. :(

share|improve this answer
1  
By the way, it's not specific to C++. However, the use in C++ is fantastic, thanks to the STL algorithms assuming you provide functors... – Klaim Dec 7 '10 at 10:49
show 3 more comments

C# null coalescing operator

the ?? operator which returns the left-hand operand if it is not null, or else it returns the right operand.

I often use it like so

foo = foo ?? GetNewFoo();

share|improve this answer
1  
I believe it's called a null coalescing operator – TWith2Sugars Sep 15 '10 at 11:32
1  
Sounds like a good name to me. Easier to say than "the-question- mark-question-mark operator" Sadly the Spec and MSDN docs don't name it. – Conrad Frix Sep 16 '10 at 15:25
2  
@Conrad I think you'll find MSDN does - msdn.microsoft.com/en-us/library/ms173224.aspx – Dan Diplo Sep 17 '10 at 18:49
3  
Ah, C# shows its Perl heritage :) – user1249 Dec 6 '10 at 22:31
2  
I just wish there was an inverse: var foo = bar !? bar.Prop !? bar.Prop.SubProp; – John Fisher Dec 7 '10 at 16:16
show 5 more comments

Monads (Example is F#)

async {
    let! asyncValue = getSomethingAsync
    if asyncValue = something then
        do! alertSomeone asyncValue
        do! alertSomeoneElse asyncValue
}
share|improve this answer
1  
Another feature borrowed up from Haskell. :-) – Orbling Dec 6 '10 at 22:39
2  
I don't understand this. I wish that I did. – Carson Myers Dec 7 '10 at 3:22
1  
@Carson Myers: Monads have been described as "overloading the semicolon". Namely, you specify your own "bind" function that takes an "action" and feeds it to a function which returns another action. See Phillip Wadler's paper "Monads for Functional Programming", which gives full examples of monads hiding the plumbing of exceptions, state, and output. Note that this paper predates monads appearing in Haskell, so its notation is a tad outdated (it uses a star instead of >>= for the bind operator). – Joey Adams Dec 7 '10 at 6:15
show 1 more comment

Scala

The fact that I don't have to use "." between function calls. Makes DSLs a breeze.

share|improve this answer
1  
@Joey: Thanks to this feature a phrase like this can be made a legal Scala by encoding it as phrase.like(this). A larger example: list must have size 2 can be encoded as list.must(have).size(2). (This is what is done in ScalaCheck, and Specs - testing frameworks for Scala). – missingfaktor Dec 7 '10 at 18:48
show 3 more comments

Anonymous Functions (aka Lambda Expressions)

Sometimes you don't have or want to name everything...

collection.remove(x => isOld(x))

collection.first(x => x == true)

collectino.for_each(x => x + 3)

collection.sort((x, y) => x > y)
share|improve this answer
2  
AKA "Lambda syntax" – Marcel Lamothe Sep 15 '10 at 13:34
2  
@Mladen: C# 3.0 and up. @TomWij: Lambda Expressions are not the same as Anonymous Methods. The most important difference is that lambda expressions are convertible to expression trees (Expression<TDelegate> - the basis of many LINQ providers). See this SO question. – Allon Guralnek Dec 7 '10 at 20:37
show 3 more comments

I love the "everything is an expression"-idea, which can be found in haXe (I suppose the feature actually comes from functional languages).

function fib(n) {//the compiler infers the type of this function to Int->Int
    return 
        switch (n) {
            case 0, 1: 
                1;
                /* in case you wonder: case statements can have
                   multiple conditions, but doesn't allow fallthroughs,
                   because it is terminated by the next case/default
                   statement or the closing brace of the switch */
            default: 
                if (n < 0) 
                    fib(n + 2) - fib(n + 1);
                else 
                    fib(n - 1) + fib(n - 2);
        }
}

Basically, the function body is just one expression. A block is evaluated to the last evaluated expression of the block. A loop is evaluated to the last pass (or null, in case the body is never evaluated). And so on. I think, this is very elegant, concise, safe and less cryptic than for example the conditional operator.

share|improve this answer
4  
It looks like C and Haskell were involved in a traffic accident. – dan_waterworth Jan 9 '11 at 19:29
show 1 more comment

The List Comprehensions from Python

>>> list = [1,2,3,4,5]
>>> [x*2 for x in list]
[2, 4, 6, 8, 10]
share|improve this answer
7  
Don't forget haskell ones too! – Daenyth Sep 15 '10 at 15:43
1  
@Martin: In most circumstances it's preferable. – Daenyth Sep 20 '10 at 13:47
8  
I think the Haskell list comprehension is cleaner: [x*2 | x <- [1,2,3,4,5]] – greyfade Oct 27 '10 at 3:14
show 7 more comments

Javascript

Using apply to run a function in the context of an object. For example, suppose you have an event handler:

$(function(){
    $('#selectr').keydown(function(){
        // update the UI based on the new value
        if(this.value == 1)
        {
               $('selector2').hide();
        }
     });
});

Now suppose that $("#selectr") already has a value when you initially render the page. You could duplicate the display logic elsewhere, or refactor the above function to receive the target element as a value. Or you could use apply

$(function(){

    var selectr_keydown = function(){
        // update the UI based on the new value
        if(this.value == 1)
        {
               $('selector2').hide();
        }
     };

    selectr_keydown.apply($('#selectr').get(0));//selectr_keydown is run with ``this'' referring to $('#selectr').get(0)

    $('#selectr').keydown(selectr_keydown);
});

Note that I've written this using jQuery, but apply is a pure javascript method.

share|improve this answer
show 1 more comment

Smalltalk

Smalltalk's blocks/anonymous functions/closures have the lightest-weight syntax I have ever seen:

#(1 2 3) select: [:each | each odd]
share|improve this answer
1  
Nice! Didn't know about this. :) – missingfaktor Dec 7 '10 at 18:47
show 3 more comments

Javascript

Resize the Length of an Array

length property is a not read only. You can use it to increase or decrease the size of an array.

var myArray = [1,2,3];
myArray.length // 3 elements.
myArray.length = 2; //Deletes the last element.
myArray.length = 20 // Adds 18 elements to the array;
//the elements have the undefined value. A sparse array.
share|improve this answer
4  
Well, I never knew that! Though it looks dangerous, as you could easily resize an array by missing an = when you are evaluating the length. eg. if (myArray.length = 2) { // oops! } – Dan Diplo Sep 17 '10 at 18:52
show 1 more comment

Java

obviously the main method

public static void main (String [] args)

Getters and Setters method

Setter

public void setVar(datatype variable) {
  privateVar = variable;
}

Getter

public datatype getVar() {
  return privateVar;
}
share|improve this answer
3  
Good to have properties in C# instead of these getters and setters. – Gulshan Oct 20 '10 at 4:44
show 3 more comments

As an Oracle developer, the one feature I couldn't live without is how SQL integrates simply and cleanly with PL/SQL.

share|improve this answer

Python's lack of braces and the fact it uses whitespace for code indentation.

That combined with pep8 leads to one consistent code style across almost all python code. It also makes the flow of code much easier to follow because you're not wasting lines on syntactic salt. Before I started with python I hated the idea, but once I started coding in it, it's become second nature and anything else looks ugly.

share|improve this answer

PHP

On-the-fly include()

It simply work great for inserting a function library, 3rd party API, headers, footers, and really anything else I can think of. There is no rule as to where its placed within the file, so I never have to fight with my compiler.

<?
// the web page
include('header.php');
echo '<span>some HTML I want here</span>';
include('body-template.php');
echo '<span>some stuff I want here</span>';
include('footer.php');
?>

oh oops, I forgot my javascript I want in my footer..

<?
// footer.php
echo '</div>'; // body content wrapper
echo '<span>my footer is just this line.<br /></span>';
echo '</html>';
include('javascript.js.php'); // <--- yeah I just added this just now, no problem
?>

For me it makes the process so much easier.

share|improve this answer
show 6 more comments

Surprised no one mentioned keyword methods in Smalltalk, one of the languages best features.

A method can have a name broken up by colons, like:

Table >> atRow:column:put:

(The >> is just a documentation shorthand for showing the class that owns the method.)

To call it, you'd use each part of the name as a specifier:

aCell := DataCell new.
aTable := Table new.
aTable atRow: 3 column: 2 put: aCell

I find it much more readable than table.addCell(3, 2, aCell); even if it is a little more verbose sometimes.

share|improve this answer
show 1 more comment

The ?: and ?. operators in Groovy. They handle any nulls that may happen during a sequence of method calls, so you can do stuff like:

food = pizzaChain.nearestOpenPlace?.orderPizza() ?: makeSandwich()

..and not worry if there's still a pizza place open or not :)

share|improve this answer

In R probably the vectorization in the conditions combined with index power. This allows you to do something like :

x <- 1:10 # a vector from 1 to 10
mean(x[x<5]) # takes the mean of all numbers smaller than 5

This is a trivial example, it works with matrices, arrays, lists, more complex conditions as well. And it's a manyfold faster than any kind of looping structure.

share|improve this answer
show 1 more comment

Python

Dict Comprehensions

Someone mentioned list comprehensions, so I just wanted to add dictionary comprehensions which came in Python 2.7:

>>> def dict_filter(cb, info):
...     return {key:info[key] for key in info if cb(key)}
... 
>>> carson = {"firstname": "Carson", "lastname": "Myers", "age": 20}
>>> privatize = lambda x: x in ('firstname', 'age')
>>> dict_filter(privatize, carson)
{'age': 20, 'firstname': 'Carson'}


>>> {a+1:chr(a+65) for a in range(26)}
{1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 
 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L', 13: 'M', 14: 'N', 
 15: 'O', 16: 'P', 17: 'Q', 18: 'R', 19: 'S', 20: 'T', 21: 'U',
 22: 'V', 23: 'W', 24: 'X', 25: 'Y', 26: 'Z'}


>>> def invert(a_dict):
...     return {v:k for k, v in a_dict.iteritems()}
... 
>>> invert({'a':1, 'b':2, 'c':3})
{1: 'a', 2: 'b', 3: 'c'}
share|improve this answer

I'm a big fan of postfix conditionals in perl and ruby:

return 0 if(!$user);
return 0 if(!$user->can_do_thing);
return 1;

Easy to abuse but great for readability when used properly.

share|improve this answer
1 2

Not the answer you're looking for? Browse other questions tagged or ask your own question.