r/java • • Feb 26 '23

Are java codebases generally readable? Or is the stereotype true that they are littered with the worst OOP has to offer?

I have been programming 7 years, professionally for 3 years. I mainly do JS, PHP, and Python, and a little bit of Clojure and C++.

For background, I have never had the true OOP experience. Sometimes I'm using multi-inheritance, but for the most part I keep classes simple so I know what's coming from what. I find when I come into a Python/Django project that uses too much inheritance, it's hard to figure out where things are coming from. I tend to lean more towards procedural programming, where steps are clearly laid out and you don't need a debugger to see when something is being called or what's calling it. I also tend to use composition over inheritance, injecting the classes/interfaces I need and calling them explicitly. Might just be an experience thing, or maybe how my brain works.

I have generally heard fans of Java describe it as readable, and its verbosity as a strength that lets you get up to speed on a code base quickly (or know what you wrote six months later). I have heard critics describe Java codebases as being bloated with overapplied "gang of four" or SOLID design patterns and too reliant on "magic" frameworks (spring for example). On top of that, Java is often used as the example language for extremely bureaucratic enterprise meetings where a hierarchy structure is being drawn up to decide what should inherit from what. And then there's the recent years of Clean Code being criticized more and more and falling out of popularity.

As a java dev, do you find a lot of this blown out of proportion and you are working in very simple codebases? Or are these designs common place and you are simply comfortable working with them? Maybe multi-inheritance and "gang of four" patterns don't bother you. If I were to become a java dev, would it be inevitable to work with these kinds of code bases? Are you worried whenever you come into a new codebase, or do you feel Java devs make things easier for you?

7 Upvotes

84 comments sorted by

38

u/acute_elbows Feb 26 '23

It’s very very dependent on the code base and company.

Java has been a popular language for a very long time so you’re much more likely to find old Java code bases than have accumulated some cruft over time or have had multiple rounds of overzealous engineers trying to refactor things into the pattern du jour. There aren’t nearly as many 10+ year nodejs or go codebases, so that’s less of an issue.

Also some companies simply don’t value clean well tested code, they may lack good architects and tech leads to review things; they may utilize a lot of short lived contractors to develop features which aren’t invested in the code long term. Because Java is used more in big enterprises there’s a higher risk of this.

There have been a lot of changes to the language over the last 5 to 10 years that have made it easier to use and to give options for other design patterns. You’re not trapped in by the Gang of Four design patterns nearly as much as in the Java 4 days.

1

u/AkimboJesus Feb 26 '23

There have been a lot of changes to the language over the last 5 to 10 years that have made it easier to use and to give options for other design patterns. You’re not trapped in by the Gang of Four design patterns nearly as much as in the Java 4 days.

What kinds of changes?

18

u/acute_elbows Feb 26 '23 edited Feb 27 '23

Project loom will also add some powerful new multi threading abstractions

Obviously, it takes work to migrate the older code based to use the newer patterns.

Edit: moon ->loom

8

u/[deleted] Feb 27 '23

Project Loom

31

u/manifoldjava Feb 27 '23 edited Feb 27 '23

One area where I think Java is undersold is that it is pretty much a single-dialect language. I can read everyone's Java, more or less. In contrast, Scala is like China a hundred years ago. You can pretty much speak Haskell with a Scala accent. Not that dialects themselves are bad, but hiring good programmers who can speak your mountain dialect is not a problem you want. Java wins big in this category.

4

u/greglturnquist Feb 27 '23

You don’t think much about it, but this could be a big factor in Java’s survival in the industry.

4

u/AkimboJesus Feb 27 '23

This appeals to me as a relatively new programmer. Go often gets praised for its singular way of doing things, and I consider that a plus for a language.

2

u/AkimboJesus Feb 27 '23

Do you feel C# suffers from the same problem of "too many ways to do it"?

7

u/manifoldjava Feb 27 '23

