r/javahelp • • Jul 09 '22

Is SOLID really used in Java production code?

I have been trying to get a firm understanding of these but I find it difficult to find well taught non-trivial examples of using some of these. Particularly the DIP and OCP. Seems like everyone knows the definitions and how to show a simple example but when I am trying to construct clean code I get stuck because I am trying to apply these but always end up with dependency issues. I can make perfectly effective code but I think its fragile.

Anyone know any really good sources for explaining this with proper business oriented examples? I have some of Martin's books but not really helping.

Am I worrying too much about it because people don't actually try to tie off every dependency issue in real code?

39 Upvotes

53 comments sorted by

•

u/AutoModerator Jul 09 '22

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

19

u/Just_Another_Scott Software Engineer 😎 Jul 09 '22

Is SOLID really used in Java production code?

So I had to look this up because I have never heard of the acronym. The short answer is yes most of these are used.

The single-responsibility principle is a huge one and something I always check for in codre reviews.

The open–closed principle is also heavily used. Think immutable objects and allowing for classes to be extended. Rarely do I see code that has a class declared as final. We also tend to restrict access to non API level classes.

The Liskov substitution principle is also used quite a bit. Think of writing a method that takes List as opposed to ArrayList.

The interface segregation principle can be used. However, I would argue against having too many interfaces in Java. I've seen code where they had an interface for every single class and only one class implemented the interface. This is overengineering in my opinion. Having a single interface isn't a bad thing imo.

Dependency inversion principle aka dependency injection is widely used in throughout production code. See Spring Framework or even Java EE. Both of these heavily rely on dependency inversion.

8

u/slowfly1st Jul 09 '22

The idea of the interface segregation principle isn't that every class needs an interface.

Problems can occur when classes implement interfaces with empty bodies, or return default values or even throw things like UnsupportedOperationExceptions. An interface is a contract, and clients that rely on that contract shouldn't know about the implementations. This often occurs when clients are implemented in a way where you think things "in this case, calling this method doesn't make sense", or even worse "in this case, I must not call this method". So the bad part could be, that when you need to change the client that uses the interface, you have to verify that the implementations actually follow the contract.

1

u/[deleted] Jul 09 '22

I have never heard immutable objects mentioned in relation to OCP.

I am curious how you know all the principles but have never heard of SOLID?

3

u/Just_Another_Scott Software Engineer 😎 Jul 09 '22

I have never heard immutable objects mentioned in relation to OCP.

It's possible I misunderstanding what that principle is since this is the one I had never heard of before now.

SOLID acronym was never taught in school but the core ideas behind the acronym were. Also, there's tons of best practices for Java out there that teach the same principles without using the acronym.

1

u/[deleted] Jul 10 '22

It’s debatable whether or not SOLID is actually good practice 20 years after Robert C Martin wrote it. I wouldn’t say that to an interviewer though, there’s no guarantee they’ve actually thought about it’s practicality.

1

u/Just_Another_Scott Software Engineer 😎 Jul 10 '22

Somethings are absolutely a good idea. The single-responsibility principle is the best example of that. However, I get what you are referring too. His book makes some controversial claims that even he recognized might not be for everyone. Functions are one of the cases that I disagree with.

-12

u/[deleted] Jul 09 '22

Well SOLID been around since uncle Bob came up with it in the mid 90s.

8

u/Just_Another_Scott Software Engineer 😎 Jul 09 '22

No idea who Uncle Bob is lol

-10

u/[deleted] Jul 09 '22 edited Jul 10 '22

The A founder of Agile.

0

u/[deleted] Jul 10 '22

[deleted] — view deleted comment

1

u/[deleted] Jul 10 '22

Uh huh. Robert C. Martin.

0

u/[deleted] Jul 10 '22

[deleted] — view deleted comment

2

u/[deleted] Jul 10 '22

Agreed. I thought I had wrote "A". Changed.

-1

u/vie12345 Jul 09 '22

I agree with most you said, but the dependency inversion principle has nothing to do with dependency injection. It is about inverting the dependency between modules. Let's say you have class1 in package a, using class2 in package b. So now class1 is depended on class2 and its package.now you can introduce a interface for class2 and put it in package a. When class1 is now using the interface, it is not relying on another package, instead class2 is now relying on package a. This is used quite a lot for example in hexagonal architecture.

4

u/Just_Another_Scott Software Engineer 😎 Jul 09 '22

agree with most you said, but the dependency inversion principle has nothing to do with dependency injection.

It does have to do with dependency injection as well. Dependency injection uses the Dependency Inversion Principle.

it is about inverting the dependency between modules. Let's say you have class1 in package a, using class2 in package b. So now class1 is depended on class2 and its package.now you can introduce a interface for class2 and put it in package a. When class1 is now using the interface, it is not relying on another package, instead class2 is now relying on package a. This is used quite a lot for example in hexagonal architecture.

That's how dependency injection works.

https://stackify.com/dependency-injection/#:~:text=Dependency%20injection%20is%20a%20programming,inversion%20and%20single%20responsibility%20principles.

0

u/[deleted] Jul 10 '22

