69 points · by open-source-ux · 9y ago · 88 comments
Or are you using an FP or OOP language but rarely use the FP or OOP features? If so, why?
OO: Only rarely, and only where it really makes sense. Most programs I work on are not complex enough to justify the overhead (boilerplate, cognitive).
FP: I use this more, but again, only when I can really justify the added cognitive overhead.
You'll notice the two references to cognitive overhead: I have adapted the "write for a 6th grade level" idiom into programming. I want as many people to be able to pick up the code and modify it as possibly can. I work with everything from interns to decades plus veterans, and my code must be grok-able by both. Pure FP tends to confuse interns, and veterans have a tendency to hate the layers and layers of indirection and abstraction OO brings into a program.
Normal and boring old "an imperative main method with functions" tends to be the least offensive and most understandable to all parties. Compromise r fun.
I generally agree with "use only as much cognitive overhead as needed to get the job done" ( I'm enjoying that term ) - but it seems like a slippery slope that could slowly bring everyones abilities down to the least capable developer.
To me, it's a bit like telling a person how to get from point A to point B by telling them when, how hard, and for how long to step on the gas and what angles to put the steering wheel at. Sure, that might work to get someone out the driveway, but good luck getting to the grocery store that way.
I will genuinely never understand the go philosophy that "excessive" abstraction is bad, with no attempt to justify why current levels of abstraction — which are charitably hundreds of times more complicated than the difference between, say, go and ruby — are good, right, and just. Everything we do on a computer from processing to memory access to networked communications to rendering to handling input to relational data modeling to… anything is dozens of layers away from what's actually happening. But somehow right now we're at the optimal level of abstraction and any more would just be too much. Okay.
It seems to me that Go is part of a reaction from people who are not happy with current levels of abstraction.
Abstraction in itself is a good thing. I just think of it as "compression". We have to express solutions to problems in the shortest way possible, otherwise they become unmaintainable.
What most people fail to see that a dead simple language like C provides with all of the tools to solve many problems with good or optimal abstraction. And if you add abstraction like OO and implicit memory management to solutions for many complex or performance-oriented problem domains, these solutions become effectively non-solutions. Because in these problem domains, decisions about memory allocation or data organisation are part of the solution.
I think falcolas's philosophy is spot on - treat most problems plainly and simply. In the rare event a genuinely difficult problem arises, use your tools to get it done right.
No, that's almost exactly right. In my experience designing, building, inheriting, and maintaining systems that in some cases predate the dotcom boom, and in others need to run invisibly for just as long into the future, it's the simplest design that's the best design (but, as they say, no simpler).
I'm not talking about avoiding useful language features because nobody wants to learn them. I'm talking about the structure of the system itself. Minimize layers, minimize context, keep things as linear as possible. Don't use polymorphism just because you can, don't use functional tricks that obscure rather than enlighten the flow, don't make version zero an SOA, etc.
“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”
The common way to do this in OO (and yes this very much includes Go, whose standard library is incredibly OO) is to have C depend on an interface instead of a concrete X. Then you have full freedom to test C very robustly and at different abstraction levels.
So how do you cope with this in your code? "Imperative main method with functions" doesn't sound like it leaves room for proper testing, unless the code doesn't do much.
I will point you to this interview where Joe Armstrong describes Erlang as perhaps the only Object Oriented language (countering his earlier, less considered view that OO sucks): https://www.infoq.com/interviews/johnson-armstrong-oop
Proper testing is exercising all the functionality via the UI and understanding your program and it's use cases. If you're doing end to end testing, the codes architecture does not matter because your program is basically a black box.
I don't embrace the FP style either because while I generally limit mutation (`final` almost everywhere), I use mutation where it leads to code that is easy to understand, which would be exceedingly "clever" in FP style.
It's simpler, more flexible, less verbose and easier to follow than a full-on OO style. A great example is the early calculatoe e.g. in ed 2 vs 3 of the compiler "Dragon" book: older uses C, later uses OO java... and it's so much worse.
However, OO is great for wrapping up modules of functionality for which you've understood and settled on an informed architecture (or you just need to sweep repetitive boilerplate away).
I think inheritance is just about completely useless (but not quite completely), and (java) interfaces are great - if you have more than one implementation.
Big, multi-person projects are a different story.
I don't use much fp-style, except where recursion is natural (e.g. parser combinators); or for plug-in functions (hardly fp though).
I came to the realization I didn't even need a lot of the language features for what I was doing and decided to switch it to C to not have to maintain various versions of the library and it was a steep learning curve but I've come to really enjoy the simplicity but powerful capabilities of C.
I do some microcontroller programming, and it's usually straight C. The hardware registers are all global, and their contents change based on external stimuli, so that kind of rules out the idea of stateless programming.
The earlier versions of Visual Basic had kind of a compromise, where it came with a lot of pre-made objects, and you could create objects if you got the special kit, but the casual programmer was only expected to use objects. I kind of adhere to that idea when I write in OO languages such as Python.
I use OO sparingly when programming Python, often to encapsulate hardware functionality, but then use those objects within programs that still look procedural.
I avoid using inheritance, mainly because I don't trust myself to do it in a maintainable way.
I've tried functional programming in Rust, but it's not going well.[1] I don't like the "x.and_then(|foo|).if_even(|bar|).except_on_alternate_tuesdays(|baz|)" style. Rolling your own control structures is not good for readability.
[1] https://github.com/John-Nagle/rust-rssclient/blob/master/src...
2. "Grand scale Functional characteristics" - exposed API should try and have "referential transparency" and "composability" (you can write systems with "functional properties" in languages like PHP just fine btw.)... find not much benefit from "small scale / low level" FP.
3. Wrap stateful algorithms & other code rich in mutable variables in either (a) referentiaally transparent functions or (b) shallow objects that make it obvious how and when state changes.
4. Avoid the "islands of functional purity in a sea of objects" pattern like the plague - it results in large scale intellectual masturbation at the small scale, and incomprehensible systems at a large scale, your monadic fantasy is useless when stuck inside the method of a 8-levels-inherited monster object... functional is important on a whole-system level, a 10 line method is easy to understand even if it mutates local variables all over the place
In theory FP would be great at all scales when coupled with a good type system... but I've never got to work on projects in languages like Haskell or Scala and I'm not sure I could handle the cognitive overhead of it.
Oh, and don't use Exceptions, ever!
I tend to see programming as writing. The style of writing depends very much on the context and the audience.
I lean towards "basic" FP (immutability/pure functions/composition) but none of the heavy category theory concepts (anything with types that are too complex). Its mostly procedural with a hint of FP.
Most things should be functions, most higher level things (classes/packages) should be primarily ways to bundle related functions.
Prefer to maintain a clear separation between data & operations on data or structures imposed on top of it. I dislike the OOP approach of bundling data + transformations together. Also dislike inheritance because that is baking one particular structure into the definition of data.
It's almost a weird paradox: OO/FP focuses on reusing code yet imperative/procedural code (ie: C) does not reuse code but is itself the most reusable code. You can't have your cake and eat it too I guess.
I still like to program in C and make my own thin abstractions / "runtime", tailored to the task at hand, and using only minimal dependencies. That way it's much easier to have only essential dependencies, not accidental ones. It's such a relief seeing a couple thousand lines of cleanly modularized C code compile almost instantly.
For example, by putting a char * into a struct definition a dependency on a more clever string type can be avoided. All that it takes is delegating memory management decisions to another place. Which is actually very beneficial, since most code shouldn't be concerned with mutation or especially allocation.
Other than that, I use Mathematica quite a bit for playing around with ideas. I've tried sympy, and I hoped to switch to it but it's just not as fluid and integrated.
If I'm coding for fun I tend to come back to FP and OO, I'll use either Haskell, Python or CL. I've been meaning to make something using Rust for a while. I'm planning on building a fermentation chamber (and perhaps a kegerator depending on my budget) for homebrewing at some point over the next year; I'm thinking that I might use Rust for the temperature controller.
For side projects and for small Python code at work recently I have been applying data-oriented programming patterns. So far they worked surprisingly well.
Perhaps this is because one have an overview of the whole program state that is not hidden behind multiple layers of OOP abstractions and there is no mix between data and code, as happens with functional style.
While I sometimes teach programming in C# and C++, my main responsibility is our Algorithms and Data Structures courses, for which we've kept using plain old C. From a teaching perspective, it's a great language for teaching fundamental algorithms and data structures. The students are also able to leverage that work into later courses on microcontrollers and embedded systems.
For my own work, I tend to mostly be writing code for somewhat idiosyncratic one-off data processing (I'm currently working on a genetic algorithm for class, student and professor scheduling) or embedded systems. The former I generally work in Common Lisp (SBCL)(although I do keep promising myself to learn enough Clojure to see if I prefer it). This is probably because of the way I think, as I tend to be comfortable building a system from bottom up, moving the data representation from the general facts I start with toward a representation that meets my needs. I actually came to CL pretty late, about a dozen years ago, but it really seems to suit me, possibly because I'm still primarily a command-line person. Being an emacs user certainly was a strong influence, too, although I don't hack elisp very much. I should add that I do often use CLOS, especially when working with more structured data, so I do use some OO, although it's mostly just to provide a more convenient interface to some complicated data type.
For embedded development, I still work almost exclusively in assembler or C, with less assembler every year. I tend to be working on pretty low-powered special-purpose devices, so code reuse and robust interfaces don't add much value, but close control of exactly what the hardware is doing does. This was normal in that domain until comparitively recently, but the power of even cheap devices and the availability of libraries mean that there are a lot more options. I expect that I'll continue to work mostly in C out of familiarity and inertia, but I will admit to having recently bought some Lua books with the intent of trying it with ESP8266.
Was this written in a book somewhere? I keep hearing it from people, but nobody's able to really explain why. OO is terrible for GUIs IMHO.
My problem with non OOP in a language like python is that I have trouble scaling large apps and interacting with large libraries, because without type information enforced by the compiler, there is too much left to my own working memory, compared to a strongly types language built around OOP.
What's more, without rigid encapsulation I feel im exposed to an excess of internal code any time I need to look up a parameter or kwarg. Never mind the trouble of navigating five files feel through aliased method names...
As examples, consider matplotlib or tensorflow. Extremely easy to use once you know where everything is and what params to pass where, but I can't help but feel that it would be easier with stronger OOP.
I feel like I have not yet learned to think in a pythonic manner, but after a few years I'm not sure if I every well. As an aside, I just dont understand how python doesn't cause problems for devs when it scales...
We have a proprietary database called LogicBlox, that allows us to push all business logic down to the database layer, and almost entirely avoid having a service layer, or at least a very lean one. This allows us to address efficiency problems purely by optimizing database joins between predicates (tables).
Our data is highly normalized (6NF).
For data iteration, i prefer functional style (even in python, even after years list comprehension just feels so wrong).
I kinda tend to start with a OOP style for the data models and a small shake of FP for the functions but change this according to my needs.
There is no one true style for programming, there is only tools for a task and using the best or good enough tool is the only important thing. (Though sometimes it's fun to use the wrong tool and see how it goes)
That's probably not the right question though. If we're just focusing on implementation, using the right data structures for the problem would have to be job #1.
Screw that up, and everything else (APIs, UIs, enhancements, training, you name it) is going to be an uphill climb.
Neither style especially dominates, and most languages have enough support for both even if the tilt one way or the other. Most people pigeon whole other styles into one or the other, sometimes ambiguously (e.g. actors get counted as both OOP and FP, relational also has that problem).
Try to use FP most of the time, but sometimes a little mutation seems easier to grasp.
Rarely is anything complicated enough to abstract without making the code longer and more complex. Anybody can follow imperative code. OO is more difficult.
OOP as a technique is fine, but any language disallowing freestanding functions is perverted, I tells ya.
The last part is pretty important because properly testing software that talks to an external service is essentially impossible. Either you test in an integration setting where repeatable results are difficult to maintain, or you mock out your services and then you're testing your opinions against other opinions.
Here's an example of how I push this style to typescript, heavily redacted to remove company-specific marks, names and strutures: (this code is simple by intention; we may have a jr dev on the team soon and an excessive number of generator abstractions could help with this process but would cause readability issues).
function splitOrders(orders: e.OrderResult[]): {[key:string]: e.OrderResult[]} {
return orders.reduce(
(accum, borders) => {
// I sure would love a better idiom for non-destructive map updates but
// this isn't my primary language. Suggestions welcome!
let next = {...accum};
next[borders.datatype] = (next[borders.datatype] || []).concat([borders])
return next
}, {})
}
export async function undoifyUserProcess(env: any,
tolkien: client.tolkien,
token: client.APIToken,
spotData: IThingData): Promise<any> {
const legendaryCustomer = await e.getCustomerById(env, spotData.customer_id);
const orderResults = await e.findThingContractDetails(env, +spotData.spot_id);
const workSchedule = splitOrders(orderResults);
let btasks = scheduler.undoifyCustomerFromOrders(
env,
token,
{ key: legendaryCustomer.userKey },
workSchedule['newstyle'].map((wi => wi.bigId)));
let ltasks = (workSchedule['legacy'] || []).map(async (workItem) => {
// .. process elided but...
const nodeKey, groupKey = ["things", "were", "removed"];
const customerEmail = legendaryCustomer.some_field + "removed work"
// Factoring this out would have introduced a function with a bunch of parameters
// or state that is only synthesized here, so we left it embedded & closed over.
try {
return await omg.undoifyUserWithTagGroup(env, tolkien, customerEmail, nodeKey, groupKey);
} catch(e) {
console.log(`... malformed database call your mom for help ...`);
throw e;
}
})
try {
const work: Promise<any>[] = [btasks, ...ltasks];
const result = await Promise.all(work);
return await e.recordUndoifyingThing(env, +spotData.spot_id);
} catch(e) {
console.log(`...`);
}
}
If a language can't express a decently abstract functional style, I do my best to avoid it. Still, I've had to write a bit of Golang at my current job despite its utter lack of descriptive capabilities. It's poignantly frustrating to deal with, but a good reminder of how bad life used to be for programmers.I'm curious what you mean. Mocking out the dependencies of a piece of code allows you to test that code exhaustively (for every range of possible inputs) if you choose. Even when that's not practical (probably most of the time), it allows you to do your best. It gives you the hooks to simulate any range of behavior.
and maximizing the opportunity for correctness.
The last part is pretty important because properly testing software that talks to an external service is essentially impossible
It sounds like you're just trying your best to write correct code and then hoping for the best? This absolutely will not scale, and it sounds downright frivolous.
Still, I would love to know more about where you're coming from. Do you do anything to ensure correctness aside from maximizing your hope of writing it in the first place?
> Mocking out the dependencies of a piece of code allows you to test that code exhaustively (for every range of possible inputs) if you choose. Even when that's not practical (probably most of the time), it allows you to do your best. It gives you the hooks to simulate any range of behavior.
It lets you mock anything at all, which is not what you want to mock. You want to mock the service (and in a microservices architecture, its interplay with dependencies).
If you can encode those into a series of constant replies? Good, but you'd better be doing something like FSharp's type providers or Facebook/Marlow's Haxl where you capture real traffic off the wire, otherwise all you've done is inject more opinion and conjecture into your tests and confuse that with correctness.
Outside of a very small number of specific methodologies, I think our industry is at mostly a loss for how to test microservices.
> This absolutely will not scale, and it sounds downright frivolous.
It doesn't scale with junior engineers. But neither does unit testing, which is more of the same "I think these tests and we try them and pretend that's test coverage because this line of code was touched" which is demonstrably false.
In typescript, I try to do queue-based architectures with full docker stack simulation. People like to call these "integration" tests, but I consider them unit tests for impure code.
In a language that lets me do pure/impure effect separation even in a communal setting, I tend to use quickcheck for the pure parts and hand-test the impure parts if an environment exists. When I get to use Haxl, I used their caching features to preload responses and my code didn't even know it was being tested, which was great.
Also, in Haskell, I'll sometimes use MonadMock but only if I can grab raw source response from APIs (or of course I need to do something like fix time or random numbers).
But I really try not to waste my time in the futile tarpit that is unit testing anymore. It's sort of the pop quiz mentality applied to software engineering and all it does is provide false confidence that code is "tested" when the quality of the output still varies radically on the discipline of the developer.
When I _do_ go back to Ruby or untyped javascript, I do end up writing unit tests. But they're mostly to capture scope around components to ease refactoring and make requirements explicit; something every language should have.
Sorry for being so frank, but you seemed like you wanted a bigger discussion. I think the industry has collectively decided to freeze all interest in any technology conceived after 2007 and it bugs me.
(accum, borders) => ({
...accum,
[borders.datatype]: (accum[borders.datatype] || []).concat([borders])
}, {})
although it's a little codegolfy and I'd personally write it more like this: (accum, borders) => {
const datatype = accum[borders.datatype] || [];
datatype.push(borders);
return {
...accum,
[borders.datatype]: datatype,
};
}, {})Nice point on the first part though.
(accum, borders) => ({
...accum,
[borders.datatype]: [...(accum[borders.datatype] || []), borders]
}, {})
although it's essentially concat(). const x = {};
x.a = 123;
You're not changing x, you're changing a property of the object it points to.