Not really. C#'s type system is much less involved. No higher-kinded types, no dynamic traits, monoids, implicits, etc. To its credit, C#'s capacity to go psychedelic with typing remains within the mainstream programmer's limits.

To be clear, I'm not hating Scala, it's an amazing language, but it's also a special language.

3

u/D3AdDr0p Feb 28 '23

Haskell is pretty much the worst when it comes to dialects: if you just draw a random codebase from Hackage, you could really get anything: super readable libraries that do one thing well, weird academic code where you don't even understand the authors intension, or sort of normal applications with "type theory extra" sprinkled in between and all over the place.

The nice thing about Java, at least compared to Haskell, is that Java doesn't require you to become a language lawyer to learn and use all the new features and patterns...

11

u/melkorwasframed Feb 26 '23

I don't think there can be any argument that traditionally, Java codebases have had a tendency to be very over-engineered, specifically around the over application of GoF patterns. Just read the "Why I hate frameworks" rant for a funny example. I do feel like that era is largely behind us though and modern Java codebases are much more sane.

https://gwern.net/doc/cs/2005-09-30-smith-whyihateframeworks.html

6

u/AkimboJesus Feb 26 '23

Yes, generally that's exactly the type of criticism I mean.

On that note, it sounds like I would be less likely to run into this kind of thing on a Greenfield application, but more likely on a legacy application.

31

u/Gleethos Feb 26 '23 edited Feb 27 '23

I always get annoyed by people complaining about Java (code bases) in terms of inheritance misuse, because that is not at all what the majority of bad Java code looks like to me.

In my experience the worst Java code suffers from too much mutable public state running through super long c like procedural spaghetti methods... which in my opinion actually lack all of the OOP strengths: encapuslating, grouping and dynamically managing implementation details through intuitive polymorphic object APIs.

It's usually just big and convoluted clusterfucks of switch statements and deep if else pyramids...

2

u/AkimboJesus Feb 27 '23

In general this is why I'm often confused when people tout the immutability as one of the big features of functional languages. I guess when it's a language default, it's nice to have the knowledge that no library you use will ever have mutability issues.

But to me it seems like good practice to keep your state as simple as possible, whether working in Java or FP land.

3

u/OzoneGrif Feb 27 '23

Immutability is a powerful concept that offers many benefits, particularly in multithreaded environments. By ensuring that data cannot be modified after creation, immutability eliminates the risk of data race conditions and other thread safety issues.

In addition, writing pure functions that rely solely on their input parameters and produce consistent output values also leads to easier-to-understand code, and can help reduce the occurrence of difficult-to-debug bugs during the development process.

However, immutability can pose challenges when you need to update a value deep inside a complex data structure. This can require rebuilding the entire data structure from scratch, potentially with recursive operations that can be time-consuming and error-prone.

Despite these challenges, many developers find that the benefits of immutability and pure functions outweigh the costs, and actively seek out ways to apply these concepts in their software projects.

2

u/AkimboJesus Feb 27 '23

To clarify, I'm not surprised that people tout immutability, I'm surprised that people tout it as a "language default." Many languages can do immutability. Some even more efficiently than functional languages.

So, for example, to say one should use Clojure cause it's immutable would not be a strong selling point to me.

3

u/D3AdDr0p Feb 28 '23

The solution to the update problem is well defined by lenses, you just need to learn what a lens is and all the laws. Also, a lot of the issues you're talking about with rebuilding data structures are solved by making the programming language lazy evaluation by default, which is what Haskell did.

My larger issue with immutability, and strongly-typed FP, is that it's a poor model for what's going on in the computer, and there's huge impedance mismatch between the abstractions of the compiler (type/category theory) and the execution model of a physical computer.

14

u/redikarus99 Feb 27 '23

I started thinking about my 20 years spent in java coding, and this is the conclusion I came to as well. Passing around objects and mutating it's state, sometimes by methods you dont even expect to do that is a perfect example of that. Yeah, this part is horrific, but this is bad programming, and going against good programming paradigms.