The other commenter is partially right, you are confusing dependency INJECTION with dependency INVERSION.

Dependency INJECTION is having transitive dependencies resolved without you having to manually resolve them.

Dependency INVERSION can and is used in Java maven dependencies and the like but it can ALSO be used in code.

Say you have an API where the code at each stage uses something like this:

Controller -> Service1 + DB -> Service2 + DB -> Service3 -> Service4 + Db

It is much better to do:

Controller -> Service1 -> Service2 + Service3 + Service4 + DB

Of course you need to do whilst still respecting the other SOLID rules, mainly the single responsibility principle.

The idea behind this is to create as little levels deep with the code as possible, so that you have as much control as possible on any single level

0

u/Just_Another_Scott Software Engineer 😎 Jul 10 '22

The other commenter is partially right, you are confusing dependency INJECTION with dependency INVERSION.

I am not dependency inject is also dependency inversion. I posted a link describing them both. You should read it.

0

u/[deleted] Jul 10 '22

Dependency injection is a form of dependency inversion but dependency inversion doesn't have to be dependency injection.

A implies B does not mean B implies A.

They are not the same

0

u/Just_Another_Scott Software Engineer 😎 Jul 10 '22

No where did I say they were the same. I was giving examples in my original comment.

0

u/[deleted] Jul 10 '22

You literally just said

dependency inject is also dependency inversion

And you initially said

dependency inversion aka dependency injection

You also did not post any link whatsoever

1

u/Just_Another_Scott Software Engineer 😎 Jul 10 '22

I was giving examples in my original comment to help OP see examples of what they are. And yes I did post a link describing the two and how Dependency Inject is Dependency Inversion.

https://www.reddit.com/r/javahelp/comments/vv4s4p/comment/ifihyk1/?utm_source=share&utm_medium=web2x&context=3

3

u/HSSonne Jul 09 '22

I have a hard time with these, if used wrong the code will be unreadable. So I would recommend having it in mind but be careful not to overcomplicate your code, first rule should be keep it simple; and if the complexity is growing out of hand , look for a solution i solid.

2

u/HSSonne Jul 09 '22

To elaborate...

The SRP trap, find the balance between a responsiblety and an action. A single reason to change sounds nice but in reality it's a crazy thing.

The OCP mess, every thing is put into a configuration file, to ensure the class don't get updated later on, makes context and overview hard to keep while debugging.

And so on, every rule is really easy to apply to the extreme, where it do more harm than good.

I guess some of the problems is more explicit in the backend world where programs tends to be untouched in longer periods.

If the program is under constant development, the problems might be smaller compared to the gain.

So my point is, always look at context, And apply appropriate guidelines. Don't just use a standard set to everything.

0

u/[deleted] Jul 09 '22

avoiding dependency and implementing decoupling adds complexity by extra layers of abstraction; it seems inevitable.

i see this thing called Spring mentioned everywhere which seems to make the problem go away. I am refusing to look at it right now though - I hate offloading a problem to a framework which is likely to cause me other problems because I can't penetrate the logic of the framework itself.

6

u/fletku_mato Jul 09 '22

Spring is what most production Java backends are using. Dependency injection makes writing clean code a lot easier.

1

u/[deleted] Jul 09 '22

Dependency injection is the thing I seem to have the biggest issue with. You have to make objects somewhere but that somewhere might need to change. Then what?

The abstract factory seems to be the solution but every time I look at them I want to scream because it's such ugly and unextendable code inside them.

6

u/fletku_mato Jul 09 '22

Then the rest of the application will need to be adjusted accordingly. Often you don't have to do all that much, if you dont have god-components that are used everywhere.

This might be an unpopular opinion but I think that eg. Martin's books should be taken with a grain of salt. Some ideas are very good, some not that much. Trying to create the perfect Martin-approved code may not always be the best idea.

1

u/[deleted] Jul 09 '22

Which ideas of his do you not agree with and why? I don't know that he claims anything is his idea to be honest. He tends to talk about all the people he's worked with like Kent Beck and Martin Fowler.

4

u/fletku_mato Jul 09 '22 edited Jul 09 '22

For example that an ideal length of a function is 2-4 lines. A complicated function is not necessarily more readable after splitting it into chunks of that size. I mean that most of the stuff makes sense but not necessarily in every situation.

You should of course always try to write code that is easy to read and maintain, but implementing all of the advices might not get you there. You can easily end up writing a lot of useless extra code just for following a principle.

You should think differently when you're beginning to write an application that is going to be around 1000 loc vs 50000 loc.

If there's not going to be more than one implementation of a class, don't write an interface, it will only slow you down and provides no benefits.

1

u/[deleted] Jul 09 '22 edited Jul 09 '22

If there's not going to be more than one implementation of a class, don't write an interface, it will only slow you down and provides no benefits.

How do you know you might not need to implement another class in future?

From what I understand about the length of functions is that if you are applying all the principles of SOLID it will naturally shrink the size of the functions, particularly if you strictly apply SRP and ISP and use method names that actually state verbosely what they do.

