DEV Community

Cover image for The Coolest Programming Language Features

The Coolest Programming Language Features

Jeremy Grifski on April 03, 2019

As the Sample Programs collection grows, I often like to reflect on what I’ve learned. In particular, I enjoy comparing and contrasting languages a...
Collapse
 
aaronpowell profile image
Aaron Powell

I'd like to throw in Pattern Matching from C# 8 and F# as one of the coolest language features.

// fsharp
let name = match person with
           | None -> ""
           | Some p when p.FirstName = "" -> sprintf "Mr/Ms %s" p.LastName
           | Some p -> sprintf "%s %s" p.FirstName p.LastName
// csharp
var name = person switch
           {
               null => ""
               { FirstName: "", LastName: var lastName } => $"Mr/Ms {lastName}"
               { FirstName: var firstName, LastName: var lastName } => $"{firstName} {lastName}"
           };

In both these examples we first check if there was a value (using an Option<T> in F# or a nullable type in C#), then checking if there was or wasn't a first name to determine the name of the person to print.

I totally ❤ using pattern matching in code over nested if blocks!

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

That F# syntax is really pretty! Know anyone who would want to add some new F# snippets to the collection?

TheRenegadeCoder / sample-programs

Sample Programs in Every Programming Language

Sample Programs in Every Language

Build Status Join the chat at https://gitter.im/TheRenegadeCoder/sample-programs

Welcome to the Sample Programs in Every Language repository! What began as a simple 100 Days of Code challenge has expanded into a fun project Within this repository, you'll find a growing collection of simple programs in just about every programming language to date.

Learn More

Originally, I had planned to have an article written for every code snippet in this repository However, in the interest of growing this collection, I removed the pull request merge article requirement As a result, not every code snippet in the repository has an associated article, yet.

Of course, we're adding articles every day, and we're tracking our article progress under the issues tab Feel free to request your favorites from there, and we'll try to move them up the queue. If you can't wait, consider writing the article yourself. Prospective authors can find directions in the contributing doc

Also, I'd be interested in learning more about pattern matching. I've seen it in other functional languages like Racket, but I don't know a lot about it.

Collapse
 
aaronpowell profile image
Aaron Powell

I'll have a look at getting an example up there for you 😊

Collapse
 
saint4eva profile image
saint4eva

I love C#

Collapse
 
cout970 profile image
cout970

There is a feature in Kotlin that I haven't seen in any other programming language and I think is the coolest feature ever.

Extension lambdas: It's a lambda where you specify the value of 'this', where 'this' is the implicit object where to find functions or fields. For example, the function apply() has a lambda as argument where the value of 'this' is the object used to call apply() (Kotlin lambdas are delimited by {})

StringBuilder().apply {
  append("hello")
  append(" ")
  append("world")
  append("!")
}

It creates an instance of StringBuilder and calls the method append() without having to write this.append(). In java you have to write this instead:

StringBuilder s = new StringBuilder();
s.append("hello")
s.append(" ")
s.append("world")
s.append("!")
s

This also works with properties, so you can easily build SDLs:

message {
  author = "Cout970"
  subject = "Hello"
  content = "Hello world!"
  method = Method.POST
  send(to = "everybody")
}
Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Oh, so this is pretty cool. Let me try to understand it better. Instead of writing a constructor with ten parameters, you can expose properties that can be set with an extension lambda?

Collapse
 
cout970 profile image
cout970 • Edited

yes, basically, but it has a lot more uses!, for example there is a library that allows you to write html using extension lambdas and it looks like this:

html {
  head {
    title { +"Page title" }
  }
  body {
    h1{ + "Cool article" }
    p { +"article content" }
  }
}

they have the same flexibility as normal lambdas but with a lot less boilerplate

Thread Thread
 
renegadecoder94 profile image
Jeremy Grifski

Wow that’s elegant. I imagine you get the added benefit of type checking and whatnot, right?

Thread Thread
 
cout970 profile image
cout970

Yes!

Collapse
 
rhymes profile image
rhymes

Great article Jeremy! Thanks.

Funny because I didn't know what extension methods were and instead of some voodoo thing they are just what you can achieve in Ruby with open classes:

2.6.1 :001 > class String
2.6.1 :002?>   def mutate()
2.6.1 :003?>     return self + " mutation"
2.6.1 :004?>   end
2.6.1 :005?> end
 => :mutate
2.6.1 :006 > s = "Hello, world!"
 => "Hello, world!"
2.6.1 :007 > s.mutate
 => "Hello, world! mutation"

or JavaScript extensions using prototype inheritance:

> String.prototype.mutate = function() { return this + " mutation"; }
> a = "Hello, world!"
> a.mutate()
"Hello, world! mutation"

Optional chaining should be added to all languages with the concept of null 😭

Collapse
 
vicentemaldonado profile image
Vicente Maldonado

en.wikipedia.org/wiki/Extension_me...

"The Ruby community often describes an extension method as a kind of monkey patch." 😀

But yes, they can be useful.

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Wow. Clearly, I haven’t played around enough with ruby or JavaScript. I really thought Kotlin was changing the game. Haha thanks for the tip!

Collapse
 
samuraiseoul profile image
Sophie The Lionhart • Edited

You can do this weird BS in PHP. I liked it when I super junior and starting out but now it horrifies me as quite the bad idea.

class Foo {
    public function bar() { return 42; }
} 

$foo = new Foo();
$voodoo = 'bar';
echo $foo->bar(); //42
echo $foo->$voodoo(); //42

$anotherVoodoo = 'Foo';
$foo2 = new $anotherVoodoo();
echo $foo2->bar(); //42
echo $foo2->$voodoo(); //42

Disclaimer: I didn't atually test the above.

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Woah, that's wild. You can literally initialize objects and run methods using strings?

Collapse
 
samuraiseoul profile image
Sophie The Lionhart • Edited

Yeah. Heck you can get even weirder.

class Foo { public function bar() { return 1; }
$foo = new Foo();
$funcName = 'bar';

$funcNameVarName = 'funcName';
echo $foo->$$funcNameVarName(); // 1

You can reference variables with it too like above. In php this whole thing is called variable variables.

You can get weirder too. I'm not gonna redefine the above class because I'm lazy but:

$foo = new Foo();
$incompleteFunctionName = 'ba';
$referenceToFuncName = 'incompleteFunctionNam';

echo $foo->{${$referenceToFuncName . 'e'} . 'r'}(); // 1
Thread Thread
 
renegadecoder94 profile image
Jeremy Grifski • Edited

Hahaha in a weird way, I find this syntax amazing. The idea that everything is just a string is really a funny concept, and it would make a great language for obfuscation. Good luck trying to figure out what anything does.

Kind of reminds me of Tcl: "strong internationalization support: everything is a Unicode string"

Thread Thread
 
samuraiseoul profile image
Sophie The Lionhart • Edited

I wish to make the disclaimer that while the above is possible it's not super common anymore. You might find some of that fun in framework or library code instead of using or in addition to reflection. You would also see it in legacy code, especially version 4 and below. I found that syntax really cool when I just starting out at programming as well, now I see it as a really strange and even powerful language feature, but one that should almost never be touched. :P

Php arrays are equally BS though. PHP doesn't have real arrays, as in the sequential memory array concept. Everything is essentially a hash map. This causes some weird indexing things. The official docs explain it much better than I can.

php.net/manual/en/language.types.a...

Also for all it's weirdness, php docs at least are really good for the most part. Also PHP is not as bad as people make it out to be at least version 7.1+ and beyond. Though it still is fucked. :P

Also php tried to do the whole everything is unicode thing I believe in version 6 but abandoned it.

Collapse
 
gypsydave5 profile image
David Wickes

What a great post! It's really kicked off some good discussion.

Now... to business!

Macros

For those of you that don’t know, macros are actually a metaprogramming feature. More specifically, macros allow us to modify the language directly by adding rules to the abstract syntax tree. These rules are generated through pattern matching.

Alas! Alas, that you should have stumbled upon macros in Rust of all places! Macros in Rust are horrible - look at that syntax:

macro_rules! print {
    ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
}

A whole new and weird 'pattern matching' language to manipulate Rust's AST. No wonder we're not meant to use it - it's horrible! macro_rules!? More like macro_sucks!.

My friend, if you want to see and do macro programming right, you need to get yourself a Lisp. Preferably Common Lisp, but Racket, Scheme or Clojure will do in a pinch. Because these languages exhibit homoiconicity, which is to say that the representation of the language - the way you write it - is a data structure of the language. You write Lisp - as lists!

This means that, when it comes to changing the program with a macro, you're using the same language (Lisp) to manipulate the list structures that are the syntax of Lisp. No weird embedded pattern matching language - just the same stuff you've been writing all along (only occuring before evaluation which takes a bit of getting used to...). Code is data! Data is code!

Try them today - Lisp macros are fun and easy!

(Whether they're a good idea or not is more contentious...)

Collapse
 
renegadecoder94 profile image
Jeremy Grifski • Edited

So, I've actually written a pretty basic Lisp interpreter (in an imperative language no less), so it makes sense that you can manipulate the language with itself. In fact, I believe Racket has a ton of support for dialects, but I haven't gotten a chance to play around with that feature myself.

Thanks for the tip! I know C has macros as well, and they're arguably worse the Rust's, so I guess I could have used a worse example. haha

Collapse
 
vicentemaldonado profile image
Vicente Maldonado

Pattern matching! I've only been familiar with variable unpacking from Python and then I learned some Erlang. Many people don't like Erlang's syntax but pattern matching is great! I understand that F# and OCaml also have that.

Haskell types. I've been toying with language construction lately and it's very nice.

data Exp  
      = Let String Exp Exp
      | Exp1 Exp1
      deriving Show

data Exp1 
      = Plus Exp1 Term 
      | Minus Exp1 Term 
      | Term Term
      deriving Show

data Term 
      = Times Term Factor 
      | Div Term Factor 
      | Factor Factor
      deriving Show

data Factor 
      = Int Int 
      | Var String 
      | Brack Exp
      deriving Show

This would take an entire class hierarchy in Java.

And third, string interpolation is very handy.

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Wait, so you can write an entire language grammar in Haskell like that?! I once wrote a compiler in java, and I ended up just using ANTLR to generate the syntax tree (and a huge string of If statements to clean up that tree). This would have been a lot more fun to work with.

Collapse
 
vicentemaldonado profile image
Vicente Maldonado • Edited

Yes it's from the parser generator example

haskell.org/happy/doc/html/sec-usi...

I understand you can do the same in OCaml and F#, they say ML languages are well suited for compiler construction for that. I've been playing with yacc-like Java parser generators and that seems such a time saver compared to a Java class hierarchy.

Edit: you still have to define production rules though, just like in Yacc.

Collapse
 
darkain profile image
Vincent Milum Jr

The C/C++ preprocessor is still a feature I miss in virtually every other language I ever touch. The ability to transmute the actual code before it is parsed is invaluable in those environments. It also ties in directly with the inline ASM on your list, where the preprocessor can be used to select the proper ASM architecture for the given platform.

A great example of this is used in crypto libraries. They generally have a basic C/C++ implementation, but also optimized versions of certain routines for x86, x86-64, AES-NI, ARM, ARM-NEON, and more.

It is also nice to have platform-specific or build-specific flags that can toggle various parts of code on/off, or change things up entirely. This helps when porting code for example, because the path to a particular file may not be the same between Linux, BSD, MacOS, and Windows.

One last trick to mention. The preprocessor can also modify the linker. In one of my projects, I have preprocessor directives to link in static libraries. These libraries are compiler specific, so instead of creating countless different build scripts, I have a single CPP file with them all listed with different #ifdef tags to target each compiler.

Collapse
 
phlash profile image
Phil Ashby

Given that the C pre-processor can usually be invoked without the language compiler (eg: gcc -E), it can and indeed has been used to pre-process other languages, Wikipedia has a nice list of abuse at the end here:
en.wikipedia.org/wiki/Preprocessor

Of course many people think pre-processing is bad (mostly I agree):
stackoverflow.com/questions/321791...
literateprogramming.com/ifdefs.pdf

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Very cool stuff! I try to stay away from languages like C/C++ because I don’t love managing my own memory. That said, I’m always surprised with how powerful those languages are.

Collapse
 
darkain profile image
Vincent Milum Jr

Self-managed memory does add some issues, but it also affords some great advantages, too! Last year I worked on optimizing a web server for a micro controller that only has 80KiB of RAM so it required a lot of custom fine-tuning of memory management to get the thing to perform well.

Here is an example of one method I converted from a C++ managed memory library to some unmanaged code to help reduce the RAM consumption:
gist.github.com/darkain/23da34f00e...

Collapse
 
nickytonline profile image
Nick Taylor • Edited

I'd say another great language feature is generics. I'm not sure if C# was the language that first created this feature, but it was my first exposure to it.

Some references for those interested:

Collapse
 
renegadecoder94 profile image
Jeremy Grifski • Edited

Good one! I forgot about generics. They're used all the time in Java as well when you want to specify the type of some collection (i.e. ArrayList<T>, LinkedList<T>, etc.).

Collapse
 
vicentemaldonado profile image
Vicente Maldonado

I guess we kind of just take generics for granted. It would probably take me to program in a language that doesn't have generics (like VB6) to really appreciate it.

Collapse
 
ld00d profile image
Brian Lampe

Top 10 Coolest Programming Language Features! You won't believe number 9!!!

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Haha exactly! Number 3 will blow your mind.

Collapse
 
edh_developer profile image
edh_developer

Have you tried Groovy? It has most of what you list here, and for someone that's familiar with Java it doesn't take much getting used to.

Collapse
 
renegadecoder94 profile image
Jeremy Grifski • Edited

Oddly enough, I've just started playing with Groovy:

Add Article for Hello World in Groovy #33

jrg94 avatar
jrg94 commented on Apr 22, 2018

Merged the script #20. Never wrote the article.

I'm in the process of trying to get groovy files to run with docker (and writing a hello world article). Any good tutorials or documentation you know of for Groovy?

Collapse
 
edh_developer profile image
edh_developer

I liked Venkat Subramaniam's book, "Programming Groovy".

Hello World is just...

println "Hello World!"

Thread Thread
 
renegadecoder94 profile image
Jeremy Grifski

That sure beats the heck out of:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
Collapse
 
ben profile image
Ben Halpern

Really great post Jeremy!

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Thanks, Ben! Glad you liked it.

Collapse
 
johnpaulada profile image
John Paul Ada

Piping and Pattern Matching are some of my favorite language features 🦄

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Do you have any good piping examples? I think I've seen it in F# (and bash).

Collapse
 
johnpaulada profile image
John Paul Ada

Yeah something like in F#!
Here's an example in ReasonML: 2ality.com/2017/12/functions-reaso...

Thread Thread
 
renegadecoder94 profile image
Jeremy Grifski

Awesome! Instead of nesting function calls, you can chain them. And, you don’t have to do anything special like making all methods return the same instance. I like that a lot.

Collapse
 
ameliagapin profile image
Amelia Gapin

Okay, your lamba example is the first time anyone has succinctly explained and demonstrated what lambdas are and why they are useful in a way that clicks for me.

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Thanks! I'm glad it was helpful. I published this article for the first time about a year ago, so I wasn't confident these definitions were any good.

Collapse
 
josegonz321 profile image
Jose Gonzalez
  • Immutability
  • No NULLs
Collapse
 
renegadecoder94 profile image
Jeremy Grifski

I love both of these things. Know of any languages that have implemented these features?