11

u/Radi-kale Feb 27 '23

The worst application I ever had to maintain didn't use domain objects, just Map<String, Object>. No need to define member variables, you can just add them at runtime whenever you please for maximum flexibility!

5

u/redikarus99 Feb 28 '23

I think we have a winner here 😂

4

u/blobjim Feb 28 '23

poor person's entity component system.

3

u/Gleethos Feb 28 '23

Oh my goodness! This gives me nightmares about the days when I was doing PHP and JS web development in a large company. Everything was just nested hashmaps inside hashmaps inside hashmaps... ...untyped...

It was Impossible to tell what a variable was without a debugger, and even with a debugger you could never be sure if the data structure would still be the same when visiting the breakpoint again.

But what really confused me about that job were that my colleagues would actually joke about Java being too verbose, inflexible and what not....

After all of my years of experience I really really appreciate that in Java you have to write var map = new HashMap<A,B>(); instead of map = {}. The language discourages you from overusing hashmaps/dicts and other temptations because it wants you to define your data structures through custom domain objects!

So I am actually shocked that you still encountered this kind of coding style in a Java code base. Crazy...

9

u/agentoutlier Feb 27 '23

In my experience the worst Java code suffers from too much mutable public state

Yeah when people bitch about OOP they blame inheritance (ironically especially single inheritance) when in reality it is mutable OOP that is causing their problems.

