r/programming • • Aug 05 '19

Why Declarative Coding Makes You a Better Programmer

http://minborgsjavapot.blogspot.com/2019/08/why-declarative-coding-makes-you-better.html
0 Upvotes

15 comments sorted by

23

u/HomeBrewingCoder Aug 05 '19

Why choosing your metrics decides your results, would be a better title.

public final class RestDeclarative implements Rest {

    @Override
    public List<Person> page(List<Person> persons,
                             Predicate<Person> predicate, 
                             Comparator<Person> order,
                             int page) {
        return persons.stream()
            .filter(predicate)
           .sorted(order)
           .skip(RestUtil.PAGE_SIZE * (long) page)
            .limit(RestUtil.PAGE_SIZE)
            .collect(collectingAndThen(toList(), Collections::unmodifiableList));
    }
}

Yes - this does strictly speaking have one statement. But would you call over your coworker and tell them 'hey check this out, I've implemented this in one statement that has zero cognitive complexity!'. Would we be considering some crazy perl one-liner as having similarly a single statement?

Don't get me wrong - I like functional coding, but this article is at best picking only metrics that prove its point.

1

u/scottmcmrust Aug 05 '19

Agreed; this article seems to actually be about how I should never use SonarQube because its metrics aren't useful.

4

u/[deleted] Aug 05 '19

I personally hate SonarQube. I feel like it gives some programmers an easily visible goal to optimize towards (making SonarQube happy) while ignoring other (more) important aspects, like good design and understandable code, which SQ can’t sense at all.

In my experience nobody really critically thinks about if the analysis rules included are even value-adds or make sense, like having accidental tabs included in a file or a copyright header omitted marked as Major issues, and it’s inability to recognize code that is safe from NPEs, as it’ll throw a Critical issue just the same.

And then you have the beyond hope programmers who take stuff like the rule “all numbers should be stored in a field” and replace 2s with private int TWO = 2;

5

u/HomeBrewingCoder Aug 05 '19

As soon as a metric starts being used for scoring, it becomes a bad metric.

17

u/[deleted] Aug 05 '19

The thing I've realized about "declarative coding" is that it's actually not a separate type of coding. There's no hard line there. In the way they're defined it feels like it is, but in practice, declarative code is basically higher-level code.

And of course, higher-level code is to be preferred. But the most important part about being able to write high-level code is to have the habit of writing your own "declarative" abstractions and high-level tools to express the rest of your code with.

Using what the language offers, like filters/map/reduce, LINQ and so on, that's great. But if you stop at what's built-in, you're missing vast opportunities in making your code higher-level.

Functional programming practitioners do this instinctively. They'd create for themselves highly composable high-order functions designed for a task, so they can express a program in a surprisingly tight and minimal way. Most mainstream programmers would just grunt through, copy-pasting samples from the web, and using whatever APIs are available out of the box.

So in a way, it's not that declarative coding makes you a better programmer as much as... being a better programmer is in large part about factoring your code declaratively (high-level).

1

u/[deleted] Aug 05 '19

Can you go a little more into what a functional programmer would do instinctively?

4

u/[deleted] Aug 05 '19 edited Aug 05 '19

It's a subtle topic, but I'll use a very small example to illustrate a principle. Functional programmers commonly use a principle called partial application, commonly through "currying", which take a highly general-purpose function with, say, 5-6 arguments, and produces a more specialized function with 2-3 arguments by providing "default" values for some of the arguments.

So this means you can have your complex to call general purpose function, but you don't have to call it directly in your code, except in the few places where you "partially apply" it for a specific purpose (in OOP similar to: Facade pattern).

In functional programming two trends stand out that I don't see as often in OOP, and not because OOP can't do that, on the contrary: it's built for it; rather it's about culture and experience.

One is, when you're building general purpose code make it extremely flexible through closures taking closures (Strategy pattern, Decorator pattern, Proxy pattern, etc. in OOP for ex.), returning closures (Factory pattern, Builder pattern etc.). Note that objects/closures are interchangeable units of code in these examples.

Two is, you take these very general purpose, sometimes complex closures/functions, and then you produce simpler "wrappers" for a smaller part of your object. Then you proceed to use these "wrappers" for most of your code, not the general purpose (and much more verbose and complex) APIs.

And then of course there's a third concept, which is using very simple, very universal interfaces where possible, so you can compose vastly different units of code together into solutions through their shared simple interfaces (in functional programming one example is monads, well LINQ is basically monads, so are streams in Java).

