News for hackers. Stuff that matters.
Re:Generating a Java program with 90% less code by ronnier on Wednesday December 04, 2019 @11:12AM (#21703394)
> We define the UserProvider interface

I'm strongly against creating interfaces for non-library (not shared) code, that will only ever have one concrete implementation. I see it all the time in internal service code, code that will never have a second implementation. It makes code hard to navigate, harder to understand, and tedious to manage as instead of updating one file, now you'll need to update two.

Re:Generating a Java program with 90% less code by wvenable on Wednesday December 04, 2019 @11:24AM (#21703517)
So much over-engineering comes from the fear of changing already written code. Some programmers, I believe, have the impression that changing code any reason other than new features or requirements is wasted effort. So they try and build out all possibilities they can imagine first so they won't have to change it later.

If you eventually need that interface, you can change your existing code to use it. Making that change is relatively easy compared to maintaining a bunch of code that isn't needed. But still I find it hard for some programmers to get past that mentality.

Re:Generating a Java program with 90% less code by bitbuilder on Wednesday December 04, 2019 @12:28PM (#21704384)
Couldn't agree more, and I feel like I've spent half my career tilting at windmills trying to get other engineers to use less abstraction, instead of more.

I can't count the number of C#/Java projects I've walked into where it felt like I had to drill down through a dozen layers of abstraction just to find code that actually does something. Hundreds (thousands?) of files that contain nothing but autogenerated boilerplate crap.

Layers upon layers of boilerplate, "just in case we need to swap something out later!" No. I promise you, you won't. And if you do, I promise you things aren't as loosely coupled as you think they are. You're going to have to do a bunch of rewriting anyway.

Also, 9 times out of 10, by the time you realize some seemingly interchangeable piece of your architecture needs to be replaced, your team will be chomping at the bit to blow the whole thing up and rewrite from the ground up anyway.

In the meantime, having a simple codebase that people actually enjoy working in will make everyone's job so much easier. And fun.

Re:Generating a Java program with 90% less code by minblaster on Wednesday December 04, 2019 @01:05PM (#21704924)
YAGNI was coined for a reason.
Re:Generating a Java program with 90% less code by sna1l on Wednesday December 04, 2019 @11:30AM (#21703602)
+1 to this

In my own progression as an engineer who writes Java, I read Clean Architecture by Robert Martin which lead to AbstractFactory(s) and interfaces up the wazoo. The reasoning would always be "this can change!"

It definitely took me some time to understand that not everything will change, and if it does change, having some extra work for simplicity is a reasonable tradeoff sometimes. In general, knowing when to utilize OO design patterns takes time and experience.

Re:Generating a Java program with 90% less code by mumblemumble on Wednesday December 04, 2019 @12:14PM (#21704167)
Similar progression here.

It took a long time before I realized that a lot of the changeability that come with writing aggressively SOLID code is actually a self-fulfilling prophecy: Some tightly intertwined chain of steps that might have been implemented as five consecutive (albeit tightly coupled) statements gets blown out into 10 or 15 modules and abstractions spread across as many files. All this added complexity was invariably designed to make it easy to change the code in a way that is not actually how you ended up needing to change it, so the end result is that it increased the difficulty of changing things: Instead of editing 5 lines, you now need to edit 10 files. And, since the logic is spread across 10 files whose members are, thanks to the magic of Java's access control facilities, all public, and whose connections to other parts of the codebase are all, thanks to the magic of dependency injection, loose (read: not explicit), it's hard to even understand the scope of impact of those changes without relying extensively on an IDE.

I've since taken a big turn back toward procedural programming. Object-oriented and functional techniques have their place (and the best procedural languages will let you use both), and I've learned a lot from working in both paradigms. But most of what I learned is that no amount of abstraction can replace the KISS principle.

Re:Generating a Java program with 90% less code by pscanf on Wednesday December 04, 2019 @12:59PM (#21704845)
> The reasoning would always be "this can change!"

As I understood Uncle Bob's argument for using interfaces though, the main benefit is not supporting alternative implementations, but rather aiding in the enforcement of the Dependency Rule[1] and of the Single Responsibility Principle[2].

Interfaces make the relation between components explicit in two ways:

- they make it clear what depends on what - they make it clear what are the responsibilities of the components on either side of the interface

So aside from the fact that it might make it easier in the future to swap implementations, it first makes it easier when writing the code to decide how to organize its components (i.e. laying out its architecture).

Of course I agree with you that interfaces can definitely be abused, and can make code more indirect and difficult to read. I just wanted to point out what I think is Uncle Bob's point. :)

[1] https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-a... [2] https://en.wikipedia.org/wiki/Single_responsibility_principl...

Re:Generating a Java program with 90% less code by Sohcahtoa82 on Wednesday December 04, 2019 @01:10PM (#21705004)
> Single Responsibility Principle

Too many Java programmers take the SRE too far, IMO.

If you have a class that only has a single function, then it probably should be a function, not a whole class.

To give an example that I've seen, I've seen code with classes named UserGetter, UserCreator, UserDeleter, etc. All of these should have just been bundled up into a single User class.

Re:Generating a Java program with 90% less code by GordonS on Wednesday December 04, 2019 @01:39PM (#21705406)
I see a lot of interface abuse with C# too. My hope is that C#'s new default interface implementations will put an end to this mess.
Re:Generating a Java program with 90% less code by apta on Wednesday December 04, 2019 @05:54PM (#21708068)
Java also now has default interface implementations.
Re:Generating a Java program with 90% less code by cageface on Wednesday December 04, 2019 @11:38AM (#21703705)
This is taken to a pathological degree in the VIPER architecture. Every thing is decomposed and wrapped in and interface. Unfortunately this has gained some popularity in the iOS world. It makes code so much harder to follow and maintain.
Re:Generating a Java program with 90% less code by dep_b on Wednesday December 04, 2019 @12:09PM (#21704088)
Never used VIPER. MVVM with navigation flows and layout handlers works well enough.
Re:Generating a Java program with 90% less code by cageface on Wednesday December 04, 2019 @10:23PM (#21709704)
AppKit is pretty deeply MVC. I generally prefer to just work with the underlying APIs than try to invent a new paradigm on top of them. With VC containment I feel like I have enough abstraction power already.
Re:Generating a Java program with 90% less code by dep_b on Thursday December 05, 2019 @06:29AM (#21711538)
In my case the "Flows" are usually UINavigationControllers hidden behind a protocol. I tend to chop up my UI's really deeply into VC's but most of them get a VM because I like my VC's really, really small.
Re:Generating a Java program with 90% less code by jswizzy on Wednesday December 04, 2019 @12:43PM (#21704631)
MVI is the latest evolution of MVVM. It's basically MVVM with Reactive programming.
Re:Generating a Java program with 90% less code by dep_b on Thursday December 05, 2019 @06:27AM (#21711529)
I do use Reactive (ReactiveKit) a lot now to prepare for Combine
Re:Generating a Java program with 90% less code by GordonS on Wednesday December 04, 2019 @01:37PM (#21705373)
I've gone through the same learning process, and I've seen it happen with numerous devs - they go through a cargo-culting stage, where they see abstractions and patterns espoused by people they respect, only to later come to the conclusion that it makes for code that is anything but clear.

Abstractions are not evil, but it takes experience to use just enough abstraction.

Re:Generating a Java program with 90% less code by potta_coffee on Wednesday December 04, 2019 @12:15PM (#21704179)
This is my main complaint with OOP. It's not a feature of OOP explicitly but I've only seen it in OOP codebases. And the most complicated, awful, snaggletoothed codebases I've had to unravel were all like this - heavily laden with abstractions that weren't really necessary.
Re:Generating a Java program with 90% less code by wvenable on Wednesday December 04, 2019 @12:28PM (#21704387)
OOP exists exactly to solve problems where abstraction is appropriate. So obviously it's going to be implicated in cases of over-abstraction.

It's kind of like how cars are implicated in traffic problems. Everywhere you have heavy traffic, you'll find cars.

Re:Generating a Java program with 90% less code by potta_coffee on Wednesday December 04, 2019 @04:58PM (#21707636)
So do you not believe that OOP practices can be abused?
Re:Generating a Java program with 90% less code by wvenable on Wednesday December 04, 2019 @06:13PM (#21708208)
I actually said the opposite. Any tool of sufficient power is going to more abused than a tool with less power. You can do more damage with a backhoe than a shovel.

But the fact that you can do more damage with a backhoe than a shovel doesn't mean there is anything wrong with a backhoe or anything good about shovel. Same is true of OOP.

Re:Generating a Java program with 90% less code by potta_coffee on Wednesday December 04, 2019 @08:03PM (#21708989)
Got it. I don't have an issue with OOP, just the ways I've seen it abused, mostly by intermediate programmers that are too clever for their own good.
Re:Generating a Java program with 90% less code by tootie on Wednesday December 04, 2019 @11:59AM (#21703956)
As mentioned elsewhere, refactoring a concrete class into an interface is actually pretty trivial using an IDE. At least within an codebase. The only time to really be diligent about interface design is if you're designing an API.
Re:Generating a Java program with 90% less code by marcus_holmes on Wednesday December 04, 2019 @11:52AM (#21703858)
I catch myself doing this all the time. I'm never going to move this project off Postgres, so why the hell have I created an interface to abstract the database?
Re:Generating a Java program with 90% less code by pm90 on Wednesday December 04, 2019 @12:00PM (#21703958)
Unit testing?
Re:Generating a Java program with 90% less code by yawgmoth on Wednesday December 04, 2019 @01:04PM (#21704919)
Not sure about Java, but at least in C# there are clear advantages to using interfaces over concrete classes when using Moq.
Re:Generating a Java program with 90% less code by GordonS on Wednesday December 04, 2019 @01:41PM (#21705448)
Interfaces are not the only option - you can also mark methods as virtual.

But overuse of mocking is a very big problem in a lot of codebases. Often I look at a test, and all it seems to do is setup mocks, such that I'm not sure if anything is actually being tested!

My hope is that C#'s new default interface implementations feature will put an end to this mess.

Re:Generating a Java program with 90% less code by acidictadpole on Wednesday December 04, 2019 @12:00PM (#21703957)
I've been in the workforce for nearly 10 years and I still have this issue when starting a new project.

It takes a conscious effort to just move forward, and it still leaves a lingering thought in my mind about what I'm doing wrong while building exactly what I need.

Re:Generating a Java program with 90% less code by ieatpies on Wednesday December 04, 2019 @11:28AM (#21703568)
The cost of refactoring is dependent on the scale/stage of the project
Re:Generating a Java program with 90% less code by oldmanhorton on Wednesday December 04, 2019 @11:18AM (#21703445)
Do you consider test mocks to be a second implementation that warrants the interface?
Re:Generating a Java program with 90% less code by bcrosby95 on Wednesday December 04, 2019 @11:57AM (#21703927)
No. This is what many considered test induced damage. If the only reason you create an interface is because a test requires it, you are damaging the integrity of your design.

Interfaces are one of the more powerful abstractions available and should be well thought out points of flexibility you specifically designed into your solution. If you use interfaces for other reasons your codebase is full of false flexibility and not-actually-abstracted abstractions which makes it difficult for other people to figure out what they can actually do with it.

Re:Generating a Java program with 90% less code by iamaelephant on Wednesday December 04, 2019 @12:04PM (#21704013)
> No. This is what many considered test induced damage. If the only reason why you create an interface is because a test requires it, you are damaging the integrity of your design.

Writing testable code is not "damage". An interface is a small concession in exchange for the well known benefits of automated testing.

I see where you're coming from and many programmers use too many interfaces as a reflex. But I absolutely think interfaces should be used to create seams for automated tests in front of components that do things like interact with databases, file systems, networks etc.

Re:Generating a Java program with 90% less code by klmr on Wednesday December 04, 2019 @01:07PM (#21704955)
> Writing testable code is not "damage"

Correct, but you can go a long way in writing testable code without requiring mock implementations. While I don’t deny the usefulness of mock testing, it comes at a steep cost (= vastly more complex code base), and I increasingly question whether that’s worth it. In practice I find it more useful to unit test what can be tested in isolation, and to perform integration testing for the test, and to limit mock testing (and thus unit tests which would require mocking) to a few well-defined interfaces. This cuts down drastically on boilerplate, with little (if any) loss of testability. And these few remaining mock object dependencies can be modelled via simple parameters and higher-order functions, further cutting down on extraneous interface classes.

Re:Generating a Java program with 90% less code by BeetleB on Wednesday December 04, 2019 @08:03PM (#21708987)
> Correct, but you can go a long way in writing testable code without requiring mock implementations.

For some languages (e.g. C++), if you are using classes, it can actually be fairly challenging to do unit tests without mocks. And almost every solution to this problem out there is to use interfaces/dependency injection/inversion.

Re:Generating a Java program with 90% less code by klmr on Thursday December 05, 2019 @05:11AM (#21711200)
> [in C++] it can actually be fairly challenging to do unit tests without mocks

Yes, but you can write integration tests instead. There’s no rule that says that unit testing must cover every aspect of the software. Unit test those units that can be used in isolation, integration test the rest. Case in point, our main software at work, written in C++, has close to 100% test coverage, and uses almost no mock tests. Instead, we have extensive integration tests where unit testing without mocking doesn’t work.

And, again: I’m not saying that there are no tradeoffs involved in that. But the benefit of having a drastically simpler code architecture outweigh the cost of having to move those tests into integration.

Incidentally this is vastly easier when the architecture cleanly separates business logic from general logic and moves as much of it as possible into side-effect free general-purpose functions.

Re:Generating a Java program with 90% less code by BeetleB on Thursday December 05, 2019 @02:33PM (#21715601)
> Yes, but you can write integration tests instead. There’s no rule that says that unit testing must cover every aspect of the software. Unit test those units that can be used in isolation, integration test the rest. Case in point, our main software at work, written in C++, has close to 100% test coverage, and uses almost no mock tests. Instead, we have extensive integration tests where unit testing without mocking doesn’t work.

In my last C++ job, perhaps less than 5% of our code was unit testable. We had very good test coverage using integrated tests, but those were very expensive tests. Running a full test suite took 10 hours. Our SW heavily relied on certain equipment. Fortunately, the vendor had provided a very good simulator for it - so almost all our integration tests needed that simulator. And the simulator was such that there was a fair amount of overhead in loading and setting it up and unloading it. We didn't do this for every test - that would have taken days/weeks to run - but for logically grouped tests. And unfortunately many of the integration tests we wrote were much more suited to unit tests, but because we didn't have interfaces, we were forced to test them via an integration test, which was very expensive.

Oh, and the simulator would not allow parallelism - you could have only one simulator running on a given machine at a time. So all our tests had to be run in sequence.

And of course, the simulator had bugs, so whenever we had a failure, we had to determine if the simulator was at fault. Especially for intermittent failures.

So yes, we had very thorough tests and were proud of it, but unit testing for perhaps 30% of our tests would have been better. But to unit test those we really needed interfaces. I know because I convinced management to give me some weeks to convert one of our simplest portions of code into something we could unit test. I thought it would be trivial, but I ended up needing interfaces.

There is a whole other approach which our sister team (very similar SW, but different HW) used. They did not have a reliable simulator. So they wrote a "fake" simulator. They simply reproduced the APIs and wrote code to return certain values under certain conditions - a poor man's mock. On the plus side their test suite ran very quickly. The down side was they needed to write many mocks for the same function (for when they needed to return different values). Writing tests was very expensive for them.

Why did they write fakes instead of using a mocking framework? Because every mocking framework they found in C++ required interfaces, and they didn't want to change their SW architecture.

In many cases integration tests are OK. But in our case, they were extremely expensive.

> Incidentally this is vastly easier when the architecture cleanly separates business logic from general logic and moves as much of it as possible into side-effect free general-purpose functions.

This is precisely where interfaces come from! It's not trivial to separate business logic from general logic without them. When I took the time to show how we could write unit tests for our code base, I ended up with interfaces. And no, I didn't read any books/sites telling me I should do it. I didn't even know they were called interfaces. I just took some of the simplest code in our codebase, and asked "How can I write unit tests for this?" and essentially reinvented interfaces. I separated the business logic from the logic requiring the simulator, and then wrote unit tests for the business logic, and had an interface class to interface with the simulator.

To give you an idea, the code I converted to unit tests was trivial: Given this input string with these flags set, return this converted string, etc. It should be one of the easiest things to unit test! However, the input string and flags were entities understood by the HW and so we had simulator dependencies. I wrote a class that dealt only with strings and booleans to implement the business logic, and then had the interface class translate back and forth between strings/bools to entities the simulator expected/understood.

I appreciate your comment, and trust me, I'm not trying to be difficult. But while I've heard many claims, every time I've gone into the details I end up with interface classes. I work at a large company and went around asking several teams in different C++ projects, and they all independently had come to the same conclusion: Either use interfaces or live without unit tests. I presented my work to convert portions of our code base to unit tests at internal SW conferences, and would say "This is a highly nontrivial and crappy way to do unit tests in C++. I'd really like to hear from people in the audience if they found a better way." And whoever approached me afterwards said they had gone down the same path as me and ended up with interfaces.

Testing in C++ sucks, to be frank.

As an aside, I'm not pro-mocks, BTW. I recently did a small personal Python project where I insisted doing TDD. I would not write code till I had a test. And this involved several mocks. And while all my tests involving mocks passed, in the majority of cases involving the mocked code, my program had bugs and would fail when I tested with real data.

(Maybe that's more a criticism of TDD than of mocks, though).

Re:Generating a Java program with 90% less code by klmr on Friday December 06, 2019 @09:14AM (#21721875)
I appreciate your comment and your experience. And I agree: integration tests tend to be time consuming to run. At work we actually had similar issues (and many of our integration tests need to exercise cloud APIs) before a rewrite that made the time manageable.

I just wanted to pick up one of your points:

> I've gone into the details I end up with interface classes

My reply to this is that functional programming languages tend to manage entirely without, just by doing “dependency injection” via higher-order functions (in fact, outside Java I’ve never [needed to] use a DI framework). This (often? always? I honestly don’t know!) makes mocking possible without impacting the overall architecture. And like you, I practice strict TDD for all my current own hobby projects, and I manage without interfaces. But I don’t want to make a claim of generality here: it’s entirely possible that this approach doesn’t work everywhere, or even in the majority of cases.

Re:Generating a Java program with 90% less code by t-writescode on Wednesday December 04, 2019 @12:38PM (#21704539)
A common pattern to get around this situation is to use mocking frameworks to fake those calls without using interfaces. It’s in the air whether this is better or worse in the general lifespan of a piece of code; but, there are alternatives.
Re:Generating a Java program with 90% less code by taco_emoji on Wednesday December 04, 2019 @01:01PM (#21704881)
How does that work in a static language? In most (all?) static languages, you'd need an interface or virtual method in order to on-the-fly generate a class that implements the mocked functionality.
Re:Generating a Java program with 90% less code by chinhodado on Wednesday December 04, 2019 @01:32PM (#21705308)
Not entirely sure what you meant, but in Java/C# you can easily mock out a concrete class with a mock library, like Mockito. No interface required.
Re:Generating a Java program with 90% less code by GordonS on Wednesday December 04, 2019 @01:46PM (#21705511)
There are plenty of mocking frameworks for C# (Moq, FakeItEasy, etc), but for all but the most trivial classes, you generally need to use an interface or mark methods as virtual.

It's one of the reasons I tend to minimise my use of mocks as much as possible.

Re:Generating a Java program with 90% less code by chinhodado on Wednesday December 04, 2019 @02:03PM (#21705731)
It's the same with Java where it's very hard/not possible to mock final methods. It's just that methods in Java are virtual by default so it's less "in the way" when you need to mock something.
Re:Generating a Java program with 90% less code by apta on Wednesday December 04, 2019 @05:38PM (#21707995)
What do you use instead of mocks when testing?
Re:Generating a Java program with 90% less code by GordonS on Wednesday December 04, 2019 @06:10PM (#21708186)
Real instances of the dependant class.

A "unit test purist" would likely shun this, but I take more of a realist approach; in many real-world cases, mock-heavy tests make for brittle tests that don't give confidence of correctness.

I tend to focus on integration tests, as I find these provide the most value while still executing very quickly (depending on the stack, obv).

That doesn't mean I don't use unit tests, or that I never use mocks - I just use mocks very sparingly.

Re:Generating a Java program with 90% less code by andrewprock on Wednesday December 04, 2019 @01:09PM (#21704993)
On the contrary, using interfaces to make testable code is precisely the damage.

You should be writing pure functions which are easily testable, and using integration code to wrap the pure and testable parts.

Interfaces are typically a hack to get around the challenge of writing well designed, pure, and testable code.

Re:Generating a Java program with 90% less code by BeetleB on Wednesday December 04, 2019 @08:04PM (#21708996)
> You should be writing pure functions which are easily testable, and using integration code to wrap the pure and testable parts.

This often ends up with interfaces...

Re:Generating a Java program with 90% less code by andrewprock on Thursday December 05, 2019 @02:12PM (#21715347)
If you write a pure function, an interface is meaningless.
Re:Generating a Java program with 90% less code by BeetleB on Thursday December 05, 2019 @02:49PM (#21715772)
The interface comes in this part of your comment:

> and using integration code to wrap the pure and testable parts.

Re:Generating a Java program with 90% less code by andrewprock on Thursday December 05, 2019 @06:16PM (#21717714)
I think you and I are talking about different things when we say "integration test".
Re:Generating a Java program with 90% less code by rb808 on Wednesday December 04, 2019 @12:41PM (#21704586)
I'm so glad to see someone write this. I keep seeing all these horrible code bases that are supposed to be easily testable but all I see is a horrible design that is impossible to understand - all because Mocking is supposed to be a good idea.
Re:Generating a Java program with 90% less code by marcus_holmes on Wednesday December 04, 2019 @11:53AM (#21703880)
I did this, and then switched back to just running the code on a test database. I found I was writing two sets of tests: one that tested the code to see if it injected the right parameters into the SQL, and another to see if the SQL worked. It just got easier to test them both together.
Re:Generating a Java program with 90% less code by breischl on Wednesday December 04, 2019 @03:34PM (#21706613)
This can become a challenge when you want to scale a dev team. You either have people conflicting in the DB, or each dev needs to set up a local DB and deal with DB migrations. Containerized DBs help with this to some extent, but it's still a maintenance headache.

There's also a tradeoff around testing error states, but that can be a wash. Some errors are easier to create with a mock, some are easier to create with the actual driver.

Re:Generating a Java program with 90% less code by dcolkitt on Wednesday December 04, 2019 @12:38PM (#21704537)
There are tradeoffs to this approach. When the tests break it becomes a lot harder to triangulate the origin of the problems.
Re:Generating a Java program with 90% less code by runeks on Friday December 06, 2019 @06:14AM (#21720763)
I don’t buy this argument.

Once you know there’s a bug, you will definitely want to write more tests, in order to find the cause. But always writing a lot of tests, which are only usable in case you find a bug, seems like wasted effort to me.

If you need to triangulate the origin, do that when it’s necessary (i.e. when your broad test fails) and not all the time.

Re:Generating a Java program with 90% less code by GordonS on Wednesday December 04, 2019 @01:48PM (#21705534)
I prefer to just runs tests using a real database too. They might not complete as fast as mocked out ones, but they give me much more confidence of correctness, and still complete in milliseconds.
Re:Generating a Java program with 90% less code by ses1984 on Wednesday December 04, 2019 @11:19AM (#21703465)
There are test frameworks that obviate the need to do this.
Re:Generating a Java program with 90% less code by gautamdivgi on Wednesday December 04, 2019 @11:22AM (#21703507)
Not if you use something like c/c++. There are test frameworks but there is no way from preventing testing code from leeching into functional code.

But yes - Java/python, etc. you shouldn't need to do this.

Re:Generating a Java program with 90% less code by CraigJPerry on Wednesday December 04, 2019 @11:39AM (#21703723)
What’s cheaper to own though - a whole test library / framework (assuming you don’t use any other feature), or a simple interface?

I’m generally hesitant to add test libraries if there’s an easy design choice alternative that keeps the code simpler.

Re:Generating a Java program with 90% less code by ses1984 on Wednesday December 04, 2019 @12:39PM (#21704560)
Sure pulling in a giant magical reflection heavy test framework has costs but I think it's well worth it.
Re:Generating a Java program with 90% less code by MockObject on Wednesday December 04, 2019 @12:23PM (#21704311)
Adding interfaces whose only purpose is unit tests is not keeping the code simpler. Using a test library that automatically generates mocks for unit testing is what keeps the code simpler.
Re:Generating a Java program with 90% less code by closeparen on Wednesday December 04, 2019 @12:55PM (#21704793)
Using a test framework that bends the rules of the language is far from simple. One of the things I appreciate about Go is that any mortal can understand how a unit test works: you "just" plug in something that satisfies the interface. However, we are spoiled to have implicitly satisfied interfaces, which can be declared on the consumer side without the implementation even knowing.
Re:Generating a Java program with 90% less code by BeetleB on Wednesday December 04, 2019 @08:08PM (#21709014)
> Adding interfaces whose only purpose is unit tests is not keeping the code simpler. Using a test library that automatically generates mocks for unit testing is what keeps the code simpler.

I've yet to find a library for C++ that generates mocks without requiring interfaces, but I'll admit I'm not an expert on it. Can you recommend any?

As an example, Google Mock/Test will require interfaces in a C++ code base.

Of course, we may be disagreeing on what is meant by the term "interface".

Re:Generating a Java program with 90% less code by CraigJPerry on Wednesday December 04, 2019 @12:43PM (#21704627)
>> automatically generates mocks for unit testing is what keeps the code simpler

You're possibly confusing easy with simple but adding a versioned library of some thousands of lines of code to a project is in no objective way simpler than adding a small test double which you wrote.

Re:Generating a Java program with 90% less code by MockObject on Wednesday December 04, 2019 @02:51PM (#21706193)
Yes, it is, in the only objective way that people actually care about: the size and simplicity of the source code.

(What people don't care about is the size of libraries that are scoped for the test context only, and don't even impact artifact size at all.)

Also, a Mockito mock is simpler in usage than a hand-written and normally instantiated test double.

Re:Generating a Java program with 90% less code by CraigJPerry on Wednesday December 04, 2019 @04:08PM (#21707005)
Ripping off the classic talk by Rich Hickey:

  Simple - composed of a single element; not compound
  Complex - consisting of many different and connected parts
  Easy - achieved without great effort; presenting few difficulties.
This is not as easy but is simple. It is explicit, fundamental Java.

  public void allocationOnlyPossibleWhenOpen() {
     LocalDateTime expected = LocalDateTime.now();
     TimeAllocator sut = new TimeAllocator(new Clock() {
    public LocalDateTime getTime() {
      return expected;
    }
     });
    
     sut.setOpen(false);
     assertThat(sut.allocate()).isNull();

     sut.setOpen(true);
     assertThat(sut.allocate()).isEqualTo(expected);
   }
This is easier but more complex. It depends on a multi-thousand line library with its own API.

  public void allocationOnlyPossibleWhenOpen() {
     LocalDateTime expected = LocalDateTime.now();
     Clock mockClock = mock(Clock.class);
     when(clock.getTime()).thenReturn(expected);
     TimeAllocator sut = new TimeAllocator(mockClock);

     sut.setOpen(false);
     assertThat(sut.allocate()).isNull();

     sut.setOpen(true);
     assertThat(sut.allocate()).isEqualTo(expected);
   }
The 2nd example has:

A versioned external dependency, externally versioned == opportunity for future conflict. Remember the java logging library wars? Today it's trivial to encounter conflicting spring dependencies on your classpath

A complex (but convenient) reflection based implementation, the object has non-obvious behaviour with a clever implementation

An entire api surface distinct from the components of your software system

Tens of thousands of lines of opportunity for bugs, security risks or just plain old $$ cost to hide in

Once you're able to see the world in complexity, it opens up a whole new dimension of cost & quality for your code.

All this said, in practice complexity is just a consideration. Often the complexity is worth paying. I don't want to risk the impression that i'm saying never use mockito. If my argument is anything then it's consider the impact of complexity.

Re:Generating a Java program with 90% less code by organsnyder on Wednesday December 04, 2019 @11:59AM (#21703949)
Mockito is a single pom.xml (or build.gradle) entry.

edit: Not "Moquitto".

Re:Generating a Java program with 90% less code by MockObject on Wednesday December 04, 2019 @12:21PM (#21704275)
Close! That's Mockito.

https://site.mockito.org/

Re:Generating a Java program with 90% less code by organsnyder on Wednesday December 04, 2019 @12:29PM (#21704401)
Oops. Haven't done Java programming full-time since last year, but I did set up a home MQTT broker recently...
Re:Generating a Java program with 90% less code by CraigJPerry on Wednesday December 04, 2019 @12:45PM (#21704657)
It is - but my point is about complexity not ease.

The fact that dependency is versioned separately from your code base is one source of complexity that it adds. The fact that it has many lines of code is another complexity.

It is however often easier, even although i'm advocating very small self-written test doubles, they are still less easy than using mockito.

Re:Generating a Java program with 90% less code by organsnyder on Wednesday December 04, 2019 @01:42PM (#21705457)
It's a dependency that's only needed during testing, though—it's not shipped with production artifacts.
Re:Generating a Java program with 90% less code by CraigJPerry on Wednesday December 04, 2019 @02:43PM (#21706115)
That argument doesn't address complexity. Tests are part of the system.
Re:Generating a Java program with 90% less code by taco_emoji on Wednesday December 04, 2019 @01:04PM (#21704906)
Not on all platforms. In .NET you need an interface or virtual method in order to allow the mocking framework to dynamically generate a concrete subclass that mocks out that method's functionality.
Re:Generating a Java program with 90% less code by chopin on Wednesday December 04, 2019 @11:21AM (#21703487)
I do that for this reason but only if I am able to inject the implementation into the classes under test. Very often I just resort to constrictor injection for internal code.
Re:Generating a Java program with 90% less code by devit on Wednesday December 04, 2019 @03:27PM (#21706542)
Testing with mocks is generally a bad idea; instead, one should just test using the same dependencies that are used in production (after testing those dependencies, if also part of the project).

This avoids having to introduce the extra interface, having to code the mock, sometimes having to change the mock or tests when changing the code and also lets you catch bugs in the dependencies that the tests on the dependency itself missed and that would otherwise show up in production.

One might have to do some work to partially replicate the production setup in testing and making it fast to start and run, but that's usually less work and gives a much better result.

Re:Generating a Java program with 90% less code by ludjer on Thursday December 05, 2019 @06:40AM (#21711589)
That is more integration tests. Unit tests should target logic more then dependencies/integration.
Re:Generating a Java program with 90% less code by ludjer on Thursday December 05, 2019 @06:36AM (#21711571)
You do know you can mock out concrete classes aswell. You do not need a interface.
Re:Generating a Java program with 90% less code by GordonS on Wednesday December 04, 2019 @01:34PM (#21705340)
I see a lot of this with C# too, with devs creating separate projects for "contracts" and "implementations" - yet almost every interface has 1 implementation, and will never have more.

The rationale I'm given is generally one of two:

  1. "It's best practice"/"it's clean architecture" - which is basically dogmatic cargo-culting
  2. To support mocking in unit tests
The later is also found with unit test projects rammed with mocks, making for brittle, unreadable tests that often don't really seem to actually test anything!
Re:Generating a Java program with 90% less code by stouset on Wednesday December 04, 2019 @01:57PM (#21705643)
Yep. People fundamentally misunderstand how to use mocks and stubs, and often end up writing tests that test little more than “the function was written the way it was currently written”.

This is the worst of all possible worlds, because a test suite should accomplish two goals: identify bugs and enable refactoring. Tests like these fundamentally can’t identify bugs because they don’t test any behavior. And worse, they prohibit refactoring because any meaningful code change will alter what functions are called and in what order they’re called. So any refactor breaks almost every test, and it’s impossible to quickly tell if something “real” was broken or if it’s just an artifact of poor testing.

Re:Generating a Java program with 90% less code by imtringued on Wednesday December 04, 2019 @07:38PM (#21708797)
I've seen things that you wouldn't believe. "Business Objects" that do absolutely nothing but forward function calls to "Data Access Objects"

UserController -> UserBo -> UserBoImpl -> UserDao -> UserDaoImpl.

Needless to say the implementations have never been replaced with something else. The middle layer is completely useless. UserBo, UserBoImpl and UserDao should be tossed into the garbage. Every single time you wanted to add a new SQL query you had to edit 5 files... Code navigation features of your IDE become useless and you are better off with string based search.

Re:Generating a Java program with 90% less code by 3fe9a03ccd14ca5 on Wednesday December 04, 2019 @11:14AM (#21703410)
I find myself doing this often and it’s annoying. Usually it’s because I want to use some other implementation for testing that never materialized, and then the interface sits there.
Re:Generating a Java program with 90% less code by buzzy_hacker on Wednesday December 04, 2019 @11:53AM (#21703869)
You're actually reinforcing the OP's point. Coding to an interface is ideal but we are reluctant to do so because it involves more boilerplate that is a pain to manage.
Re:Generating a Java program with 90% less code by giancarlostoro on Wednesday December 04, 2019 @12:19PM (#21704252)
> I'm strongly against creating interfaces for non-library (not shared) code, that will only ever have one concrete implementation. I see it all the time in internal service code, code that will never have a second implementation. It makes code hard to navigate, harder to understand, and tedious to manage as instead of updating one file, now you'll need to update two.

I was just telling someone this yesterday. Not every damn thing needs to be an interface you implement if you're only implementing it once. Especially if you have to put "I" in front of it (as is standard in C#) and name the class the same thing, you should think if it's even necessary...

Re:Generating a Java program with 90% less code by octorian on Wednesday December 04, 2019 @11:45AM (#21703777)
> I'm strongly against creating interfaces for non-library (not shared) code, that will only ever have one concrete implementation.

Even if it does, for a mild behavior change or a test implementation, the simple fact that Java methods are virtual-by-default is a huge benefit here.

C#, on the other hand, is final-by-default. This makes code much more annoying to deal with unless it implements an interface and/or is thoughtfully written with these cases in mind.

Re:Generating a Java program with 90% less code by acidictadpole on Wednesday December 04, 2019 @12:03PM (#21703995)
If you know there'll only be one concrete implementation, then yeah don't bother.

What people sometimes forget though is that any implementations of this in your tests are also concrete.

Some things like a DB accessor, will use a mocked/lite implementation in testing for code that doesn't need access to the db (but still needs to be provided data) to test it's functionality.

Re:Generating a Java program with 90% less code by zzbzq on Wednesday December 04, 2019 @12:14PM (#21704169)
I strongly agree with this, but if are using an inversion of control pattern for your business logic vs. I/O, then interfaces are often needed to prevent circular references. If using multiple compilation modules, this becomes evident because the code wouldn't even compile without the interface! When using this design, interfaces can sometimes be required more often than not.

That's the litmus test I use to determine if I need an interface: Will the code compile without it? If not, the interface is declared alongside the code that depends on it, and the implementation is in a second compilation module which depends on the first. Inversion of control.

Re:Generating a Java program with 90% less code by whycombagator on Wednesday December 04, 2019 @12:28PM (#21704393)
I generally agree, but you can have the inferface and implementation in the same file.
Re:Generating a Java program with 90% less code by Roboprog on Wednesday December 04, 2019 @08:29PM (#21709156)
I use the term “monomorphism”, as an antonym to polymorphism.

Yeah, not good.

And you meant update 3 files, not 2. You forgot the 1 file that uses the 1 implementation, which should have simply been nested the only place it was used.

Re:Generating a Java program with 90% less code by protonimitate on Wednesday December 04, 2019 @12:50PM (#21704716)
> I'm strongly against creating interfaces for non-library (not shared) code, that will only ever have one concrete implementation.

I agree with this, but the problem I see is that people have bad judgement when thinking about if something will only be implemented once or not.

Personally, I don't think the boiler plate / interface bloat is as cumbersome as others do. I'm currently working in a code base where things were decided to "never change", and now we need to change those things.

In a perfect world, I'd rather have less abstract code that never changes. But if it's a choice between poorly written highly coupled code or poorly written code that relies on interfaces, I'll take the interfaces and their bloats.

Re:Generating a Java program with 90% less code by apta on Wednesday December 04, 2019 @06:04PM (#21708154)
Ironically, I see this in golang all the time. Interfaces are defined with a single implementation in the code, and then the interface is used to generate mocks.
Re:Generating a Java program with 90% less code by sfblah on Wednesday December 04, 2019 @11:35AM (#21703671)
Interfaces in that case can be useful for unit tests since they enable mocking.
Re:Generating a Java program with 90% less code by Quekid5 on Wednesday December 04, 2019 @12:00PM (#21703966)
You can do that with classes -- as long the dependents don't instantiate their dependencies directly.

However, I personally like interfaces (well, traits, I'm doing scala), because it makes it much easier for readers to understand what bits are supposed to be part of the interface and which parts are supposed to be an internal implementation detail. Without interfaces it's really easy to accidentally change e.g. a return type into a more concrete one which accidentally leaks impl. details and suddenly other bits of code will come to rely on those impl. details. I work on rather large/complicated systems and I've seen this gradual spaghettification time and time again.

Disclosure: I'm usually the person who gets called in to fix the mess -- so that might bias my perceptions here.

Re:Generating a Java program with 90% less code by tcoff91 on Wednesday December 04, 2019 @12:01PM (#21703978)
With Java you can mock concrete classes using mock libraries which can change a class to a mocked class at runtime.
Re:Generating a Java program with 90% less code by commandlinefan on Wednesday December 04, 2019 @11:20AM (#21703472)
The Spring "Framework" essentially demands this, though.
Re:Generating a Java program with 90% less code by Eduard on Wednesday December 04, 2019 @11:35AM (#21703660)
Not true, and where the Spring Framework <strong>allows</strong> to use interfaces only (i.e. without having to write an implementing class) it's for neat reasons, e.g. autogenerating Spring Repositories.
Re:Generating a Java program with 90% less code by playworker on Wednesday December 04, 2019 @12:48PM (#21704701)
I think the GP is referring to the use of interfaces with only one implementing class, rather than interfaces with no implementing class. i.e. you end up creating a UserProvider and UserProviderImpl for every service class you write.

OP is probably referring to the JDK Proxy support which is used by Spring and requires classes to implement at least one interface.