825 points · by brundolf · 5y ago · 352 comments
Might be a little off topic, but it reminds me how I am happy that the Go programming language and its philosophies gained popularity even though I don't use the language regularly. Watching Go talks made me appreciate simplicity and clarity.
It made me accept that I don't always need to use every design pattern in the book. It made me think about the readers of my code, who might not always be experienced enough, or might not always have time to understand the brilliant architecture I came up with. I can have some repeated code sprinkled around in the codebase. I don't always need to have n+1 layers in my architecture where all the layers just call the next layer anyway. It might be better to use functions over a complicated hierarchy of classes. It made me appreciate simple tools and widely accepted conventions that result in codebases that feel familiar the second you dive in.
Of course, go is not the only community where these ideas are prevalent, and it's good to know your design patterns and architecture, etc... Finding the balance is not always easy, but it's good to have a popular, successful "counter force" community.
This is by far the most common thing I’ve seen consistently in especially difficult to maintain codebases. Anecdotal for sure, but number 2 on that list is way behind. Extra abstractions for a future that has yet to happen and abstractions because the IDE makes it easy to click through the layers is the number 1 by far reason I’ve seen code based be very difficult to maintain.
If you just keep in your head, “Can I see exactly enough on this page to know what it does? Not more, not less?“ It’s an impossible ideal but that concept is a fantastic mental guideline for maintainable codebases.
The best organizational level technique I've found so far is to add the rule of three to code review checklists. An abstraction requires at least three users. Not three callsites, but three distinct clients with different requirements of the abstraction.
Obviously it's not a hard rule, and we allow someone to give a reason why they think that it's still a good idea, but forcing a conversation starting with "why is this even necessary" I feel has been a great addition.
Obviously for trivial logic that’s less appealing. And obviously all the usual abstraction caveats (too many options or parameters are a bad sign, etc) apply.
The risk with so much duplication is that if the logic is expected to remain the same, even tests won’t catch where they diverge. To me that’s just as risky if not more with internal call sites than with clients, as at least client drift will be apparent to other users.
Instead of creating a Spring service to call a repository for data retrieval, i instead called the repository directly, because there was just a single method that needed to be implemented for read-only access of some data.
And yet, a colleague said that there should "always" be a service, for consistency with the existing codebase (~1.5M SLoC project). Seeing as the project is about 5 years old, i didn't entirely agree. Even linked the rule of threes, but the coworker remained adamant that consistency trumps everything.
I'm not sure, maybe they have a good point? However, jumping through extra hoops just because the software is a large enterprise mess doesn't seem that comfortable either, just because someone decided to do things a particular way 5 years ago. It feels like it'd be easier to just switch projects than try to "solve" "issues" like that (both in quotes, given that there is no absolute truth).
Rule of three sounds catchy but logically it's just a arbitrary number.
Similar to SOLID and KISS, why pick some arbitrary (and also obvious) qualitative features and put it into an acronym and declare it to be core design principles?
Did the core design principles just Happen to spell out Solid and Kiss? Did it happen to be Three?
Either way, in my opinion, designing an abstraction for 3 clients is actually quite complex.
The reason the OP advocates pure functions is because pure functions are abstractions designed for N clients, when things are done for N clients using pure functions the code becomes much more simpler and modular then when you do it for three specific clients.
Is there some book/website/SO post that tries to drive this piont home? Bascialyl some web resource I can link to other programmers to explain the value of coding as such.
Maybe you should be the one to write the article you seek! Believe in yourself. If you find yourself with steadfast values that you find tedious to repeatedly communicate, but that you thinks others ought to know about, why not write them down? Who knows - if it's good and resonates with others, is sounds advice, etc. one day it may end up on HN too.
Not everything worth doing has already been done before!
Over the years there were a couple of attempts at replacing this legacy system with a "well-architected" .net one but all the architecture made things harder to maintain and it only ever got to a fraction of the functionality. When there was a bug in those ones we had to not only find it but we had to go through every other bit of calling code to ensure there were no unwanted side effects because everything was tied together. Often the bug was in some complicated dependency because spitting out html or connecting to a database wasn't enterprisy enough. Deployment was complicated enough it had to be done overnight because the .net world has a fetish for physically separating tiers even though it makes many things less scalable.
90% of the corporate/enterprise code I've seen would be much better off being more like that cgi app.
My second job, they splashed the cash for full-scale professional IDEs, and they couldn't get enough abstraction. I suspect the conveninence of "oh, the tools will let us control-click our way to that class buried on the opposite side of the filesystem" made it feasible.
I wonder if there's some sort of "defeatured" mode for IDEs which could remind people of the cognitive cost of these choices.
This is always tempting. A good argument against it is to realise that future developers (us included!) will know their requirements far better than we can guess them; if code needs writing, they should do it (as an extra bonus, we don't waste effort on things which aren't needed). The best way to help them is to avoid introducing unnecessary restrictions.
But that's the other side of the exact same coin. How do you know if a restriction today is good or bad for the future? Restrictions prevent misuse and unexpected behavior, in the good case.
It's not to save the ~10 minutes per year in faster key strokes to manipulate your code. It's about the way it shapes your thinking about how you code.
After using Intellij for about 5 years I switched to a less batteries-included code editor (currently doom emacs). I figure if I need an IDE to navigate our code as a senior developer on the project then less experienced ones don't stand much of a chance.
I still use Intellij for refactoring.
Want a Set? Golang does not have one, create a map[type]boolean instead.
Want an Enum? Golang does not have one, create a bunch of constants yourself that are not tied together by a type, or create your own type that won't quite make what an Enum is.
If simplicity means feeling like you are programming in the 80's, that is what Golang meant for me with simplicity.
Not having basic stuff such as Set and having to workaround with a map of booleans is not simplicity, as you will have to make it turning the code into a more complex blob to represent the same kind of data structure.
I could go on and on with the list of things that lack instead of things that are simple. </rant>
That being said I’m looking forward to more collection types now that they have a plan for generics.
In my experience, code with too many functions is more difficult to grok than spaghetti code. It's like trying to read a book with each sentence reference a different page. So, I try to code like I would write, in digestible chunks.
> As I get older my code gets a little more verbose
I've seen too many of my previous projects die right when I moved on. Now I tend to write code as if it were written by a beginner: verbose and boring, with no magic.
There seems to be two types of programmers: one that can read a line of code like or theCar.fuel() and trust that you in the current context understand enough of what the call does that you can continue reading on the current level of code. This type of programmers don’t mind abstractions even if a function is called in only one place.
The other type of programmer must immediately dig into the car.fuel code and make sure she understands that functionality before she can continue. And of course then each and every call becomes a misdirection from understanding the code, and of course for them it is better is everything is spelled out on the same level.
I’ve seen quite a bit of code written by the second type of programmers, and if you don’t mind scrolling and don’t mind reading the comment chapter headers (/* here we fuel the car */) instead of all the code itself, it can be reasonably readable. But there’s never comprehensive testing coverage for this kind of code, and there’s usually code for fuelling the car in four different places because programmers 2-4 didn’t have time to read all the old code to see if there was something they could reuse, and just assumed that no one had to fuel the car before since there wasn’t any car.fuel() method.
This is so true. The worst code that I've dealt with is the code that requires jumping to a ton of different files to figure out what is going on. It's usually easier to decompose a pile of spaghetti code than to figure out how to unwrap code that has been overly abstracted.
That more than anything is what kills readability, because context switching imposes a huge cognitive load. Isolating layers of abstraction almost always means small, isolated, single-purpose functions.
Because it is, just on multiple plates.
Yes!!! I've been trying to teach Juniors that if the function itself has 4 levels of abstraction, even if the names are readableFunctionThatDoesXwithYSideEffect ..... it is harder to understand, Ctrl+clicking downards into each little mini-rabbit -hole. Just keep the function as a 80-liner, not a 20-liner with 4 levels of indirection w/ functions that are only used once (inside parent function) ugh.
This works really well as long as you use pure functions, because their impact on behaviour is clearly restricted.
Theres nothing wrong with charming magic in your code, if it really does something special and is not just used for the sake of it - it only gets into dark magic, when you forget or are too lazy to add proper documentation in the end. Which ... happened to me, too many times.
But otherwise very much yes. Clarity and simplicity should be always goal number one. But since simplicity is hard to reach at times and time is short, it is always about the balance.
The difference between code and books is that programmers can freely and naturally define functions. I wonder if some people complaining about too many functions never actually learned how to read code in the first place.
In a way, it kind of _is_ spaghetti code. Even if there's no back references, it turns a single train of thought into a string of entrances and exits.
Which is why I enjoy languages that let me do this without getting too hung up on performance. It's curious that you bring up Python, because idiomatic Python (especially where math libs are concerned) seems to vastly favor brevity/one-liners over all else. It's nice to hear that a veteran is favoring clarity.
I can’t speak to math libs, but in my experience with server-side development, Python devs tend to (often even religiously) cite PEP style guides favoring explicitness and verbosity. I think there may have been a shift as Python got a lot of uptake in scientific and ML communities, and I hope that hasn’t seriously impacted the rest of the Python community because, while I don’t especially love the language/environment, I deeply appreciated the consistency of valuing clear and readable code.
After a spine surgery my programming time got severely limited and so I decided to code my future projects with utility focused languages. I had used Python in the past, but the performance tuning once the application scales is counterproductive and expensive to say the least.
I wanted a language which has predictable performance, decent standard library and most importantly not waste my time; time I can focus on my health. Go was the answer, even if it meant that I had to let go of some of my decade long programming patterns and practices.
Now my only wish w.r.t to Go's future is for it to stick with its utilitarian philosophy and not succumb to pressure of including features which might compromise it and leading to the several forks of Go.
I'm coming from a C# mindset and thinking of learning Go, but I'm so used to generics...
As for the inclusion of Generics I'm divided, I'm eager to use generics again in my current Go to language but on the other hand I'm worried if this is the direction Go language design team is going to take then where will it end?
Your assertion doesn't make sense. N-tier architectures are primarily intended by the needs of said reader of the code, because it provides a clear understanding of how the overall code is organized.
More importantly, it provides a clear idea of what code is expected to call which code, and makes it clear that dependencies only go one way.
I have no idea what leads people to believe that ad-hoc solutions improvised on the spot are helpful to the reader instead of clear architectures where all the responsibilities and relationships are lined up clearly from the start.
I am not against abstractions, but I think they lead to hard to read/debug code when overused. I think they need to be used wisely rather than the default.
It really doesn't. There is nothing intrinsic to Java that forces developers to needlessly add abstractions.
If your codebase has too many unwarranted abstractions to the point it adds a toll to your maintenance, it's up to you to refactor your code into maintainability.
And no, n-tier architectures do not add abstractions. They never do. At most, you add an interface to invert the dependencies between outer and inner layers, which does not create an abstraction. Instead they lift the interface that was always there,and ensures that you don't have to touch your inner layers when you need to fix issues in your outer layers.
One thing that I don't understand about the ecosystem is the hate towards GOPATH. Why introduce a complex dependency system for a package manager when you can just pin submodules with git and reap the same benefits? :)
In simpler terms, the people who designed the language don't use GOPATH at all. That's why it's terrible.
Universal:
- apt, yum, brew
Team PATH:
- GOPATH
- CMAKE_PREFIX_PATH
- PYTHONPATH (which Conda, virtualenv, etc modify)
- CARGO_HOME
Team redundant local blob:
- Node
- pipenv
Rust is probably the least-half-assed (most full-assed?) model, with both a sane user-wide default for cache (~/.local/cargo), a way to edit that default, and project location flexibility.
But I actually love the Go notation that I've opted to organize most of my code around the ~/namespace/src/domain/repo scheme. I never lose track of where a folder is :)
Every time.
That being said I think module borders have become more important to me. Keep seperated what is meant to be seperated.
"It's better to repeat yourself than use the wrong abstraction."
It happens often in the attempt to be DRY we add a parameter or some condition to handle a new variation to what seems like a universal logical construct in the code. Do this enough times and the code is no longer comprehensible to any of the people who wrote each variation, let alone a newcommer. We mistake some commonalities with a universality. We become zealots.
After programming for Clojure for quite a long time (~2 years), I fully share this sentiment. Using pure functions for business logic (and also using simple data structures instead of, say, classes and encapsulation) seems to generally makes the code more simple and maintainable in the long run.
> Of course the qualifier is "mostly": this isn't a dogma. Writing a 100% functional system ("going vegan", if you will) often requires you to jump through a bunch of extra hoops to get all the functionality you need.
Also this. Sometimes going fully functional makes things much more difficult, so a little of "impurity" is also fine.
There are exceptions of course, but I personally feel that there's three main 'kinds' of code:
1. functions that define some input/output relation
2. query methods on data structures
3. modification methods on data structures
4. the bodies of the above functions
In a purely functional language all four are purely functional, but this is (IMO) needlessly restrictive. It leads to recursion where iteration is more natural, awkward choices of data structures or even plain impossibility of certain algorithms/data structures (ask a functional programming zealot to implement an O(1) hash map in a pure way—they will usually stammer, try to move goal posts, before finally admitting it's not possible).Personally I feel that 1 & 2 should be 'pure' and not modify (observable) data and have the same results, but 3 & 4 are perfectly fine if not natural to be imperative and have mutable state.
Viewing iteration as more 'natural' than a fold seems down to mostly taste. And hell, if you really want iteration, you can easily get that in both effectful and non-effectul variants through monads.
>ask a functional programming zealot to implement an O(1) hash map in a pure way—they will usually stammer, try to move goal posts, before finally admitting it's not possible
Except that no one - not even Haskell zealots - will argue that you never need effects, but simply that effects should be encapsulated. In Haskell, nothing prevents you from using mutable state if you really need it and mutable hash tables can be easily implemented using something called functional state threads [1][2].
[1] https://www.microsoft.com/en-us/research/wp-content/uploads/...
I concur. My two favorite languages nowadays (Elixir and Clojure) are far from being purely functional. They are functional enough that mutating state is awkward, but if you do need it it is there.
I also think having immutable data structures by default is a saner choice IMO.
> It leads to recursion where iteration is more natural, awkward choices of data structures or even plain impossibility of certain algorithms/data structures
Anecdotal, but I rarely use recursion/for loops, opting for defining auxiliary functions that works in one element and using map/reduce instead. Really, I don't remember the last time I needed recursion to solve a problem (for example, I know recur exists in Clojure, but I never saw it in the code that I work everyday).
Same here. I use c# and Typescript mostly. In c# you can use Select for map, Aggregate for reduce and there's a huge selection of other list processing operations that make use of lambda expressions. In typescript/javascript there map, reduce, etc
I’ve taken what I learned in clojure (and I can just say the article, even just its title, adequately sum it up) and use the same approach in TypeScript. And it’s a breath of fresh air.
This is probably often true. In high level applications, the idea of classing or abstracting out your i/o from the core functionality is appealing from a security and reasoning perspective, but not sure if serious developers think that way.
Would you need to understand the rationale behind the codebase from a functional perspective, and even the economics of the business logic behind the features? It's kind of an architects view of "this thing essentially reduces to a queue and if I optimize for this, I get more value."
I also find that people who are used to a certain kind of project (e.g. heavily logical) and spend years on it have this tendency to assume all code is the same way.
Couldn’t agree more. But my colleagues make a point of keeping cryptic code cryptic because comments explaining context and reasoning are for noobs. I guess it’s a mid level developer fallacy and until they’ve had enough of pulling their own hair out over this kind of code, they won’t change their mind.
— Linus Torvalds
Programming is ultimately about reading and transforming data. When presented a problem, the bad programmer (presumably not well versed in DS theory) thinks of it first in terms of "steps to reach a solution". Whereas the more skilled programmer is able to identify which set of DS is a good match to a specific problem. That is, which combination of structures allow for an efficient access and manipulation of the data in the context of the problem at hand. The implementation then stems from that insight.
Obviously this skill is mostly valuable in performance critical code, which the bulk of our trade generally doesn't intersect with. And in an age of fast processors and abundant memory, it's common to see O(N) data structures applied to O(1) problems and barely anyone notices the cost. Thus keeping us in the comforting illusion that we're better programmers than we actually are.
I rarely comment on code style for this reason. I want the review to focus on functionality, not style. I don't really believe the notion "imperfect code style is a code smell" anyway.
Blaming developers for something that can be automated? Yeah, something is off here, though not necessarily the review.
> nitpicking of inconsequential things like variable names
To me it sounds like a good thing when there's nothing else to comment on. Making code more readable is a win for everybody.
The style itself is inconsequential, but no consistent style is a red flag to me.
let c = ... versus let customer_address = ... can save a lot of sanity throughout the years
Structure of the code, as in relationship of classes, data flow and high level design is also important and checked during review.
“I’m a good programmer”, I imagine. I wouldn’t disagree :p
I came to the same conclusion ~1 year ago when writing rust.
It's pretty common to have some "high level" method in rust then you split it up, some small parts go into other maybe private methods but a lot goes into split out functions (through this depends on the task, and sometimes could be made into methods if rust would support partial self-borrows).
The only think which sometimes bothers me with that approach is where to place this split out methods. As long as I don't need their functionality in other places I want them to be keep close to the function because of which they exist. But they are function and not methods so placing them in the `impl` block isn't right. Alternatively making them free functions in the method using them seems better but also isn't quite right as this "blows" up the method...
Which for me suggests that it doesn’t really matter which way you do it, as long as you 1) dogmatically adhere to doing it the same way every time and 2) have the tooling to effectively manage the downsides of your choice.
For the field of compilers, I can for example see value in making program analyses pure functions that just compute information about the program and separate them from the program transformations that use this information to (impurely) manipulate code. This makes the analyses more reusable and probably makes reasoning about correctness easier.
For other tasks in the compiler, pure functions can be a pain. My favorite anecdote for this is that of a group of students in a compiler's course who insisted on writing the project (a compiler for a subset of C) in Haskell and who, when discussing their implementation in the final code review, cited a recent paper [1] that describes how you can attach type information to an abstract syntax tree (which is an obvious no-brainer in the imperative world).
---
[1] http://www.jucs.org/jucs_23_1/trees_that_grow/jucs_23_01_004...
“The Value of Values” https://www.infoq.com/presentations/Value-Values/
It explains what the difference is between state and value and why most (almost all) programs actually have very little state and can be written mostly stateless. It was a big eye opener for me.
If you are unable to describe, on paper, what your problem domain actually is, then you have no business opening up an IDE and typing out a single line of code.
I will take that further. If, with your domain model, you are unable to craft a query that projects a needed fact from an instance of the model, the you should probably start over. Dimensionality and normalization are a big deal with your model. You have to be really careful about nesting collections of things within other things if you want to allow for higher-order logic to project required views. This is something we struggled with for a really long time. Every rewrite conversation began something like "well customer and account need each other in equal measure...". And it took us god knows how many iterations to figure out the relationship should not be an explicit property either way.
Put shortly, Modeling is the core of it all. Start with simple top-level collections of things. E.g. instead of modeling Customer.Transactions[], model Customers, Transactions and CustomerTransactions. This fundamental principle of keeping your model dimensions separated by way of relational types can help to un-fuck the most problematic of domains. These will start to look a lot like EF POCOs for managing SQL tables...
At the end of the data, data dominates, and SQL is the king of managing data. If you embrace these realities, you might be encouraged to embed SQL a lot deeper into your applications. I spent a long time writing a conditional expression parser by hand. Feels like a really bad use of time in retrospect, but I did learn some things. Now I am looking at using SQLite to do all of this heavy-lifting for me. All I have to do is define a schema matching my domain model, insert data per instance of the model, and run SQL against it to evaluate conditionals and produce complex string output as desired.
And some think asking your boss if it's okay is a good idea, (spoilers: they'll say no). That is just a way to pass blame for a decision you can't stomach.
You model a certain experimental ("discovery") thing, then you implement it then you analyses the result then you change the model etc.
And sure in many cases in practice people might not skip the modeling but don't properly write it down in any later one usable way. Especially during initial experimental discovery phases. Which isn't good. But understandable and can be fully ok. Honestly especially for boring simple web API's this is pretty common. It's just important to know when to stop ;=)
This IMHO makes most tools to generate code from models just painful to use.
But I still agree that you have no business programming something which you can't somewhat model in a higher abstraction level.
> SQL is the king of managing data
Hm, not so much IMHO. SQL Is terrible bad at it in some contexts because it's inherently made for a 2d table projection which is (more or less) only joined to larger 2d table projections of data which often in it's nature is neither 2d nor maps well to 2d representations. And while you can extend SQL to support that or work around it with e.g. recursive queries it's not very nice to do at all.
There's a fascinating book "Data Model Patterns: A Metadata Map" by David C. Hay that's pretty much a Pattern Language or catalog for data models. You can just implement the subset of Hay's patterns that make sense for your application.
The implementation itself just flowed, allowing me to focus on smaller details that can't be modelled (e.g. error handling). By copying the design of classes and function names, I didn't have to backtrack and redo anything, I didn't have to think about names of things - which were pre decided and so consistent throughout the codebase and my code dovetailed nicely with parts that other people implemented.
However, I've tried to figure out how to actually store and query data relationally in a language like C++ and haven't been able to figure out a good way. I don't want to use SQLite because of performance, this needs to be close to real time (like a game or something similar). I just want a way to store data relationally in memory in C++. I'm still trying to figure out the right approach here. C++ is very static which makes it difficult. I've been able to figure it out in Javascript though.
I agree with this part assuming that graphics and video along with the words are allowed.
>"I will take that further. If, with your domain model, you are unable to craft a query that projects a needed fact from an instance of the model, the you should probably start over."
This is very narrow minded approach that will only work for a very limited set of possible domains. Simplest example to the contrary: the domain is a creation of efficient way of solving some math related problem. What query?
I challenge anyone to present a problem domain which cannot be meaningfully represented in terms of tables in a database. I would prefer if this were bounded by the set of problems you would use any software development strategy upon, but I welcome a more difficult problem as well.
I am being practical. There are many languages that are Turing complete but ill suited for particular domain. It's been proven that SQL is Turing complete as well. However should you propose using SQL to write implementation of say FFT you are not likely to find much of a sympathy.
Dimension = Customers, Accounts, Users, Widgets, Inventory
Higher-Order Logic = combining basic functional building blocks in order to compose more complex functionality. SQL enables direct, declarative access to the whole space of higher-order functions. E.g. You want the list of widgets made 3 quarters ago but scoped to one factory line, and only when a certain rotation of employees was on the factory floor? You got it. That's like 10-15 lines of SQL.
The term "higher order logic" typically means program logic that uses higher order functions. An object-oriented programming style is inherently higher order because objects typically contain functions and are passed to methods.
The term "higher order logic" can also mean a system of logic that allows statements about logical statements. [2]
[1] https://en.wikipedia.org/wiki/Higher-order_function [2] https://en.wikipedia.org/wiki/Higher-order_logic
Spot on. And I would add: Keeping in mind that junior level person could be under excessive stress. Perhaps something has failed. Perhaps they are looking at that section of code for the first time.
Context matters. It affects readability, comprehension, and understanding.
Straightforward > Cleverness
So, Lisp?
From the react docs
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
It's clear "Example" will be called every time it's rendered yet "useState" is NOT "pure". Some magic state is being kept because the first time it's called "count" will be initialized to 0 but after that it won't. Same arguments, different results = not "pure"It's worth noting that it's entirely possible to write "pure methods". Unfortunately most languages don't really let you a) have mutable structures, and b) write enforced-immutable methods on them. Rust is the only one I know of: a method can take a &self instead of a &mut self, which prevents it from mutating self (recursively, which requires knowledge about ownership unless your language is 100% immutable like Haskell or Clojure, which is why this feature is so rare). What I tend to do in other languages like JavaScript, C#, or Python is to use property-getters as a convention that strongly suggests purity; unfortunately that's about the best you can do.
In multi-paradigm languages the decision on whether to make something a pure "getter" method or a standalone function is mostly one of aesthetics. Standalone functions give you a bit more flexibility in use, but sometimes the foo.prop syntax is more readable.
Passing a big structure to a function is a bad idea in any paradigm because it's a big dependency. Instead, you should write the function to operate on the data that it needs and pass just that when you call it.
He's not suggesting pure functional programming - and beyond a certain point the simplicity associated with functional programming will be completely negated by the complexity of the arguments.
From my understanding of what he said, I doubt that he'd advocate for pure functional in circumstances of significant necessary complexity.
I encountered a similar problem where an identity number could be represented in different formats, and the solution had been to store the string representation in all its glorious permutations. Doing db queries to find anything by that key was then impossible until the representation had been made consistent.
Then when e.g. creating reports for different systems we could format the output as per that systems expectation.
This is probably what you're implicitly doing with the class solution you're talking about.
I think I get where you're coming from though. The class hides a type representation that is used as the "internal" representation of the serial number so you only need to write 2n functions. N function to convert to the special serial types, and N functions/logic to convert the special serial types to the internal serial type. The latter N functions are placed in the constructor not as functions but as a series of procedures to deduce the type of the parameter and do the conversion internally. (The effect of this is identical to overloading the constructor).
Let's say A represents that internal serial type, with all other letters in the alphabet representing the serial types of your oil well. You're essentially doing the same as writing:
AtoB :: B -> A
BtoA :: A -> B
CtoA :: C -> A
AtoC :: A -> C
If the goal was to convert B to C with classes you do this: Serial(B).CtoA()
with functions you do this: AtoC(BtoA(A))
Your BtoA logic is simply hidden in the constructor of Serial. But basically the exact amount of written logic is occurring here.I think your question was a trap. One class with n methods is obviously better then n(n-1)/2. I think you were just unable to see that it's basically all functions and expressions in the end. When you use classes you are simply tying these functions to structure and internal variables making them less modular, but the amount of logic is exactly the same.
But overall, if you want to know which methodology is logically better and more resistant to technical debt then I will tell you.
The functional approach is better.
Because the functional approach modularized BtoA. BtoA can be reused in other contexts in the functional approach but in the Object Oriented approach the logic of BtoA is tied together with CtoA, DtoA, EtoA and all of that in the constructor. Likely if you needed that logic as a one off... say to print the serials in internal receipts... you would likely be copying and pasting that logic from the constructor and duplicating it in another class when you follow the object oriented approach.
This is the main reason why the author of the post promotes pure functions. Greater modularity and greater resistance to technical debt.
I don't get upset by a local var i in a while loop, although I often don't see the point.
The problem is the dark mutable data. All those objects being passed around, are they just being read?, are they being modified by this method call?
So if mutable data is used responsibly, it's not a problem. But there's no guarantee that it's used responsibly. Unless all data is immutable. Then it's guaranteed
When you go back to edit your code, it's like calling a 1-800 number and getting re-routed to 15 different departments to finally find the person you need to talk to.
I see this all the time with "business rules" problems.
If you have a situation where you can't make levelled abstractions, you've got some thorny interconnections in your logic (and those may be fundamental!!!). The way I handle this is with a "gauntlet pattern." You still can split your logic up into parts, but you just do it by "rejecting" certain logical chunks at a time within a function and comment above each state of the gauntlet.
It looks something like this:
// marketing told me we should never do this ever under any circumstances
if (!a) {
return CASE_1;
}// if the user enrolled like this, we should check if there's this bad property about that user
if (!b) {
return CASE_2;
}// oh, you crazy people in finance
if (c > 4 && d < 0) {
return CASE_3;
}return CASE_4;
The key thing is not to get hung up on duplication or having exact control flow like how the business thinks about it. You want 1) to return the largest percentage or simplest cases out first, 2) keep everything flat as possible without layers of branching, and 3) be able to associate tests to each one of those early-reject lines.
The nice thing about this is the reduction of cognitive load. By the time you get to the 3rd case or whatever, your mind can already know certain things are true. It makes reasoning about rules much easier in my experience.
Splitting a functions which consists of multiple logical steps is most times a good idea because it makes testing much simple and tends to show you where you accidentally had subtle cross-cutting concerns or unintended cross-talk between sub-domains (domains in sense of modelling, not http).
What is important is to properly name functions (and if you can't you probably shouldn't write that function).
Also it's important to learn how to live with abstraction, i.e. to reason about code wrt. a specific problem without needing to jump into the implementations about every function /method it calls.
Through the later point is much easier with a reasonable use-full type system. And with this I mean useful for abstraction without making abstraction to hard and without allowing to many unexpected things. Languages like rust or scala have such a type system (as long as you don't abuse it) but e.g. C++ fails this even through it has a powerful type system.
At least this are is opinion.
And without question if you can't cleanly split something out, then don't split it out. If you can split it out but not name it reasonable either your understanding it lacking or it should never have been split out.
Assuming you just need helper functions for f(), compare
int f(int x)
{
return g(h(x));
}
int g(int x)
{
return ...
}
int h(int x)
{
return ...
}
to f = g . h
where g = ...
h = ...
Turns out my language choice was the problem, not over-abstraction. If you can fit it all on one screen, then have at it tbh.> Code only those things that your grandparents would have coded
Software has been around long enough that some people's grandparents were coding, but due to the limitations of many of the systems at the time, functional, simple programs were often the craziest they could get.
Still, Lisp was created in 1958 [0], so it's definitely likely some folks grandparents were programming in it :)
[0] https://en.wikipedia.org/wiki/Lisp_(programming_language)
Systemd has these stupid config files. And by stupid, I mean that literally. They replaced init files (with arguably too much logic) with these simplistic config files that have no logic available.
What ends up happening is you replace init files with nothing, and you have to push out any logic to an intermediate script or binary which just adds indirection.
The decoupling provides greater resiliency to change and thus doesn't add geometrically to the complexity of the code base, rather just linearly.
in my experience I've seen codebases that are entirely object oriented where we are writing methods, not functions, or codebases that use methods or functions as appropriate, and they also have done just fine long term.
How is this article making any real argument for the former and not the latter?
I would rephrase it as "FP is a better default". A big part of my thesis is that dogmas tend to have shortcomings, which contrasts with the stereotypical "FP is better" literature.
> in my experience I've seen codebases that are entirely object oriented where we are writing methods, not functions, or codebases that use methods or functions as appropriate
Using X "as appropriate" is one of the things I was hoping to encourage :)
As for "most codebases have a pure functional subset", perhaps what I should have said is "most projects' domains have a pure functional subset". The idea being that some slice of the business logic is naturally just deriving values from other values, and that if you isolate that substrate you get many of the benefits people talk about FP having (lack of sprawling side-effects, composability, easy parallelization, etc), without the more extreme costs like having to learn what an IO-Monad is
Also I think that the source code of his projects in Python pretty much validates the point of writing simple code. He has made great user-facing APIs (flask) but as soon you dive into the code base itself it's imo a rather dense and hairy mess of abstractions.
Don't just write pure functions. Write point free combinators.
Have you guys ever wondered why no matter how much care or planning you use to organize your code when you begin a project, some time down the line you will always encounter a situation where the organizational scheme you chose is less than ideal or even flat out wrong? It's a sort of inevitable technical debt that occurs.
The industry spends an endless amount of time debating and coming up with all kinds of solutions to deal with the above problem. First it was OOP, the latest is microservices.
The actual solution to the above problem is to use point free combinators as much as possible in your code.
I'm with you here...
> The actual solution to the above problem is to use point free combinators as much as possible in your code.
You lost me here. Perhaps if you're working in a problem space with high complexity, little ambiguity and hard performance requirements (fairly rare in my experience), you might get mileage here.
Otherwise, functional programming techniques are somewhat orthogonal to Conway's law. Point-free combinators don't stop new information about customers from completely altering your domain model, business logic and how your data is stored at rest.
I think it's helpful to realize that some of the root causes of bit-rot in a codebase are more closely tied to not fully knowing what was going to evolve into ahead of time, which in and of itself isn't a bad thing. However, it means that it's a failure mode that is independent and often out of the hands of the engineer writing the code -- functional programming idioms or not.
As most software engineers know, there's tons of examples where the main issue was mostly organizational issues preventing the programmer from simply removing/replacing/moving logic to fulfill the main objective. This is the "technical debt" I'm talking about.
In that case if all your logic was combinators (and thus dependency free) then all you need to do is move things around, pull things out and/or put things in like lego blocks.
The main reason why people can't move code around like lego blocks is because most logic contains dependencies or is tied to state. Combinators are never tied to state or anything and thus if all your code was made up of combinators you would have no issues in moving logic around. The problem of organizational technical debt is solved with combinators.
If you take it a step further and use the point free style, you are eliminating state all together further protecting your program from ever being dependent on state.
The logic is pretty sound though most people can't put the benefits of FP into purely logical terms. They only talk about why they like it qualitatively without ever pinpointing why it's truly better for design/organizational issues.
The problem is that the part of your program which processes state...is generally the useful part. This is part of the reason why I eventually came back down to earth after a couple of years of FP zealotry in my early career. I realized that it makes the easy parts easier. And there is something to be said about that -- there are a lot of codebases where just doing the table stakes refactoring that minimizes the surface area of stateful code does a ton to improve the codebase.
But in my experience, that's only table stakes. It doesn't make the hard parts (such as unfucking a broken data model and code + existing prod data which depends on those implicit assumptions) any easier. So it's a tool of limited use for most of the thorny issues I've come across in my career, across startups and BigCos.
I read the wiki and the Python example seems to suggest writing functions that take a single argument.
x = 1
addSomething(y) = y + x
The above is not a combinator. addSomething relies on the line x = 1 and is forever tied to it. You cannot reuse addSoemthing without moving x = 1 with it. Therefore addSomething is not modular. This is the root of organizational technical debt. When logic depends on external factors it cannot be reorganized or moved.This is also a big argument against OOP because OOP is basically the same exact thing with a bit of scope around it:
class B()
x = 1
addSomething(y) = y + x
divideSomething ...
b = 3
Now addSomething can never be used without taking x=1 and everything inside B with it. It is less modular as a result.A combinator is like this:
addSomething(x,y) = x + y
fully modular and not tied to state.The point free style is a bit long to explain. Another poster brought up readability and now I think I went too far with it as a recommendation, it's like going vegan basically if you employ that style. Just stick to combinators and you get 99% of the same benefits.
Suffice to say the point free style eliminates the usage of all variables in your code. You are building just pipelines of pure logic without any state.
When you get rid of state as much as possible, your logic will not have any dependencies on state, and thus will generally be free of technical debt caused by logic being tied to dependencies.
This dilemma has a name: The Expression Problem. A decent summary can be found here.
https://wiki.c2.com/?ExpressionProblem
Functional programming is an amazing paradigm for most domains. However, some domains will take a seasoned functional programmer and make them want to jump off a cliff. UI programming, game programming, and simulation programming are some examples where pure functional approaches have never made a dent, and for good reason.
You don't gain or lose state with classes alone. Your examples didn't remove any state. X is still there, its just not B.x.
What you're fighting against is side effects and reducing what is in scope at any given time. One could argue that the goal of classes is the same!
Sadly one can write terrible, leaky code in either style.
it comes from topology, no?
grok () {
grep -v DEBUG | sort -n | uniq | tail
}
Unlike a generic pure function, it forcibly abstracts away arguments. It's a bunch of other functions combined somehow, but it's impossible to know the type/structure/semantics of the input. And in most cases also of the output! Although it's less visible in my example.Debugging the point free style is different though as there are no points to put your breakpoint. Think of the identity function with a side effect as a replacement for print or breakpoints.
I think it's similar to the concept of Variadic functions(https://en.wikipedia.org/wiki/Variadic_function)
"Point-Free or Die: Tacit Programming in Haskell and Beyond" by Amar Shah
I would rename that video to "Tacit Programming: It's Not A Joke <everyone bursts into laughter>"
My point is, that the use of combinators and point free programming formally eliminates organizational technical debt. So for this specific issue, Joy should indeed be better by logic.
Although they are mostly syntactic, they hamper the readability of the resulting code.
Overall though this method basically solves the problem with technical debt I described above.
The root of all dependencies come from free variables. So if you get rid of free variables and turn your functions into combinators, then all your logic is modular.
If you get rid of all variables then all your code has to be combinators.
Perhaps the point free style goes to far in terms of readability. Maybe just switching to combinators is a good middle ground. In layman's terms for the readers who don't understand this means don't even use pure functions in classes. Just use functions.
... so you agree with the author of this post?
Also, seems like there is tech debt with point free, you just have it up front rather than putting it off until later.
I think the bigger question is what is X and is it definitively correct? Because the irony of a situation has nothing to do with how correct X is.
You’re right, everything I said is completely wrong. I’m not a biased person so I admit when I’m wrong.
Also note that this post is not sarcastic. I am 100% serious and being honest here. You are completely right. This is not a joke. It’s rare for people to do a 180 flip so I can see how this post can come off as sarcasm. I am not most people and this post is earnest.
IME, the point free style is aesthetic.
It's a forcing function to make your logic all combinators and not dependent on free variables.
Though I do agree with one replier. It does harm readability so now I'm thinking it may not be the best recommendation. Using combinators without the point free style is enough to actually fix the technical debt I'm talking about.
>Use the primitives that are there, when possible. Write what is simple, and natural, and human.
I agree with this very much, but most of this article doesn't support this statement. Let's start with the statement it is based on.
>Eat food. Not too much. Mostly plants.
Michael Pollan is great but the human way is definitely not what Michael Pollan suggests. No human tribe ate that way prior to agriculture, which happened relatively recently, and has greatly complicated things when it comes to our diet.
So, I'm in the "Eat a lot. Not too frequently. Mostly animals." camp because I believe that's what we'd have done as scavengers and later hunter-gatherers... and since we lost most of our digestive system because of the change in diet, we can no longer digest plants well and most importantly, we are no longer immune to plants toxins, which they use to protect themselves, and a lot of processing is required to get rid of the toxins (which is seen in various indigenous diets)... and still, it is never as good as animals when it comes to toxins and nutritional value. There are other considerations which may make eating more plants sound better but I have noticed that they're not well thought-through. Also, if I'm going to be conservative about one thing, it will definitely be food. We haven't evolved for 22 million years as hominids without certain adaptations to our diets. We can't arbitarily decide to change them without side effects.
Similarly, when it comes to programming, I'm in the "Write code. However much is needed. Whatever works for you." camp, the one that I made up just now and I invite others to join it.
Objects and classes are good analogies and work well for many use cases. Humans think object oriented programming makes a lot of sense because we already think in object oriented terms. A lot of software we use day-to-day are written like that and it has worked fine for a very long time. Same is true for patterns and frameworks built on top of them. They caught on because they resonate with human way of reasoning about things. They have their limitations though.
Similarly, functional programming has a simplicity to it which works great in many applications. When complexity grows, you have to get used to various other patterns and concepts to write real-world applications. Functional programming originates in mathematics, which is also very human... but as complexity grows, it's not as human as you'd like it to be. A lot of humans struggle with complicated functional programming code, which is why it is not as popular.
When it comes to programming, there are various useful theories and tricks you can learn and knowledge you can acquire... but ultimately you are responsible for collaborating with your peers and getting the work done. So, you should choose whatever programming paradigm, patterns, frameworks, abstractions make it easy to do so. There is no "one true way" to do things.
If you really enjoy the "one true way" idea and want to take it to the extremes for fun, feel free to do so. But otherwise, there's no reason to beat yourself for not using some "superior" design pattern or programming language or paradigm. A lot of these things are context-dependent. While understanding all the intricacies and benefits and tradeoffs can be very interesting, and it is in fact explored in academia, it has little real-world value, apart of entertainment, if you just care about getting things done.
I agree, but I wouldn't say people struggle with "functional programming code", they rather struggle with the concept in general. In that sense, functional programming is like higher mathematics: it's a great tool to solve many problems in a very efficient way, but it's also difficult to learn and everyone of us reaches a level where they can't advance anymore at some point. Some sooner and some later.
Have you read the seminal paper "Why Functional Programming Matters"? In it, it's argued -- quite successfully -- that FP is all about modularization and managing complexity. That is, that FP (and related techniques) is the way to go precisely in order to both modularize and glue the parts together, i.e. keep the complexity tractable.
write code, and then visualize it: https://www.visualsource.net
if it's too complex, simplify.
Sometimes an analogy is funny but that doesn't make it less wrong...
(Which is that you can get the most benefit from mainly adhering to a principle, while full adherence has intense costs)
My point not being to redirect your snark back at you. My point being, sometimes stating the obvious can be useful. I don't think that devalues an article.
It has zero information. It’s a paean to smug, unconsidered mediocrity.
Not only is the premise of the tenuous analogy likely completely wrong (the preponderance of evidence suggests eating “mostly plants” is, in fact, anywhere from bad to terrible for you, depending on your choice of plants), but the way in which it’s presented is absurd as well; paying lip service to “incontrovertible scientific research” and then writing an article completely free of any references to such research.
The only thing of value I took away from this article is that the author posted it 3 times this week, and it only got popular on the 3rd try. So if you want to get something to the front page of HN, post it a bunch of times!
> If a story has not had significant attention in the last year or so, a small number of reposts is ok. Otherwise we bury reposts as duplicates.
https://news.ycombinator.com/newsfaq.html
Usually you have to get lucky with the right time of day for something to actually take off the way it would otherwise (before it falls too far down "new"). Sometimes the staff will even email you asking if you can repost a link that "should have" taken off, but didn't because of bad timing. Personally I limit myself to three tries on posts I've spent time writing that haven't yet gotten out of the single digits.
Where did you get that information, foster farms? Or are you defining "mostly plants" to be a diet that consists solely of green skittles?