Sorry if this sounds fuzzy, it's something best understood in practice, not in theory.

EDIT: Slight terminology mix-up.

8

u/TommyTheTiger Aug 05 '19

Isn't using higher order functions (functions that take functions as arguments, like map, filter, reduce) normally called functional programming? Now SQL, there's a declarative language

7

u/Zardotab Aug 05 '19 edited Aug 05 '19

I've often found declarative and functional (D/F) code difficult to debug, and others have shared this observation. With imperative code it's usually easier to examine the intermediate "parts". With D/F you often have to use trial-and-error to tease out the problem by removing constraints or functions within the "function chain" incrementally.

When I bring this up to D/F proponents, they either say something like, "learn to code better so you don't have to debug", or recommend splitting things up into mini-functions or similar. But that often makes for messy or cluttered code, at least to my eyes. Plus, with such splitting, it is still harder to debug than imperative.

I've been in many long debates on this. Some things are subjective, and one has to be careful about extrapolating their own mind to other minds. So far, imperative code is the easiest to x-ray to most. If you are an elite coder of a Sheldon Cooper level, then maybe you can debug just by glancing at the code. But us mortals need the ability to easily dissect problem code at finer levels.

As far as speed improvements, your application code should not be chomping on 10,000+ records; that's the job of the database. If you are reinventing database operations in your app code, then you are probably doing something wrong. I will agree that some domains are inherently speed-constrained or can't use a database. That's fine, but realize you may be trading debug-ability for speed.

I've been leaning toward the idea of using declarative to get a "draft list", and then imperative to "decorate" it with nitty gritty domain specifics. In other words, use declarative when the filters or behaviors are clear-cut and simple, but use imperative to tweak the intermediate results with specialized imperative code that does things like complex conditionals, parsing, string conversion, etc. That way each does what it does best (D/F and imperative).

Overall, I find imperative better at nitty-gritty logic. If you have a clean domain where the "rules" are defined by the laws of physics or good well-factored technical standards, D/F may shine more often. But if the domain is driven by whims of the legal system, office politics, marketers chasing fads, etc., then imperative may better handle all the micro-tweaking needed.

In general, use D/F to do forest-level processing/filtering, but imperative to do tree-level processing/filtering. (I don't mean trees in the data-structure sense). Use-The-Right-Tool-For-The-Job. The code may resemble something like this SQL-ish pseudocode:

SELECT *      
FROM   employees AS e 
  JOIN offices AS o 
    ON   e.officeID = o.ID
WHERE  /* functional-style actions */
    e.salary > 80000 AND o.region = 7
LOOP   /* imperative actions */
    IF e.status = 13 AND o.closedDate NOT NULL
    AND myOwnFunction(e, o) 
    THEN 
      e.adjustedResult = 'foo';   /* generated output column */
      e.lastName = 'Redacted'     /* altered output column */
    END IF
    IF myOwnFunction2(e) THEN
      EXCLUDE RECORD    /* exclude this row from result set */
    END IF
END LOOP

2

u/masterofmisc Aug 05 '19

If you are using C# he is basically replace all your imperative for loops with Linq queries where possible!

... which is good advice that you cant grumble with.

Lambda functions such as map (Select in Linq), Where, Filter etc are common place now in languages like Python, C#, Java & JavaScript, etc.

5

u/tulipoika Aug 05 '19

It’s good only if you know what you’re doing and can live with the possible performance issues. In most cases it’s fine and speed of development is more important, but in some cases the little streams become a big river.

LINQ has come a long way and will be even better in the future.

2

u/scottmcmrust Aug 05 '19

Resharper can do this automatically. Using that feature is often a good demonstration of why that advice is not necessarily good advice, and I tend to Ctrl-Z after trying it.

3

u/snowmountainjc Aug 05 '19

Isn't advertising against the community rules?

1

u/[deleted] Aug 05 '19

I would extend this concept to parameters.

Sometimes, a simple enum to abstract an array index can do wonders in readability.

0

u/chewyfruitloop Aug 05 '19

.....oh look I’ve reduced the number of lines of code....made a program that’s got bugger all chance of being understood by anyone but me....will be the cause of no end of maintenance issues and gives me a reputation as a lose cannon who can’t be trusted to work as part of a team

Look at me I’m a rock star....sod the rest of you peasants