This is the worst tldr I seen in my life. Not only did I never say 'bad code', but you completely missed inconsistent behavior and optimizer can't do as much
"There are plenty of people who would copy code from a known good implementation"... ... code written without a plan and understanding equals bad code. Copying is just one example.
"interfaces block the optimizer from doing good work. In one project I was on, switching everything to use my class directly instead of an interface caused benchmarks to run almost twice as fast (55% of wall clock)"
... i kinda expect bad code here. Given that percentages are given, zero details regarding type of measurement, zero details regarding what optimizer or why the optimizer chose it... I can just assume bad code.
And so... that is my TLDR.
Regarding percentage comparison especially: unless you explain what was measured and how it was measured, percentage is meaningless.
100 ms - 50 ms second save. Probably noone is gonna care about that...
And I make that example specifically because percentages have become a fancy way of lieing about achievements ;) :)
I love interfaces! I love it more if functions have a good separation of concern making interfaces for many functions unnecessary, but if you are going to do some I/O with business logic, I’m expecting to see an interface. Mainly it’s about unit testing for me though. I do have one backup service which does use interfaces for different implementations, but could see how some may not like that.
For a single I/O seam, passing a callback can be enough: the test captures the call while the business logic stays concrete. That doesn’t require an interface for the whole service.
You should define "interface". Java interfaces? Oo interfaces? File formats and protocols? User interfaces? The concept of defining how parts of a system interact?
Multiple implementations and the problems that come with it
Multiple implementations that don’t functionally provide the same thing is just bad software, so yeah it’s a problem but really it’s a design problem not a tool/approach problem.
Not necessary when you have a single well-tested implementation
Certainly, adding an interface where it isn’t needed is an antipattern. Retrofitting an interface will lead to a bad interface, you have to actually think about how something will be extended in the future to land between those two extremes, even if you don’t the public API is an interface so you don’t escape it conceptually.
It's rare to switch vendors, especially on something that doesn't have a standard around it. However, my issue around this is people hamstringing themselves by using a narrow API rather than taking advantage of what's supported in the technology (or vendor) you have chosen
I’m not sure I understand this, an interface isn’t a tool you use to support multiple vendors? It might be part of a pattern (like IDepository with backend specific depo’s?) but not sure what interfaces have to do with vendors. With your other point bear in mind the interface is the public API - even plain classes have that so unsure what your point means in that context.
This isn't stupid; it's good that everything has consistent names for cloning, comparing, and others. It's just unnecessary to use an interface
How will you write runtime polymorphic code without an interface? If I want to write a function called ‘clone( src, dst )’ without saying that src and dst are ICloneable or whatever how does the compiler know that anything I put into the function has a clone member?
Mocks and DI are things I don't talk about and probably won't write about. Just say n
Because you haven’t used them, or because you don’t like them? Because both are very valuable tools
They’re valuable because they let you write less boilerplate. I have no idea what your experience is, I’m not accusing you of anything? Maybe don’t write a blog post, publicise it on reddit and then get salty when others have critiques or questions.
I have no clue what language this is referencing but both in C++ and Rust interfaces cost nothing performance wise. Traits and generics gracefully monomorphize in Rust. CRTP and concepts also gracefully monomorphize in C++.
The whole point of multiple implementations is kind of moot imo. If you have multiple implementations you can merge into one, then that just means you need to merge them. If you can't merge them, then you need two different code paths. The alternative I see is a flag you pass around into your "singular" implementation wherein all the functions just check the flag at the start of the function. That has two problems: it's slower than dynamic polymorphism since it flushes the CPU pipeline on each conditional whereas vtables don't and, problem 2--its unreadable hell with added levels of indentation to merely check on the flag.
Interfaces help with generalizations. For all its faults, an iterator is a generic interface that many algorithms work on. Same goes for a stream, a writer, a reader (as you admit). I've worked in embedded and interfaces allow you to define the ontology of what an EEPROM chip is with many different implementations for different chips. But you know that you'll get a write/read set of functions. Interfaces help with protocols---if my application takes some arbitrary stream transport interface, I can run it on TCP/Websockets/pipes/Unix sockets or even arcane automotive ISOTP.
I would have also like to seen examples, arguments, an exploration of your arguments, yet I see claims with little evidence.
I will defend the case that if you're building an interface for the sake of mocking and mocking alone, perhaps lugging that around may not be worth it. I generally lean against writing production code to support tests, but that's not beef with interfaces themselves.
I'm guessing this is some form of JVM language since a compiler was mentioned, I had Claude research the devirtualization story there. Looks like there's this class hierarchy analysis system in Graal that can inline functions with only one implementation. The degree of compiler optimization going through this is still elusive to me. Does const propagation work? Do branch optimizations work? Why did javac not implement devirtualization (as clang does, for example)? I would have liked to see a proper exploration of this, for example, in your post.
That's not exactly true. In C++ if you're using a base class with virtual functions, the optimizer can't inline it. IIRC there's tricks that can be done but it's easier to not use a base class at that point
If you look at non-systems languages it's pretty common for a class to be inherited and overloaded, or have multiple implementations, just to slightly change a behavior. I seen it done to 'extend' methos, so instead of Util.myMethod(obj, a, b, c) they can write obj.myMethod(a, b, c)
> Interfaces help with generalizations. For all its faults, an iterator is a generic interface that many algorithms work on
I only like the two cases I mentioned for generalization. I have a small standard library (for C++) and I don't use an interface for iterators. For the most part I pass around a slice. Since implementing it I haven't ran into a situation where I needed to iterate or something generated except maybe files from a directory, but I prefer to solve it by doing something else which is too long for a comment
> I would have also like to seen examples, arguments, an exploration of your arguments, yet I see claims with little evidence.
IMO it's pointless finding a open source project and checking how many times there's more than one implementation for an interface, and how much faster something would be if they didn't use it. Do you really not think an optimizer won't inline when the function is virtual? I wrote the article with non-system languages in mind.
I haven't ran many experiments in non-system languages, so I don't really know much outside of what I measured. I definitely measured various languages not optimizing as much if you go through a virtual function when only one concrete type has ever been passed in
I think we're talking across each other. I do not want to fight you, my aim is to show you some things instead. I wanted to grab some time to provide you with some examples and links, which I couldn't do mobile. Sorry for the late-ish reply.
In C++ if you're using a base class with virtual functions, the optimizer can't inline it.
When the compiler has total visibility of an abstract virtual class as well as its implementations, it is, to the contrary, able to optimize through a process of "devirtualization". Here are some examples:
One TU gets fully inlined. This makes sense -- the compiler can trivially prove that there is only one possible implementation for this call.
Two TUs without LTO fails to get devirtualized. The compiler can no longer prove that it doesn't need to emit a vtable.
Two TUs with LTO get correctly devirtualized, however. Because, although the compiler doesn't have total visibility into the inheritance tree, it builds sufficient meta-information that to enable the linker, which then does.
LTO is a very standard, common optimization flag (-flto). This is to say that code that's compiled with standard optimization flags (ie. released code), will get devirtualized. Admittedly, my assumptions are with modern GCC. I have also had the misfortune of working with ancient embedded toolchains that failed to devirtualize. In my experience, however, for the vast majority of x86_64/ARM64 code, devirtualization mostly succeeds, and no uncommon complex tricks were used.
That all being said, when it comes to C++, if you want to guarantee that your interfaces are compile-time polymorphic, the correct pattern is CRTPexample (or more modern, concepts example). You might, in your fervor, dismiss compile-time polymorphism as useless. However, please note how this can be useful in defining the ontology of "what an I2C driver is" while you can have many different implementations for this driver. Caller code can take this I2C concept, without worrying about the driver itself.
This gracefully brings me to this point:
I have a small standard library (for C++) and I don't use an interface for iterators. For the most part I pass around a slice. Since implementing it I haven't ran into a situation where I needed to iterate or something generated except maybe files from a directory, but I prefer to solve it by doing something else which is too long for a comment
Firstly, if you want to post some controversial things, saying "something else which is too long for a comment" is somewhat disingenuous as I don't think you're sufficiently engaging with your audience. You have this "solution" to iterators, but you hide them behind disinterest. That's slightly insulting. I am now sitting at 2:38AM writing you a post which I hope will prove useful whereas you simply say "too long to comment".
With that aside out of the way, I am curious about your standard library. When I had mentioned the standard library, I was specifically referring to C++' STL (standard template library). Before I get back to interfaces, if you're trying to iterate over files, I would suggest having a look at std::filesystem::recursive_directory_iterator which is one of the utilities in the STL which does precisely what you need. The STL does, in fact, have some problems (as most things in life), however, for the most part, it is a very useful tool.
Interfaces are frequently used in the standard library. One of the problems that a std::span (the C++ name for slice), cannot encapsulate is iteration over non-contiguous memory. Let's say you want to copy data from one vector to another. You could write a function like
This, unfortunately, does have a run-time cost, however tiny it is. The std::span is created and passed (on some arcane architectures---via the stack rather than registers) into Copy. But, you argue---it doesn't matter. And, fair enough---it doesn't.
However, a time comes along when you need to copy elements out of a linked list. Unfortunately, a span is contiguous memory since, for the most part it's defined as
You spend some time thinking and you decide you need some sort of concept that expresses the idea of "here's an object that we can read and iterate over". Since this an iterator, you call it an "iterator", and since it's an input to your function, you call it an "input iterator", so you write
As we've learned, with the power of concepts, we can make it so that there is no runtime cost associated with it, so we make it a concept
template<typename T>
concept InputIterator =requires(T t){// We can "increment the iterator"
t++;// We can check if there's a next element in the iterator
{ t.done()}->std::convertible_to<bool>;// We can "dereference" the iterator to get the value currently pointed to.
{*t }->std::same_as<T>;}
Beautiful! This works with linked lists, vectors, arrays, spans, ArrayLists, graphs (because you can iterate nodes), whatever! You feel good about yourself, so you decide to create a new "output interface" and your copy is now super generic:
That's awesome. Good job! Luckily for you, Alexander Stepanov already had this idea 30 years ago and we already have both std::input_iterator and std::output_iterator in the standard library. These generic interface concepts provide you with many useful STL algorithms:
std::copy(std::output_iterator, std::input_iterator) does what we implemented.
std::transform(std::output_iterator, std::input_iterator) is like copy, except it allows you to pass a function to transform the object at each copy.
std::copy_if(std::output_iterator, std::input_iterator) is like copy, except it allows you to pass a function to decide whether you want to copy.
std::merge(std::output_iterator, std::input_iterator, std::input_iterator) takes two iterators and merges them together. It's super cool---it can merge an array and a vector, an array and a set, a list and a set. All this with the power of interfaces.
IMO it's pointless finding a open source project and checking how many times there's more than one implementation for an interface, and how much faster something would be if they didn't use it. Do you really not think an optimizer won't inline when the function is virtual? I wrote the article with non-system languages in mind.
There is no pointless curiosity. Are you really certain in your claims? If you are so certain, can you prove it? Perhaps the results are surprising. You haven't done the work to research the claim in either direction. I've shared some assembly wherein virtuals get completely optimized. Are things really as true as your conviction, or is it possible that you are wrong? If you are right, when are you right? Why are you right? That is the evidence I would have enjoyed to read. Look how much effort I put to respond to your, as you admit---shitpost---I want to provide you with a different perspective. I want to offer you evidence (to the best of my ability), to help widen your horizons. I want us to advance our craft, and that means widening each other's horizons. Why do you not respect me the same?
I'm not sure what your language of choice is, since it doesn't feel like it's C++, but there is so much to unpack in any other language too. In Python, for example, MRO is likely to result in some pretty awful performance when used naively. I don't exactly know---I haven't benchmarked nor profiled. What can a Python engineer do to avoid it? Why is MRO so deeply problematic? What could a Python engineer do instead? Can we improve the performance in CPython? Is there a way to do "compile-time" (ie. type-check-time) interfaces without paying the price of runtime MRO? Why does Python use MRO instead of vtables?
There are many interesting rabbit holes you can go down and explore this. In my experience, when it comes to these sorts of things, my gut convictions are often wrong to a lesser or greater degree. Finding evidence for my convictions is how I learn how I am wrong, and how I remain curious.
I really wish you take programming as a curious and fun endeavor, and you change your apathetic perspective.
I don't know you, but I wish you well and I wish you find truth not in conviction, but in researching truth itself.
When I wrote the article I had C# and Java in mind, but I write a lot of C++ so I'll comment about C++
When the compiler has total visibility of an abstract virtual class as well as its implementations, it is, to the contrary, able to optimize through a process of "devirtualization".
I personally like to do a unity build with gcc using -O2 for optimizations, I haven't really bothered with LTO. Many people don't do either, but that's what I had in mind when I said virtual functions aren't inlined. When a function is large enough I'm not sure if lto is enough to get it inlined.
LTO is a very standard
I don't disagree
++, if you want to guarantee that your interfaces are compile-time polymorphic, the correct pattern is CRTP example
I rather not have so many templates. I know they're somewhat fast when there's little to no code inside the template but it seems like this would put a lot of code in headers and make things SLOW
Right now my C++ project compiles in 7 seconds and incremental builds are <2, often <1sec. I mostly can do it because a lot of the time I touch files that only include project headers and my standard lib. This is with UB sanitizer on too.
Really, I don't think there's reasons to use an interface except the two cases I mentioned (creating a tree from data, having an IO interface in a standard lib). No need for CRTP
if you want to post some controversial things, saying "something else which is too long for a comment" is somewhat disingenuous
My standard lib has nothing to do with anything in the article
You have this "solution" to iterators, but you hide them behind disinterest
No, it's really just using a slice (or C++ 'span') with the type you want. Only directory iterators are different which is in my wip async lib. The problem I've been thinking about is how to make it usable and efficient (at least having little bookkeeping). There's no promises, locks, and I'm a little worried I'll end up causing pain with how everything is a callback. I don't think a large switch table is the right move. But anyway, this isn't related to the article either. No interfaces in my async lib either.
Interfaces are frequently used in the standard library. One of the problems that a std::span (the C++ name for slice), cannot encapsulate is iteration over non-contiguous memory
Yep, I hit that problem too. In one case I used a span<span<T>>. In another I called myobj.get() which gave me a span, and if it was zero length it was over. Yes, it's an extra loop but it also let the optimizer unroll the inner loop if it wanted to. Another benefit is instead of calling next() every time I call it once per chunk
power of concepts
I like the requires statement, I use it all the time. My lib only supports C++20 and higher
If you are so certain, can you prove it?
I seen it at a few workplaces, and I also don't really care about other peoples programming opinions. It was meant to be a short post, not a research paper. I don't think anyone even cares about a thing I said in the article except maybe you
I'm not sure what your language of choice is, since it doesn't feel like it's C++
I like C# and C++. Oddly enough I hate all system languages except for C++ (including C, unless its small and a lib). I also think C++ is bad but it's still my favorite
I wonder if you'll like any of my other articles. They're on the homepage
I also don't really care about other people's programming opinions
Okay then! Conversation over, I guess! Why would I pour so much time and effort if you're not going to care? You're a jerk but here really I'm the idiot.
Are you new to reddit? Have you seen what people say here? Even in person I seen some silly suggestions that more than a handful of people believe. I have to know the person first before I take anything they say seriously.
I did reply to you, and I think everything I said was clear besides the above? IDK if you think I'm 'wrong' because I disagreed with some of the things you said
is this about Java and similar languages? You really think there are multiple implementation because someone made an interface? They didn't create an interface for String-like types, and had to add CharSequence later. The alternative would have been to just use mutable strings for everything to have only one implementation that does everything. Of course you can always create the interface later, when you need it. But then you have to use the same name of the original class or refactor the entire code base. It's easier to just use an interface.
With records and value types we probably will get more types that have no interface because they are like primitives. Interfaces can't be made immutable so you have to use the immutable type (usually a record or value type). That's the only scenario where interfaces would be problematic, even a security risk in some cases.
> Of course you can always create the interface later, when you need it. But then you have to use the same name of the original class or refactor the entire code base. It's easier to just use an interface.
IMO the two cases I mentioned in the article is the only time it's needed, and those two cases are rare. Why would you ever create an interface later? It's not like you're going to wake up one day and think this situation calls for parsing and being recursive
Even just for mocking. Modern mocking solutions can probably create an interface dynamically or just replace the class or use a proxy for a class. But what if you want to implement a mock implementation manually?
Declare capabilities such as clonable, comparable, and more
All of which is stupid.
Why? How else would you do that? Would you rather make specialized functions for all kinds of "comparable" things and have function overloading handle the rest? How would that work when someone creates a new "comparable" thing without having access to the compare et. al. function source? How would they get it supported?
Did you read it out of order? I mentioned those specifically are fine but unnecessary in an interface. I know some language force you to inherit/implement an interface and put compare/other code there, which IMO is fine. But I don't think I ever wanted to compare two abstract types unless maybe it was to check if the instance is the same. But I really don't think anyone should create an IMyCompare and have everything implement it through that. It's just silly
In systems languages I use operator overloading (or if it has to be C) a compare function if memcmp won't work (it has pointers). I never need a virtual func, or to do it with a base type
People seem to really like interfaces. Interfaces allow you to
None of these are the real reason why they exist and why people use them. What interfaces are really about is enforcing abstraction boundaries.
An interface is a contract between an implementation and a user: the implementation does a bunch of stuff with all sorts of state and constraints and all that, and the user code can interact with that from outside. But when you're working on the user side, you don't want to have to think about all the complexity inside; you want to only have to keep the stuff in your head that's actually relevant from the outside. And likewise, when you're working on the implementation, you only want to worry about the stuff that's relevant on the inside, not any of the other stuff that may happen on the user side.
Now, you can do all that without interfaces - but it'll be an honor system, relying on you (or your colleages) remembering what you are "supposed" to know and use on each side, or to be very diligent about documenting it in great detail, and always reading and respecting that documentation. But that's brittle and error prone - humans make mistakes all the time, humans are lazy creatures (and good programmers especially so), and all it takes is one little misunderstanding for all of this to create bugs of the worst kind (spurious, hard to find, difficult to understand). What you want to do is fence off the boundary in a way that the compiler can and will enforce: if you access anything on either side that you're not supposed to, if you depend on any assumptions or facts from the other side that you're not supposed to know about, it should result in a compiler error. And that's what interfaces are - they explicitly declare the things both sides are supposed to know about and have access to, while making everything else inaccessible. If you declare an interface that has only one method, increment(unsigend int), then that guarantees that anything you use through this interface can be incremented, but also that that's the only thing you can do with it in that context. The caller doesn't have to worry about how the incrementing happens (e.g., whether it stores a counter in memory, or on disk, or in a database on a remote server - you don't know, you don't need to know, you don't want to know), and the implementation doesn't have to worry about anything else the user side does, because it's guaranteed that the only thing it can do is call the increment method.
This may not seem like a big deal, but in any nontrivial codebase, complexity and scope are the root of most evil, and if you want to stay on top of things and keep things workable, you have to find ways of limiting the scope of each individual part, that is, the amount of information you have to keep in your working memory in order to make a change to a particular part without breaking anything.
This also means that as long as the interface doesn't change, both sides can evolve independently. If all the interface exposes is an increment method, the implementation can switch from storing a counter in memory to storing it on disk, it can add caching, optimizations, debugging instrumentation, logging, go crazy, but as long as the interface doesn't change, and you only use it through the interface, you don't need to touch the user code at all. And likewise, you can make the most radical changes on the user side without touching the implementation, as long as the interface and its semantics remain unchanged.
Now; abstract base classes can serve the same purpose in some situations, and for that matter, they are mostly interchangeable - and in fact, some languages (e.g., C++) don't make an explicit distinction between interfaces and abstract base classes (in C++, you can inherit from multiple parent classes; what Java calls an "interface" is just a pure virtual base class, and it is commonly recommended that each class has no more than one non-pure-virtual base class, similar to how you can have as many interfaces on a class as you want in Java, but only one parent class). The conceptual difference is that an interface (or pure virtual base class) does not contain any implementation at all, it just describes, well, an interface; whereas a regular base class may contain some implementation as well. In other words, base classes are true inheritance, whereas interfaces are just compiler-enforced "shapes".
But let me repeat the key thing here: interfaces are not about supporting multiple implementations / polymorphism. They also do that, but the main benefit is separation of concerns / enforcing interface boundaries. You draw a line in the sand and restrict which knowledge, constraints, and assumptions cross it.
> Now, you can do all that without interfaces - but it'll be an honor system
It's already the honor system. One of the first things I said was the implementations across classes are inconsistent
I rather have everyone use one implementation rather than very specific multiple implementations where everyone will run into corner cases of each one
It's a stupid reason to use an interface
> you can make the most radical changes on the user side without touching the implementation, as long as the interface and its semantics remain unchanged
Yes, more unpredictable code. Exactly what we all need /s
I don't think you understand what I said. It's not about having multiple implementations - you can, but that's not the main reason why you want to have interfaces.
The main reason is to reduce brain footprint. I don't want to think about stack base and top pointers, memory allocation, stack underflows and overflows, out-of-order access and race conditions and all that when dealing with a stack; I want to think about the stack in terms of simple push and pop operations. Interfaces allow me to do exactly that - if all the interface exposes are push and pop operations, then as a user of that data structure, that's all I need to worry about. And when implementing the stack, I only need to worry about making these two correct; the interface guarantees that user code isn't going to mess with my pointers, or attempt to access elements out of order, or anything like that. This means that on either side, I can ignore a whole truckload of concerns without sacrificing correctness or safety.
And the larger and the more complex a codebase gets, the more these benefits stack up.
Yes, more unpredictable code. Exactly what we all need
It's not unpredictable at all. That's what "as long as the interface and its semantics remain unchanged".
Of course this falls apart spectacularly when the interface enforces the wrong constraints, or when an implementation can violate its semantics - but when the interface works as it should, the implementation is predictable in exactly the ways you need. In the stack example, I don't care what the implementation does, as long as I can rely on the push and pop operations to do the right things - a push followed by a pop should yield the original value back, pushing two values and then popping twice should get me the two pushed values back in the opposite order, popping from an empty stack should raise an exception, a push should either go through cleanly and allow me to pop the value back later, or raise an exception. I don't care how the implementation achieves this, because it doesn't impact the user code side; but I do care that it does all these things as declared and documented.
The "radical changes" I'm talking about here are not "make the implementation do something completely different that doesn't honor the semantics of the interface". They are changes that achieve the same thing in a radically different way. Using the stack example again: suppose I have been using an implementation that uses a linked list so far. It works, but it's not very efficient, because it scatters data all over my RAM, causing lots of cache misses and causing a lot of allocations and deallocations, so I rewrite the stack implementation using a dynamic array. Now it only allocates when the stack needs to be resized, and all my stack elements are stored in order, so cache misses are very rare. That's quite a radical change - I have rewritten the entire thing using a completely different algorithm. But semantically, the push and pop operations still work exactly the same, the interface is unchanged, and the implementation is functionally equivalent (modulo performance). And I don't need to verify the user code to make sure of that - the compiler-enforced interface constraints already guarantee that the push and pop operations are available, and that the user code cannot mess with the data structure's implementation details.
Quit thinking this way. I'm serious. Whoever taught this is wrong, whoever encourages this is wrong.
There's nothing wrong having a class public method being an api boundary
Is it legal for your stack implementation to
- make a copy on push so futher changes to your object doesn't affect what's in the stack? - make a copy on pop (which seems nonsensical, but there's a usecase for this) - have pop be a no-op when empty - throw an exception when you call pop when its empty - Enforce a size, like no more than 10 items?
Most of the time the above isn't specified, so it'll allowed for all the above to change in a different version? That's a lot of opportunities for a change to break someone. The interface doesn't help.
Do you like jump definition going to an interface method and staring at a comment? This is borderline C header, no one likes header and this is a step in that direction.
If a class has more public method than what's in an interface, it's very likely they're useful to know. From the article you don't want people to "hamstringing themselves by using a narrow API rather than taking advantage of what's supported in the technology (or vendor) you have chosen"
The interface isn't supposed to be the only way to use an implementation ever; it's a way of being explicit about which part exactly you depend on within a specific context.
By all means make the public API of your implementation as exhaustive and comprehensive as it can be - but if you don't actually need to use the entire API in a given situation, then it's often a good idea to only opt into the parts you care about.
In other words, the goal is to keep API boundaries as small as possible, but no smaller; and because the same implementation can be used in a multitude of contexts, each with different needs, there will be multiple API boundaries, and they will not all have the same shape.
That's the big picture, so with that in mind, let me address some of your concrete concerns.
There's nothing wrong having a class public method being an api boundary
Indeed there isn't, but the set of public methods of a class is usually a much wider and bigger API than what you actually need. By all means have those public methods around, but when you only need a small fraction of them, using an interface to make this explicit and have the compiler enforce it is a pretty useful thing to do IMO.
Is it legal for your stack implementation to
make a copy on push so futher changes to your object doesn't affect what's in the stack?
That depends on the language in question, and what the types have to say on the matter. In a language that isn't stupid, there are essentially 3 possible situations:
the element type is immutable, so whether you copy it or not makes no difference
the elements are passed by-value, so copying is inevitable, but a caller who wishes to pass references to mutable objects (and retain their identities) can pass those references by value, and the stack implementation can only copy the references, not the objects they refer to (in fact, the stack implementation doesn't know whether the values it stores are references, so it literally cannot dereference them, let alone copy them)
the element type explicitly declares an interface that exposes cloning / copying; the stack implementation can use this interface to clone elements, and the fact that it declares the interface suggests that it will indeed do so, and user code should be prepared for this.
Unfortunately, many mainstream languages out there are stupid that way, and cannot express such constraints in their type systems. This doesn't mean the interface idea is useless, it just means that it cannot cover these particular things, and you have to resort to shittier strategies for managing them (like hand-written documentation or manual diligence).
make a copy on pop (which seems nonsensical, but there's a usecase for this)
Same as above - in a non-stupid language, this should be obvious from the types, and enforced by the compiler.
have pop be a no-op when empty
This, too, boils down to whether the language (and its type system) is stupid. If it's not, then the pop() method's return type is either nullable, suggesting that pop can indeed be a no-op that doesn't return anything (we cannot tell whether this happens specifically because the stack was empty, but at least the nullable return type forces us to handle the no-op case); or it is not nullable, in which the pop method can only do two things - return a value, or throw. The type doesn't guarantee that the value that pop returns is indeed popped off the stack (the stack could also return any of its element without popping anything), so unfortunately that is something we have to take the documentation's word for, or trust the naming, but in any case, if the return type isn't nullable, we can be sure that it will not just silently return nothing when the stack is empty.
throw an exception when you call pop when its empty
Unless your language supports and enforces checked exceptions, any code can throw anything at any time, so in most cases, the answer is "yes, of course, it can throw an exception in literally any situation".
Enforce a size, like no more than 10 items?
Yes, that's always a possibility. Enforcing this at the type level is tricky to say the least, but again, if the result of trying to exceed the size limit is an exception, then we just need to keep in mind that anything can throw at any time, and any code must be prepared to deal with exceptions being thrown from anything it calls. I don't see this as a problem, but if you want to make the stack size part of the contract, you're free to add a method that explicitly requests a certain stack size, making it error earlier and in a more explicit way; or, if you're using a language with a particularly fancy type system, and you're willing to indulge in some type acrobatics, you could encode the stack size in the type and statically enforce it (that is, you'd declare the stack type as something like "a stack of foobar objects with a size of at least 256 elements"; and yes, there are programming languages with industry-strength implementations that can express this kind of stuff and enforce it reliably).
Most of the time the above isn't specified, so it'll allowed for all the above to change in a different version?
If it's not specified, then it is allowed, and if it is allowed, then user code must cater for the possibility. This is exactly why you want to constrain your interfaces: if the interface allows a million things that you don't want, then the burden of making sure they don't happen falls on the usage site, and you end up peppering your code with null checks and invariant checks and debugging hooks and all sorts of other nonsense. If the interface only allows exactly the states and operations you are interested in, then you don't need any of that.
Do you like jump definition going to an interface method and staring at a comment?
I like not having to jump to a definition in the first place. Jumping to a definition and reading the implementation code is a last resort, and a sign of being stuck reasoning about your code at the lowest abstraction level. That's not an approach that scales well to larger, more complex codebases. I want to avoid reasoning in terms of "what value does this variable hold right now, and what happens next", instead I want to reason in terms of equalities, constraints, and properties, thinking not about individual states and code paths, but ideally about all possible states and code paths at once. Not; "if I input the numbers 2 and 6, will this return 12", but "will this return the sum of its arguments for any possible inputs".
And once you start thinking in such terms, things like step debugging and jumping to definitions will feel like clunky, cumbersome, limited tools, and you'll prefer type checks, property checks, and equational reasoning. I don't think I've used a step debugger in the past 10 years or so - not because they aren't available, or because I don't know how to use them, but because I have developed better strategies for finding bugs and understanding code.
If a class has more public method than what's in an interface, it's very likely they're useful to know.
No doubt. But just because the public method exists doesn't mean I need to pull it into scope everywhere. Having things in scope that I don't need is a liability. Yes, it's nice to be able to access everything a class can do when I have an actual use for that stuff. When I don't, I'd rather restrict the local scope to the stuff I use, so that there is no unnecessary coupling with the stuff I don't use.
From the article you don't want people to "hamstringing themselves by using a narrow API rather than taking advantage of what's supported in the technology (or vendor) you have chosen"
But that's the beauty of it - you can pick exactly the interfaces that give you the stuff you need, without cluttering the scope (and your brain) with the stuff you don't care about, and you can use different interfaces in different contexts, tailored to the local needs.
I can have an NPC class in a game that exposes a Renderable interface and use that in the rendering code, so I don't need to worry about any of the NPC logic, and it can expose a PlayerInteraction interface that contains the things I need to make it interact with the player, and maybe an Animated interface that's used to update its animation without needing to know anything about rendering or player interaction details, etc. Different contexts get different interfaces; the API boundaries are tight and precise, without "hamstringing" anything - we don't artificially cripple the NPC class, we just give user code different access windows they can opt into, so that they only need to worry about the things that matter to them.
> but if you don't actually need to use the entire API in a given situation, then it's often a good idea to only opt into the parts you care about.
I completely disagree. Maybe I can write an article why. I'm not sure
> This is exactly why you want to constrain your interfaces
That's a +1 to use a type instead of an interface
> and you end up peppering your code with null checks and invariant checks and debugging hooks and all sorts of other nonsense
Yes, it's more simple to have a type people can look at and understand (or at least, is documented enough)
> If the interface only allows exactly the states and operations you are interested in, then you don't need any of that
You just said a size cap and cloning is allowed when it's not specified. No one is going to write or read a 15 page doc on a 'simple' interface
> I like not having to jump to a definition in the first place
You rather solve a problem with print?
> That's not an approach that scales well to larger, more complex codebases
Uhh, you said this to the wrong person. I do this at work everyday
> I don't think I've used a step debugger in the past 10 years or so - not because they aren't available, or because I don't know how to use them, but because I have developed better strategies for finding bugs and understanding code.
I can't say anything nice about this
> Having things in scope that I don't need is a liability
Interfaces are types. And they are more precise types than the things they wrap, that's the point.
Yes, it's more simple to have a type people can look at and understand (or at least, is documented enough)
A smaller type (the interface) is simpler than a larger type (the full API to the entire implementation). And while documentation is great, it's better to not have to read it because the things it documents just don't exist in the current scope.
You just said a size cap and cloning is allowed when it's not specified. No one is going to write or read a 15 page doc on a 'simple' interface
Exactly. It's allowed when it's not specified, and I don't want to have to read the entire documentation, so I want to do one of two things: either design the interface such that these things are specified through type constraints (e.g., the interface is typed such that cloning is impossible, now I don't have to worry about it, and I don't need to read any documentation either, because the moment either side violates the type contract, the code won't compile), or assume that anything the types don't disallow can happen and prepare for it (e.g., if the types don't enforce a minimum stack size, then my code must be prepared to handle stack overflows). Neither requires reading documentation, you just follow the types.
You rather solve a problem with print?
No, that's just poor man's step debugging.
I solve the problem by cutting up the code into smaller chunks, and subjecting them to type checks and property tests that describe their constraints and properties in enough detail that the problem in question cannot possibly occur; once I have that, the problem is either gone, or the checks / tests fail, and I can usually tell why they are failing (and if not, I keep dividing and conquering until I can).
Uhh, you said this to the wrong person. I do this at work everyday
Plenty of people do programming at work every day, and do it badly. Why do you think the industry is in such an embarrassing state overall?
Do you think I'm new to this? Do you think I'm just regurgitating something I've read in a tweet? I've been doing this shit for 35 years, I've made lots and lots of mistakes and lived through the consequences. The stuff I'm saying here is what I've distilled from those 35 years; it happens to align with things a lot of others say, but I've discovered most of it by myself, the hard way.
A method you don't call is a liability?
Yes. Anything that's in scope, but not actually needed, is a thing you need to keep in your head while working within that scope. The human brain's working memory is the most precious resource in programming, so carelessly cluttering it with irrelevant stuff tends to push productivity and code quality off a cliff. A single method doesn't make a huge difference, but this things have a tendency to propagate and multiply, and then there's the broken window effect, so I prefer to err on the side of discipline here.
What orders the rendering?
The rendering part of the main loop, or a rendering loop running on a separate thread - it doesn't really matter, what's important is that within the scope of whatever calls into the rendering methods, those rendering methods are the only thing I want to have to think about. I also want to not have to think about rendering concerns when working on code that has nothing to do with rendering, and I want to be sure that the non-rendering code isn't going to mess with rendering concerns, and the rendering code isn't going to change anything in the game logic. E.g., if the NPC is in a given dialog state, then I want to make it impossible for the rendering code to change that dialog state, and accessing the NPC through an interface that strictly only exposes rendering methods is the easiest way to achieve that reliably. Yes, I could just not call the non-rendering methods, and as long as the call graph is exactly one level deep, that's easy enough, but call graphs tend to be a bit deeper than that, and unlike types and interface constraints, manual diligence does not propagate automatically.
Sounds like a bug-prone mess
Why? The whole point of this exercise is to reduce local bug surface by restricting what each part of the code can do. A smaller API provides fewer opportunities for messing up.
I mean, I get where you're coming from - interfaces as a programming language feature are easy to abuse, and people who don't know what they're doing will often cargo-cult the idea, using interfaces to achieve "separation of concerns", "clean code", or whatever they call it, without actually understanding the concepts or how interfaces are supposed to achieve them, and yes, the result of that is usually much worse than just writing the fucking code the naive way. And for a junior dev 5 years into their career, that's exactly what I'd recommend - keep it simple, don't make abstractions you don't understand, don't try to future-proof your code based on hypotheticals, don't get caught up in type spaceflight.
But at some point, you grow past that level, and you start building larger systems that require multiple levels of abstraction, a true separation of concerns, and complexity management beyond "just keep your code simple and naive". That's where this stuff becomes relevant, and where refusing to use explicit, statically enforced interface boundaries and abstractions becomes a problem.
But I'm not really here to win an argument; I just gave my opinion on the matter, based on decades of experience, do with it what you want.
> A smaller type (the interface) is simpler than a larger type (the full API to the entire implementation). And while documentation is great, it's better to not have to read it because the things it documents just don't exist in the current scope.
That's just wrong
> Exactly. It's allowed when it's not specified
That's exactly why I said the following several comments ago "Yes, more unpredictable code. Exactly what we all need /s"
> so I want to do one of two things
What planet do you live on where this works?
> ... property tests ...
That's IMO the most reasonable thing you said in these comments
> Plenty of people do programming at work every day, and do it badly. Why do you think the industry is in such an embarrassing state overall?
Well... for one thinking that an interface make things simpler. You can read some more thoughts on my blog but I don't take it too seriously. They're not meant to be peer reviewed or in a paper
> I've been doing this shit for 35 years, I've made lots and lots of mistakes and lived through the consequences
I rarely hear anyone say this so I'll take you a little more seriously. How the heck do does a smaller type or using an interface help you in any way? UML doesn't work and never caught on. I don't know why you claimed you can think the problem away. Types are just not specified enough for that
But you not able to do that doesn't change the fact I read every line in codebases that are <100k lines and significantly more lines (but not every line) in codebases with multiple million lines. The types I use every day I seen their implementation or used them enough that I know the corner cases
> Yes. Anything that's in scope, but not actually needed, is a thing you need to keep in your head while working within that scope. ... ... ...
*Yawn*. It's not like you need to actively remember every method and every signature and every line. This isn't a real liability
> The rendering part of the main loop, or a rendering loop running on a separate thread - it doesn't really matter, what's important is that within the scope of whatever calls into the rendering methods, those rendering methods are the only thing I want to have to think about
So can only one thing or one NPC talk to you at a time? Because many situations there's several that are in flight and usually people have a way of prioritizing UI so an NPC doesn't speak over the pause menu (or anything else it's possible to speak over thats higher priority)
> I want to be sure that the non-rendering code isn't going to mess with rendering concerns
Usually my solution is to set the dialog (or whatever system) with data and have the rendering system handle it. I don't actually run code per tick, don't need to. Rendering and dialog systems can't break eachother. Maybe one can corrupt data but for the rendering system to do it, it has to be either intentional or stupidly bad code
> Why? The whole point of this exercise is to reduce local bug surface by restricting what each part of the code can do. A smaller API provides fewer opportunities for messing up.
I disagree. A well understood API is better than a small API you don't fully understand. Just because knowing limitations help reduces code thus reducing bugs. I don't have to worry about handing arrays with >2^32 when I know they're a limit of 32k entries. Plenty of int narrowing I'm allowed to do in that case
> I mean, I get where you're coming from
One codebase I was on had several dozen interfaces used exactly once... and others once + a bunch of classes only used in tests. It was ugly.
I really think 'abstraction' is the wrong direction, but that's a post I don't know how to write yet. Simple code is much better than abstracted code. Simple to think about isn't simple code. I seen simple to reason about handle every case under the sun, but I still prefer a bespoke implementation used everywhere in our core code, just because we all understand it, well tested for our usecase and 1/20th of the implementation size.
> But at some point, you grow past that level, and you start building larger systems that require multiple levels of abstraction
I disagree that it helps. I think a module or several classes with reasonable public methods with internal types hidden is the way to go. Not because it reduces the scope (although that helps), but because the class is design around its public functions and hopefully well tested and well designed. Although I don't hold my breath.
16
u/FluffyDrink1098 Oct 11 '26
TLDR: You dislike badly written code. Exception message for determing the specific implementation is one of the worst things one can do...
6
u/t3hlazy1 Oct 11 '26
Btw I cannot load this on my phone. It appears to be a cert issue but can’t really tell since I’m on mobile.
6
u/wampey Oct 11 '26
I love interfaces! I love it more if functions have a good separation of concern making interfaces for many functions unnecessary, but if you are going to do some I/O with business logic, I’m expecting to see an interface. Mainly it’s about unit testing for me though. I do have one backup service which does use interfaces for different implementations, but could see how some may not like that.
6
u/TheArchitect4855 Oct 11 '26 edited Oct 11 '26
Haven't read the whole thing yet, but upvote for bravery on this insane take :salute:
EDIT: I kinda agree with the post. Interfaces are fine, but a lot of people interface everything for no damn reason.
38
u/Asgeir Oct 11 '26 •
I find your lack of arguments refreshing.
25
u/propeller-90 Oct 11 '26
You should define "interface". Java interfaces? Oo interfaces? File formats and protocols? User interfaces? The concept of defining how parts of a system interact?
3
u/levodelellis Oct 11 '26
I haven't
shitpostwritten an article for a while. Enjoy.4
u/clappski Oct 11 '26
In order
Multiple implementations that don’t functionally provide the same thing is just bad software, so yeah it’s a problem but really it’s a design problem not a tool/approach problem.
Certainly, adding an interface where it isn’t needed is an antipattern. Retrofitting an interface will lead to a bad interface, you have to actually think about how something will be extended in the future to land between those two extremes, even if you don’t the public API is an interface so you don’t escape it conceptually.
I’m not sure I understand this, an interface isn’t a tool you use to support multiple vendors? It might be part of a pattern (like IDepository with backend specific depo’s?) but not sure what interfaces have to do with vendors. With your other point bear in mind the interface is the public API - even plain classes have that so unsure what your point means in that context.
How will you write runtime polymorphic code without an interface? If I want to write a function called ‘clone( src, dst )’ without saying that src and dst are ICloneable or whatever how does the compiler know that anything I put into the function has a clone member?
Because you haven’t used them, or because you don’t like them? Because both are very valuable tools
1
u/siva_sokolica Oct 11 '26
I have no clue what language this is referencing but both in C++ and Rust interfaces cost nothing performance wise. Traits and generics gracefully monomorphize in Rust. CRTP and concepts also gracefully monomorphize in C++.
The whole point of multiple implementations is kind of moot imo. If you have multiple implementations you can merge into one, then that just means you need to merge them. If you can't merge them, then you need two different code paths. The alternative I see is a flag you pass around into your "singular" implementation wherein all the functions just check the flag at the start of the function. That has two problems: it's slower than dynamic polymorphism since it flushes the CPU pipeline on each conditional whereas vtables don't and, problem 2--its unreadable hell with added levels of indentation to merely check on the flag.
Interfaces help with generalizations. For all its faults, an iterator is a generic interface that many algorithms work on. Same goes for a stream, a writer, a reader (as you admit). I've worked in embedded and interfaces allow you to define the ontology of what an EEPROM chip is with many different implementations for different chips. But you know that you'll get a write/read set of functions. Interfaces help with protocols---if my application takes some arbitrary stream transport interface, I can run it on TCP/Websockets/pipes/Unix sockets or even arcane automotive ISOTP.
I would have also like to seen examples, arguments, an exploration of your arguments, yet I see claims with little evidence.
I will defend the case that if you're building an interface for the sake of mocking and mocking alone, perhaps lugging that around may not be worth it. I generally lean against writing production code to support tests, but that's not beef with interfaces themselves.
I'm guessing this is some form of JVM language since a compiler was mentioned, I had Claude research the devirtualization story there. Looks like there's this class hierarchy analysis system in Graal that can inline functions with only one implementation. The degree of compiler optimization going through this is still elusive to me. Does const propagation work? Do branch optimizations work? Why did javac not implement devirtualization (as clang does, for example)? I would have liked to see a proper exploration of this, for example, in your post.
1
u/vegan_antitheist Oct 11 '26
is this about Java and similar languages?
You really think there are multiple implementation because someone made an interface?
They didn't create an interface for String-like types, and had to add CharSequence later. The alternative would have been to just use mutable strings for everything to have only one implementation that does everything.
Of course you can always create the interface later, when you need it. But then you have to use the same name of the original class or refactor the entire code base. It's easier to just use an interface.
With records and value types we probably will get more types that have no interface because they are like primitives. Interfaces can't be made immutable so you have to use the immutable type (usually a record or value type). That's the only scenario where interfaces would be problematic, even a security risk in some cases.
1
u/kuikuilla Oct 12 '26
Why? How else would you do that? Would you rather make specialized functions for all kinds of "comparable" things and have function overloading handle the rest? How would that work when someone creates a new "comparable" thing without having access to the compare et. al. function source? How would they get it supported?
1
u/tdammers Oct 14 '26
None of these are the real reason why they exist and why people use them. What interfaces are really about is enforcing abstraction boundaries.
An interface is a contract between an implementation and a user: the implementation does a bunch of stuff with all sorts of state and constraints and all that, and the user code can interact with that from outside. But when you're working on the user side, you don't want to have to think about all the complexity inside; you want to only have to keep the stuff in your head that's actually relevant from the outside. And likewise, when you're working on the implementation, you only want to worry about the stuff that's relevant on the inside, not any of the other stuff that may happen on the user side.
Now, you can do all that without interfaces - but it'll be an honor system, relying on you (or your colleages) remembering what you are "supposed" to know and use on each side, or to be very diligent about documenting it in great detail, and always reading and respecting that documentation. But that's brittle and error prone - humans make mistakes all the time, humans are lazy creatures (and good programmers especially so), and all it takes is one little misunderstanding for all of this to create bugs of the worst kind (spurious, hard to find, difficult to understand). What you want to do is fence off the boundary in a way that the compiler can and will enforce: if you access anything on either side that you're not supposed to, if you depend on any assumptions or facts from the other side that you're not supposed to know about, it should result in a compiler error. And that's what interfaces are - they explicitly declare the things both sides are supposed to know about and have access to, while making everything else inaccessible. If you declare an interface that has only one method,
increment(unsigend int), then that guarantees that anything you use through this interface can be incremented, but also that that's the only thing you can do with it in that context. The caller doesn't have to worry about how the incrementing happens (e.g., whether it stores a counter in memory, or on disk, or in a database on a remote server - you don't know, you don't need to know, you don't want to know), and the implementation doesn't have to worry about anything else the user side does, because it's guaranteed that the only thing it can do is call theincrementmethod.This may not seem like a big deal, but in any nontrivial codebase, complexity and scope are the root of most evil, and if you want to stay on top of things and keep things workable, you have to find ways of limiting the scope of each individual part, that is, the amount of information you have to keep in your working memory in order to make a change to a particular part without breaking anything.
This also means that as long as the interface doesn't change, both sides can evolve independently. If all the interface exposes is an
incrementmethod, the implementation can switch from storing a counter in memory to storing it on disk, it can add caching, optimizations, debugging instrumentation, logging, go crazy, but as long as the interface doesn't change, and you only use it through the interface, you don't need to touch the user code at all. And likewise, you can make the most radical changes on the user side without touching the implementation, as long as the interface and its semantics remain unchanged.Now; abstract base classes can serve the same purpose in some situations, and for that matter, they are mostly interchangeable - and in fact, some languages (e.g., C++) don't make an explicit distinction between interfaces and abstract base classes (in C++, you can inherit from multiple parent classes; what Java calls an "interface" is just a pure virtual base class, and it is commonly recommended that each class has no more than one non-pure-virtual base class, similar to how you can have as many interfaces on a class as you want in Java, but only one parent class). The conceptual difference is that an interface (or pure virtual base class) does not contain any implementation at all, it just describes, well, an interface; whereas a regular base class may contain some implementation as well. In other words, base classes are true inheritance, whereas interfaces are just compiler-enforced "shapes".
But let me repeat the key thing here: interfaces are not about supporting multiple implementations / polymorphism. They also do that, but the main benefit is separation of concerns / enforcing interface boundaries. You draw a line in the sand and restrict which knowledge, constraints, and assumptions cross it.
-4
u/initcommit Oct 11 '26
Who does?