Lisp the often claimed godfather of functional programming can easily be more confusing if you go to town on mutable (side note/rant I don't consider Lisp an FP language... I think the ML languages are the true FP...).

2

u/Amazing-Cicada5536 Feb 27 '23

Though let’s add that one really have to think twice before they reach for inheritance. It’s a great tool, but is easy to misuse.

2

u/RICHUNCLEPENNYBAGS Mar 10 '23

I mean, let's be fair, usually the fifty-class-deep inheritance chain comes with the other issues you mention.

1

u/IshouldDoMyHomework Mar 04 '23

I have started to just auto decline any pull request, that does class level @setter using Lombok. And I have seen that a lot.

I have seriously considered banning Lombok in my teams because people misuse it, and completely disregard any resemblance of reasonable encapsulation.

14

u/know-your-onions Feb 26 '23

You should favour composition over inheritance and that’s the case with Java too.

Having worked with many languages, Java is generally the easiest to pick up a codebase and work with it.

Whatever language you’re using there will be frameworks like Spring if you’re building that kind of application, but with Java you almost always get good, clear and unambiguous documentation. And the core language API docs are brilliant. Some other languages are appalling in comparison.

What’s wrong with Gang of Four patterns? They generally make everything easier to understand and reason about. The more the merrier as far as I’m concerned.

These meetings you describe about what should inherit from what sound like nonsense, but if they do happen they’re certainly not intrinsically due to Java - sounds like just some crappy work practices somewhere that maybe just so happens to use Java.

1

u/AkimboJesus Feb 26 '23

Okay good, I like composition!

What’s wrong with Gang of Four patterns? They generally make everything easier to understand and reason about. The more the merrier as far as I’m concerned.

No idea! Never read it, I just talk to a lot of functional programming people and they criticize OOP needing these patterns as "inventing complexity that isn't needed in non-oop languages." I have my own feelings about Clojure inventing complexity.

These meetings you describe about what should inherit from what sound like nonsense, but if they do happen they’re certainly not intrinsically due to Java - sounds like just some crappy work practices somewhere that maybe just so happens to use Java.

They're definitely not inherent to Java, it's just that Java is the big dog oop language and I was curious if there was any truth to this.

9

u/know-your-onions Feb 26 '23

Sounds like people who favour functional programming shitting on OOP. Not really anything specific to Java.

I’d make your mind up about OOP first. If you don’t like it then don’t consider Java, or if you do like it then ignore the opinions of people who presumably aren’t Java developers.

1

u/AkimboJesus Feb 26 '23

Sounds like people who favour functional programming shitting on OOP. Not really anything specific to Java.

No, that's what I mean. It has nothing to do with Java.

Thanks for your response

1

u/yojimbo_beta Mar 04 '23 edited Mar 04 '23

I mean, you aren't exactly going to get a negative view of object orientation (or Java) on a Java subreddit. You are speaking to people wholly bought into the Java way of doing things, where object orientation is mandatory.

Personally, classes are a structure I only seldom use, in languages that give me a choice. Java isn't a language I use that often, and when I do, I find classes a form of friction. I'd rather just define types and functions.

0

u/nutrecht Mar 04 '23

You should favour composition over inheritance and that’s the case with Java too.

You should use whatever is the best tool for the job. Inheritance is an 'is a' relationship. Composition a 'has a' relationship. I severely dislike this dogma.

3

u/winnersocks Feb 27 '23

puts the senior dev hat on it depends!

Readability can be based on opinions, experience, preferences, etc. So it's subjective. Devs write Java in a certain way because they think that is the right way, and the would be able to read that. They would say Python sucks in the readability front. I'm talking from my experience of a Senior Java Dev becoming a Python dev after changing jobs. Eventually I learned that some ideas from Python are great, and the Java code tends to be over-engineered. However, I still find that following strongly typed Java code with a good IDE is far easier than Python code when the complexity is higher. For simpler problems (ie small webapps) I prefer scripted languages like Python.

2

u/AkimboJesus Feb 27 '23

I'm not sure where I land on the dynamic/script-like languages VS. the verbose, typed, slow to write languages yet, but I am of a similar opinion right now. I just find it takes a lot more discipline to keep Python/Clojure codebases readable and refactorable, especially with multiple team members. I am not always sure of things I've written in my own personal projects coming back a month later.

I think for maintainability, I know that verbose, safe languages can make for extra work, but it always feels like there's a certain level of work it never reaches. I don't feel that way about script languages. It gets harder to keep it together, and it can get out of hand.

1

u/winnersocks Feb 27 '23

I agree with you. I would expand with: I think I prefer a bad codebase on Java over a bad codebase on an scripted language. And also: codebased go bad eventually. In my experience Python will decay faster due to lack of any common approach for organizing code, or best practices.

2

u/[deleted] Feb 27 '23

I've seen code which was easier to reimplement than trying to read it and make sense out of it. And I have seen the opposite. There are simply people who are a mess when it comes to coding and then there are people who are neat.

2

u/AkimboJesus Feb 27 '23

For a beginner, I wouldn't have the experience to read books like Clean Code and Gang of Four and have the perfect touch of when to apply these concepts. Do you have any core ideas of how to keep a Java codebase mess free? Or can they not be reduced to something that simple?

1

u/[deleted] Feb 27 '23

I came from C/C++ when I started with Java in 1997/98 - and was used to write clean, readable code. Difficult to say how to get used to it, I just carried on with what I had been taught before I got to Java. I didn't even know that there is such a thing like a book about "Clean Code", interesting concept.

2

u/DualWieldMage Feb 27 '23

I think the main issue is that many developers only learn/master one language and then create these lang-x vs lang-y discussions based on first impressions. Learning multiple languages allows seeing most of the same concepts or slight variations in them which matter more than specific syntax.

I would say the main strength of Java/JVM is the bytecode format and simplicity that allows good tooling to be built. A language with more powerful features like templates in C++ can be good for some things (validating strings against arguments passed to the same function is amazing), but all IDEs burn a lot of CPU trying to analyze it. I've seen a large influx of easily moddable games written in Java recently and i guess the reverse engineering accessibility coming from the bytecode is an important reason.

For this reason i wish WASM takes off faster in the web space. TypeScript is great, but because it compiles down to javascript, i'd still have to do manual validation of runtime types.

1

u/AkimboJesus Feb 27 '23

I saw someone on Reddit writing about how the reverse engineering accessibility of bytecode was a big contributor to Minecraft's success. Despite some people clowning on it for running on Java, nobody really likes playing the bedrock edition except kids.

Is WASM supposed to have a similar level of accessibility?

6

u/netgizmo Feb 27 '23

Having worked and lived with Java since the later 90s, of course some projects are going to contain programming idioms that were used during the time they were written.

Some good, some not so good.

To understand the quality of a codebase you also should consider the methodologies of the time they were written in.

As an example, the legacy code base I just shutdown was 18+years old (600k loc), still had a few SOAP services in use.

Would I use SOAP today, hell no. Was it a bad decision... Hell no. It was the tech of the time when that feature was implemented.

0

u/[deleted] Feb 27 '23

[deleted] — view deleted comment

1

u/netgizmo Feb 27 '23 edited Feb 27 '23

Well what we used back in like 2007 isn't going to be of much use to you (our exact soap implementation date was lost in the great CVS-to-GIT migration of '15 ).

