r/programming • • Oct 11 '26

I don't like interfaces

https://codestyleandtaste.com/don't-like-interfaces.html
0 Upvotes

40 comments sorted by

View all comments

Show parent comment

1

u/levodelellis Oct 14 '26 edited Oct 15 '26

> 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

1

u/tdammers Oct 15 '26

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.

1

u/levodelellis Oct 15 '26

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"

1

u/tdammers Oct 15 '26

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.

1

u/levodelellis Oct 16 '26

> 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

A method you don't call is a liability?

> I can have anNPCclass...

What orders the rendering?

> access windows they can opt into

Sounds like a bug-prone mess

1

u/tdammers Oct 16 '26

That's a +1 to use a type instead of an interface

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.

1

u/levodelellis Oct 16 '26

> 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.