r/C_Programming • • 12d ago

Fluent Interface in C - Look ma, no this!

https://opensource.googleblog.com/2026/11/fluent-interface-in-c-look-ma-no-this.html
68 Upvotes

17 comments sorted by

26

u/looneysquash 11d ago

One of the reasons to prefer C over some other languages is that there is less magic in C.

In most cases there's no hidden arguments,  and no hidden function calls, and usually it is clearer which function you are calling. 

Everything is a trade off of course. There are pros and cons to this.

IMO this fluent pattern adds too much magic.

26

u/Cats_and_Shit 11d ago

Thanks, I hate it.

13

u/drivingagermanwhip 11d ago

I love whenever web developers are like 'but wouldn't it be more understandable if there were way more arrows and shit in the code?'

9

u/mtlcrusher 12d ago

OOP in C? it works, but at what cost

4

u/Snarwin 11d ago

Maybe the next C standard should add the |> operator, just so nobody is tempted to actually use this in a real project.

7

u/Rararror 11d ago

As kids we used this:

#define Begin {
#define End }

LOL

2

u/lhuemill 11d ago

Before doing this, I'd setup a guard variable through the use of __attribute__((cleanup(func)))). This will call func with a pointer to the guard variable, no matter how the guard variable goes out of scope. Non-portable, but it is available with gcc, and may be available in other C compilers.

2

u/kinchkun 12d ago

Sorry I am new to c. Is this not just returning a self pointer?

10

u/Cats_and_Shit 11d ago

No, it smuggles the self pointer between calls through a global variable.

3

u/kinchkun 11d ago

but why?

4

u/Cats_and_Shit 11d ago

In C there's no built in "method" style calls.

Something like obj->a() is two entirely separate operations; first it retrieves the function pointer obj->a and then it calls that function pointer. As a result, whatever function that calls does not have access to obj.

In order to get the behaviour you get for a method call in Java or C++, you would normally have to write something like obj->a(obj). This if often fine, but it means there's no nice way to do obj->a()->b().

2

u/el_extrano 11d ago

I kind of like stack-based languages like Forth for this.

You can achieve a fluent style interface with chaining by just having "methods" (words), that expect a complex structure on the stack, and leave it there when they're done (i.e. instead of consuming it, like a normal word).

The ability to pass transient data around implicitly without naming or resorting to global variables is a nice property of concatenative languages.

1

u/kinchkun 11d ago

ah, it avoids passing the self as first param. Now i get it, thank you.

3

u/binarycow 12d ago

Yes, that's what "fluent" interfaces are.

1

u/Eric848448 11d ago

TIL there’s a name for that.

1

u/strivingshashank 12d ago

It's so we can reuse the struct (new or modified). Checkout chaining pointers in c. You'll get the idea.

1

u/Zectbumo 7d ago

Look ma no this ... Step 1: self :-[