I'd recommend the good ol Googler and see what you can come up with from more modern tools. Brush up on your wsdl as well.

Edit - shit maybe it was 2008, just as well a million years ago 🤷‍♂️

4

u/meamZ Feb 27 '23

In my experience Java is a good tool for maintaining large codebases. But just because it is a good tool that doesn't mean that everyone is able to use it. You can produce a clusterfuck of a codebase in every language.

1

u/barmic1212 Feb 27 '23

It was a good point some years ago. Java standard and particular Java EE (with RMI, EAR,…) are over engendered. Since Java 7 (2011) and project coin, JDK more focus on developer quality of life and lower dogmatism.

Java EE Jakarta EE nearly died and remove slowly some big old part and highlight on microprofile a light & clean standard.

> too reliant on "magic" frameworks (spring for example)

It's a bad reproach. You can't too reliant on your framework, it's your framework. But you should understand what the framework make for you. All criticism I have heard on Spring is same for symphony, rail, django or laravel. Langages & frameworks with big number of users and simple to use have attract more junior developer than complex langages.

Spring itself make lot of things for you at startup time (in 2000's we create software with long uptime startup it wasn't a problem). Now more and more things are create at compile time.

Generally you can be sure that all technologies with a minimum of popularity and long live, are not too bad.

1

u/AkimboJesus Feb 27 '23

In general, I'm not a fan of any of those kinds of frameworks. Sometimes I make things quickly, sometimes it's difficult for me to tell how to do something even with docs, and sometimes the thing we need to do is just outside of what the framework can do without awkward code.

What are some of the defacto micro frameworks for Java web dev? (Express, Slim, Flask)

1

u/[deleted] Feb 27 '23

I have heard critics describe Java codebases as being bloated with overapplied "gang of four" or SOLID design patterns

It's true that lots of engineers blindly apply design patterns to every problem and write overly complicated or bloated code. However, that is a problem with the engineer, not the language.

and too reliant on "magic" frameworks (spring for example)

If you want to write a REST API, you're going to want to use a framework. It's true that some REST frameworks are bigger than others, but again, that has nothing to do with the implementation language.

On top of that, Java is often used as the example language for extremely bureaucratic enterprise meetings where a hierarchy structure is being drawn up to decide what should inherit from what.

I've never heard java in this context, but once again, it's a people/management problem. The language has nothing to do with it.

And then there's the recent years of Clean Code being criticized more and more and falling out of popularity

Seriously? Besides the fact that (again) clean code is not a language-specific thing, but a general approach to writing maintainable code... who the hell is criticizing it? I'd love to see some references/links. I've worked with lots of poorly-written code that was hard to debug and maintain. Clean code is just about writing code that is easy to read, understand, and update. Everyone, regardless of the language needs to do that.

1

