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

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

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

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

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

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

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

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

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

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

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

I like Common Lisp macros (not sure they fit into the definition of syntax in this question). Macros shorten your code and lengthen your life.

share|improve this answer
show 1 more comment

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

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

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

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

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

Ruby Block

Pass anonymous function as a parameter

# fetch names of all users
names = users.map { |user| user.name }

# sum of array
sum = numbers.inject { |sum, value| sum + value }
share|improve this answer

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

Scala:

Pattern matching to extract data out of various structures like lists, tuples, and record types.

val list = List(56, 1, 89, 32)
list match {
  case x1 :: x2 :: xs => {
    println("First: " + x1 + "; Second: " + x2 + "; Rest: " + xs)
  }
}

val t = (3, 6, "Hello")
t match {
  case (_, _, c) => println("Third element of t is: " + c)
}

case class Person(
  firstName: String,
  lastName: String,
  age: Int
)
val rahul = Person("Rahul", "Phulore", 20)
rahul match {
  case Person(_, surname, _) => println("My surname is " + surname)
}
share|improve this answer
1  
Yet another element borrowed from Haskell – dan_waterworth Jan 9 '11 at 19:43

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

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

Scala:

Everything is an expression, including if-else, for, try-catch, match-case.

Examples:

val status = if(on) 1 else 0

val listDoubled = for(x <- list) yield 2 * x

val str = "124"
val i = try { str.toInt } catch { case x => -1 } 

val typeOfX: String = x match {
  case i: Int => "Integer"
  case s: String => "String"
  case _ => "Other"
}
share|improve this answer

F# forward pipe operator (|>)

Makes code very readable than otherwise.

Example:

// Without |>
List.filter (fun x -> x > 5) (List.map (fun x -> 2 * x) [1; 4; 5; 9]) 

// With |>
[1; 4; 5; 9] |> List.map (fun x -> 2 * x) |> List.filter (fun x -> x > 5)

For those who don't know F#, above code is equivalent to following C#:

(new List<int>{1, 4, 5, 9}).Select(x => 2 * x).Where(x => x > 5);
share|improve this answer
show 1 more comment

I work mostly with C, which makes me appreciate foreach() quite a bit since it is lacking in my primary language.

Yes, you can implement something a lot like it, with limitations, but it just isn't the same.

share|improve this answer

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

Javascript

I love the fact that objects are essentially dictionaries so that

someObject.property

is syntactic sugar for

someObject['property']
share|improve this answer
show 3 more comments

A very short way to test a boolean and execute a single statement in Javascript:

test && alert("hi!");

Now, if test equals true then the browser will execute alert("hi"); This is because it will only test alert("hi") when test equals true and because Javascript is so loose, you can use this outside an if statement and alert("hi") can be anything

This is not very useful for developing as it will make your code harder to read, but if you have to make a script as small as possible it is very useful indeed

share|improve this answer
1 2

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