Search code examples
c++coding-stylefluent-interface

What's a fluent interface?


I recently came across this expression - but reading up on Wikipedia did not clarify it much for me - I still don't get it:

  1. What's the point of it
  2. How is it used in practice (i.e. how does it benefit a coder in their day to day work/building systems)?

[Edit] The Wikipedia article C++ example is overly long, and conflates the discussion of a fluent interface with an example of a simple Glut app. Can someone provide a SUCCINCT C++ example of a class that illustrates a fluent interface (how does such an influence differ from an ordinary C++ interface for example)?


Solution

  • It benefits the coder by reducing the amount he has to type (and read).

    To use the C++ example on Wikipedia:

    Before:

    int main(int argc, char **argv) {
         GlutApp app(argc, argv);
         app.setDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_ALPHA|GLUT_DEPTH); // Set framebuffer params
         app.setWindowSize(500, 500); // Set window params
         app.setWindowPosition(200, 200);
         app.setTitle("My OpenGL/GLUT App");
         app.create();
    }
    

    After:

     int main(int argc, char **argv) {
         FluentGlutApp app(argc, argv);
         app.withDoubleBuffer().withRGBA().withAlpha().withDepth()
            .at(200, 200).across(500, 500)
            .named("My OpenGL/GLUT App");
         app.create();
     }