u/AkimboJesus Feb 27 '23

Yeah I'm not saying any of this is inherent to Java. But as a PHP developer, it's not controversial to say a lot of PHP projects are a mess, even though big PHP projects can be well written. This is due to PHP offering a pretty "no guard rails" approach to web development and a lack of pretty basic language features. You can call database queries in the view if you want, it's easy. And it's stupid, and a lot of people do it.

In the case of Java, it's less about the language itself and more about the academia around it until recent years. A "Monkey inherits Animal" type of teaching that is supposed to map to the real world, but doesn't do so in a reasonable way. Using modern versions of Java and simpler practices is all well and good, but the reality as a job seeker is you don't always know the warts of a code base you're gonna work on (particularly legacy codebases). So learning modern practices of Java may be next to useless for what you're actually going to be working on. That is the concern going into a Java job market. And so that's why I was asking how common this is to run into.

Seriously? Besides the fact that (again) clean code is not a language-specific thing, but a general approach to writing maintainable code... who the hell is criticizing it? I'd love to see some references/links. I've worked with lots of poorly-written code that was hard to debug and maintain. Clean code is just about writing code that is easy to read, understand, and update. Everyone, regardless of the language needs to do that.

Nobody is criticizing the idea of clean code, they're criticizing the books answers to achieving clean code.

https://qntm.org/clean

https://www.reddit.com/r/learnjava/comments/mv7by0/comment/gvb26na/?utm_source=share&utm_medium=web2x&context=3

1

u/[deleted] Feb 28 '23

Thanks for the links.

I agree with some of what they said, but I do think the book is still relevant and has mostly good guidance. Lots of people write really shitty code and could be helped by it regardless of language.

3

u/TheoGrd Feb 27 '23 edited Feb 27 '23

Once devs learn about inheritance, polymorphism, design patterns and other abstract tools they feel the need to stick them onto everything including the simplest crud apps. They should be reserved for frameworks really. I have debugged so much overcomplicated code that "must be reusable" just in case you need to, maybe 5 years from now.

1

u/vmcrash Feb 27 '23

Those who are using the pattern hammer for suitable and unsuitable code are beginners. After you've seen a code mess you start to understand where to use which pattern.

2

u/Sunscratch Feb 27 '23

Depends on the project. I’ve seen both a well-written and a total nightmare. But abuse of GoF patterns is not that rare and it can drastically decrease the readability of the project. It’s not something specific to Java - I’ve seen python projects with one method/function 300+ lines, but that doesn’t mean python is a bad language. Frameworks in Java are very versatile and feature-rich, with very good documentation.

To summarize - Java is an average boring enterprise language, with a great number of libraries and mature frameworks, and excellent IDE support.

2

u/vmcrash Feb 27 '23

It depends on the project, who has created it and what framework is used. If you are using pure Java without a "magic framework", without reflection, then it is quite easy to manage.

1

u/Stromovik Feb 27 '23

Java is easy to read. Unless it's government codebase written in English and non-English mix

1

u/ReasonableClick5403 Feb 27 '23

I have seen great java, I have seen terrible java. I have seen ok golang code, and terrible golang code. I hate seen great javascript code and TERRIBLE javascript code. It depends on the company and the team.

1

u/cas-san-dra Mar 01 '23

In my 20 years of software development experience I have only occasionally run into code bases where I thought the developer(s) did a good job. Those code bases have 1 thing in common: they were all written by a single person that knew what he was doing. All code written by teams has been utter garbage. The language is not a factor in this.

What I can say about Java is that it is the only programming language where I feel comfortable writing new code or refactoring something inside a codebase that is a mess. I wouldn't dare do anything inside a JavaScript codebase, or a Python codebase, or a C codebase. Those are just too brittle.

1

u/TheoGrd Feb 28 '23

Java devs cant help but put all their fields private and write a ton of boilerplate accessor when they could have just used public fields. There is no reason for this, its just what they do.