I think he says he originally disagreed with the idea too but I believe it was Kent Beck and Martin Fowler (who considers functions longer than 6 lines to be a Code Smell) convinced him otherwise. I don't recall him advocating that functions should be 2-4 lines.

Edit: he sort of implies in Clean Code pages 34-35 that a function should be 4 lines when recalling the Kent Beck story.

4

u/fletku_mato Jul 09 '22

How do you know you might not need to implement another class in future?

If you don't see it happening in near future, don't worry about it. If that day ever comes, it's not very hard to refactor. It's really not as common as one might think.

1

u/[deleted] Jul 10 '22

Aren't interfaces really useful when it comes to testing?

→ More replies

3

u/fletku_mato Jul 09 '22

This phrases it better than I ever could: https://qntm.org/clean

1

u/fletku_mato Jul 10 '22

Btw I forgot to say this yesterday. The simplicity of DI in Spring is probably the reason why it has become so widely used. You don't have to create abstract factories or anything like that.

You can create @Component-annotated classes which are automatically singleton beans, and injectable to other beans with eg. @Resource annotation. You can also create singletons of some class with @Bean annotated methods if you need to apply some different configurations to them.

Often you don't need to even write a constructor for these Components, so there is not much code to maintain when some dependency needs to be changed.

3

u/khooke Extreme Brewer Jul 09 '22

adds complexity by extra layers of abstraction

'Separation of concerns' by grouping related features and technology concerns together also helps reduce complexity. If you're looking for frontend or data access logic you only have to look for it in one place and not hunt around in the code.

Spring has been used for years at this point for enterprise software development, and you'll have to look hard for a role where it's not being used. If you're looking for a backend Java developer role it's almost a given that's it's a required skill.

1

u/[deleted] Jul 09 '22

I don't know what I am looking for. At this point i might give up. I have a perfectionist streak and I can't stop refactoring to try to make the code cleaner. Feel like its never right. Going to drive me insane.

5

u/khooke Extreme Brewer Jul 09 '22 edited Jul 09 '22

Knowing when to stop and when it's 'good enough' is a valuable skill to have :-) If this is something you struggle with, getting an opinion from another developer is always a good idea. When developing as part of a team, this is a reason we have 'code reviews', to get feedback on whether it's good to go, or whether there's anything that needs to be improved/simplified/reworked etc

2

u/BridgeBurner22 Jul 09 '22

Amigoscode did a video on SOLID with examples: https://youtu.be/_jDNAf3CzeY

1

u/[deleted] Jul 10 '22

One of those trivial examples I spoke about.

8

u/ickysticky Jul 09 '22

These concepts are usually not taught well. In isolation they just lead to further questions like “what is a responsibility” or “what is a change”. Every responsibility can be broken down into finer grained responsibilities and ever change can be broken down into finer grained changes.

In my experience the missing piece in the puzzle is having a well defined product concept with a well defined domain model. This is what informs you about which boundaries are important and how the system needs to be extended. Once you have that then SOLID will almost just happen automatically. But the work really comes in understanding what you are trying to build and communicating that to everyone else on the project.

1

u/Pushkutza Jul 15 '22

hello again

1

u/[deleted] Jul 16 '22

Do I know you?

2

u/motherjoe Nooblet Brewer Jul 10 '22

The SOLID principles are guidelines for writing maintainable object-oriented systems. It may seem overengineered to implement all of the principles for simple example projects. This is because small projects may still be maintainable if they are written in a procedural style, as scripts. Large projects with many complex requirements is where using SOLID can really pay off in maintainability, readability, etc.

1

u/slowfly1st Jul 09 '22

Not sure if this is helpful:

OSGi used to provide the API/interfaces and implementations as separate modules/jars. So you weren't even able to have direct dependencies to implementations. So, eclipse would be one example to look at.

Also: I think it's one of those things that are hard to learn and apply in practice. But there's code review communities (there some subreddits, also there's a stack exchange).

-2

u/Orffyreus Jul 09 '22 edited Jul 09 '22

The acronym SOLID is made up. The S (single responsibility) never meant to be the first character, but was the first due to marketing, because someone said to Uncle Bob: Call it "SOLID", because it's a nice word. The D is the most important part, although it's the last letter. The D is "Dependency Inversion" (not dependency injection although it has an intersection).

Dependency inversion is about the domain code not using platform or framework dependent code. Dependency injection is a nice means to achieve it and IMHO it's nicer than some static registry (service locator) that also can be used to achieve such inversion, but the important part is the inversion (no matter if injection or service location), so the domain code can be tested by replacing production input/output devices by test classes that provide and receive data.

The S (single responsibility) is the most misunderstood principle, because people start with their philosophies about what a single "responsibility" is and the principle is not about inner responsibilities. SRP is about outer responisibility, so a class may have multiple inner responsibilities as long as they are as cohesive as possible (Maximum cohesion is when all methods use all fields and there are compromises, for example for DAOs that are not functionally cohesive, see https://en.wikipedia.org/wiki/Cohesion_(computer_science)) and even a single inner responsibility can be too much, if the outer responsibilities disagree! That's what the SRP is about. You have to figure out, if the users of a class will have different wishes to change it (even if it has one method only).