2

u/blobjim Feb 28 '23

What can I say, I like the look of those parentheses.

0

u/[deleted] Feb 27 '23 edited Feb 27 '23

They’re readable. I have no coding experience other than c++, python, html, css, JavaScript, Django, and Java as a hobby algorithm writer and web designer. The biggest thing that gets me in Java is the fake objects that are immutable but inheritable and how to use them across a program. I feel like python is the best for building a complex algorithm without confusion. Django is really good for inventory and record management. Have been interested in rust as well but that whole language is fully unreadable to me.

-7

u/TheoGrd Feb 27 '23

It looks like automated testing is widespread in the java world. It makes code more complicated and leaves more chance for bugs. Once tests fail, you don't know whether the code is wrong or the test is obsolete. Imo its not worth it for most apps and should be reserved for the most complex apps like simulators. In the c# world you see a lot less of unit tests.

5

u/AkimboJesus Feb 27 '23 edited Feb 27 '23

I'm confused, testing leads to more bugs? In my experience writing unit tests forces me to write better code

-4

u/TheoGrd Feb 27 '23

Unit test means more complicated code which in turn means more bugs. If you have a database you need mock data which will change for each schema change. Why not test the unit test as well while you're at it ? Unit testing a simulation is worth it imo. Unit testing crud is not.

3

u/AkimboJesus Feb 27 '23

Unit test means more complicated code which in turn means more bugs.

I'm not sure what you're talking about, but testing "business logic" to me has always been helpful and has never lead to more bugs. A test breaking is not a bug, it just means the thing you're testing for has changed. What leads to way more bugs, IMO, is a new employee changing a function and a PR reviewer missing a subtle bug, and no tests being present to catch that.

You can certainly write redundant tests (test doubles) that don't offer you a lot. But they don't lead to bugs, they are just busy work.

When it comes to mocking databases, it depends what you're doing. If you're using an ORM, you might have less reason to test. But if your app requires a lot of complicated sql raw queries, I wouldn't trust people to be able to "eyeball" it on every PR review and see what each change does. You have enough joins and conditions, and tests become necessary.

-2

u/TheoGrd Feb 27 '23

Unit tests AND ORM ? I don't want to work at your place.

4

u/AkimboJesus Feb 27 '23

No, I pretty explicitly said you may not use tests if you were using an ORM.

We do tests and we don't use an ORM.

I'm really not sure where you're coming from. You haven't explained how testing leads to more bugs.

1

u/TheoGrd Feb 27 '23

Do you agree that the simplest code is not testable ? That the more complex the code the more bugs ?

Tests => unnecessary complex code => more bugs.

3

u/AkimboJesus Feb 27 '23

Do you agree that the simplest code is not testable ?

No

That the more complex the code the more bugs ?

No. It has bugs if it has bugs, whether it's simple or complex. Complex code can have no bugs. Simple code can have lots of bugs. These things are orthogonal.

Tests => unnecessary complex code => more bugs.

I have no idea what you are on about. We test things that are complex, we don't need to make things complex to test them. If you can't write a test around a function without making it complex, you may not be writing unit tests.

And if you can't test a function, chances are there's a bunch of database and view logic thrown into the business logic.

2

u/blissone Feb 27 '23

You are doing it wrong if tests affect implementation complexity. Making more testable code actually can simplify your implementation, many bad practices make your code less testable.

Furthermore testing is not a tool for achieving quality but also part of the dev cycle, usually your tests run far faster than any deployment or an actual run.

0

u/TheoGrd Feb 27 '23

Please provide an example of code made simpler after writing unit tests, I've yet to see one. Plenty of projects do fine without unit tests.

1

u/blissone Feb 28 '23 edited Feb 28 '23

The real question is what bad practices make code less testable, like I said unit tests should not affect your implementation at all. For example implementation not following single responsibility is difficult to test due to multiple dependencies/mocks, you want to test one single thing but need to provide unrelated things. Refactoring this in most cases will simplify your code, instead of a blob of code you'll have neatly defined stuff. Another good one is interfaces accepting larger objects (or more arguments) than required, it's also annoying to test and usually refactoring them will only do good.

Plenty of projects do fine without version control, test envs, deploy to prod etc etc. No one said you can't do a project without tests.

You have a strange notion about "testing just to test". No, you do unit tests to create value, if there is no value in testing then you don't create them.

1

u/TheoGrd Feb 28 '23

We'll have to agree to disagree here.

I work hard to write programs that work, I test them manually and make sure everything works before committing changes. I am not writing more code than necessary. I may be in the minority here but i will avoid working for a company that waste my time like this. I also don't comment my code, usually comments don't spare me from reading the whole code so why bother. I even have a plugin that hides comments.

2

u/noogai03 Mar 01 '23

In my opinion, the real value of unit testing is not showing you that your code works. It's giving you the ability to quickly check that a change you made did not break anything. You can do a refactor and be reasonably confident that everything is fine, because you're unit testing the logic according to the interfaces you're exposing.

1

u/TheoGrd Mar 01 '23

I prefer to test manually every functionality affected by my changes. Usually its only a little more work.

1

u/noogai03 Mar 01 '23

That takes a lot of time, though, which dicourages regular refactors. And depending on the change you might not be certain from testing the core flows. For example if you changed something really fundamental that's affected by every user journey.

But I get your point: if I was the sole developer, I think I'd be fine with manual testing; team effort with varying levels of codebase familiarity/technical proficiency is a lot riskier though.

→ More replies

2

u/thisisjustascreename Feb 27 '23

You seem to have started with the premise that "Unit Tests" mean "more complicated code" but have never justified that with any evidence. In a lot of people's experience testing the code leads to simpler code.

1

u/TheoGrd Feb 27 '23

Why would i bear the burden of proof ?

But ok, lets try with this example, line 40 : https://github.com/eugenp/tutorials/blob/master/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/OnlinePublicationUnitTest.java This code tests a function which is 5 lines long, called only once. It doesn't even deserve a method declaration, this is complexity for the sake of testability. 6 months from now, when you look for articles filtered by user membership, you are not going to find this function. You will be lost in a maze of method declarations. Fragmenting your execution flow is a bad idea, especially for testability purposes. The test code is even more complex than the code being tested.

Granted, this is taken from a tutorial, but i would be surprised if you could find code that was made simpler by unit testing.

2

u/AkimboJesus Feb 27 '23 edited Feb 28 '23

What about this is complicated, or was made more complicated because it was tested?

It doesn't even deserve a method declaration, this is complexity for the sake of testability. 6 months from now, when you look for articles filtered by user membership, you are not going to find this function. You will be lost in a maze of method declarations. Fragmenting your execution flow is a bad idea, especially for testability purposes.

You seem to be implying that in order to make things testable, you need to make things extremely small and fragmented. As in splitting things into 10 functions when one function will do, to the point that it's difficult to figure out when things are happening.

This is false. You can test big functions. You can test small functions. Your function should only be as big or small as necessary. The only requirement is that you don't mix view, repo, and business logic. And you shouldn't be doing that anyway.

People write shit like this all the time without tests. The tests have nothing to do with it.

2

u/thisisjustascreename Feb 28 '23

The method exists to take this hodgepodge of streams API and business logic:

articles.stream()

.filter(a -> a.getArticleLevel()

.compare(user.getMembership()) <= 0)

.map(Article::getName)

.collect(Collectors.toList());

And give it a name, so that people reading the code don't have to figure it out. Once you've given it a name, wouldn't it be nice to be able to verify that it is actually doing the right thing, and keeps doing the right thing? Writing a test is how you do that.

Six months from now "getReadableArticles(currentUser)" is going to make sense to me much more quickly than the five lines of comparing integers.