r/SpringBoot • • Jun 30 '24

Feedback on my Spring boot project (Have around 2 years of experience in Java Backend).

I have been working on a Spring boot application for quite a while, and I'm reaching out for some feedback from the community. I haven't had a chance to discuss it with anyone yet, and I'd love to get some fresh perspectives.

What I'm looking for

  • Architecture: How well-organized is the code? Are there any areas for improvement in terms of design patterns or best practices?

  • Missing features: Is there any core functionality that you think is missing from the application?

  • Existing issues: Have you spotted any bugs or potential problems in the code?

  • Interview talking points: What features or functionalities would best showcase my 2 years of experience during a Spring Boot interview?

Open to collaboration!

If anyone is interested in taking a look at the code and potentially collaborating, I'd be happy to chat.
Project Link

54 Upvotes

37 comments sorted by

15

u/mars3142 Jun 30 '24

Don’t use verbs in the URIs. Your method is the verb, so e.g. /bus/admin/** can be POST /bus/admin, PUT /bus/admin and DELETE /bus/admin/{id}, GET /bus/admin, GET /bus/admin/{id} and maybe GET /bus/admin/busType. This would be much more intuitive to use.

Also try to use Spring Boot Modulith as dependency. It helps to organize your code into modules.

1

u/deecoder_01 Jul 02 '24

Fixed API end points.

1

u/mars3142 Jul 03 '24

Don’t use @GetMapping(„/all“). It’s just @GetMapping().

For your GetMapping logout in UserController you should use PostMapping. It’s more secure to transfer the userKey as payload via TLS, which is encryption via transfer.

But yes, now it’s more a REST API.

0

u/deecoder_01 Jun 30 '24

Yes, that makes sense. Thank you.

0

u/[deleted] Jun 30 '24

[deleted]

3

u/mars3142 Jun 30 '24

I will do some examples. The best practice for load all „GET /v1/users“ or load one „GET /v1/users/{id}“. For DELETE you could do the same, but I never saw a delete all.

You mentioned a save all - never heard that. Maybe use the load all URI, but use POST and the payload will be an array instead of a simple object.

Regarding Login and Password stuff, you are right. This could be within the URI with POST (so the payload is in the body).

One important information. Within the result of load all, don’t let the root be an array. This will be a mistake in the long run - believe me, I did it. Always return an object and if the result is an array, use e.g. { „data“: [] }. This way you are able to include pagination or filters in the future without breaking older clients.

PS: Always use TLS (aka SSL or HTTPS). PPS: We can also write via DM.

27

u/WaferIndependent7601 Jun 30 '24

Don't put all Controllers in a Controller package. Put the packages into the packages.

Always use brackets in if statements!

Use RequiredArgsConstructor and make the fields final.

AdminService: admin cannot be null because it's validated. Make sure to put the validation in one place. Don't check in every method if the arguments are null

findByEmailAndPassword should return an Optional<Admin>.

addNewBusToDB: bad naming. You should not tell that the data goes into a DB.

BusService: Don't use more than one repository in one service method. If you need Data from other Repos, call the Service layer. The service layer can than throw the Exception and you don't have to care about it in the service layer (it's not the task of the BusService to care about login).

Line 53: route is always null. Do you want to save a null route? Why do you call the new route "route1"? Bad naming! You should also extract this thing to a method. Something like "if(route == null { return createNewRoute(...)} else { addRoute(...)}"

findAllBusByBusType: just return the empty list if no bus is found

Route: you don't need NotNull, NotEmpty and NotBlank at once. NotBlank has everything you need here.

In general: you really like BadRequests? You only return BadRequests even when the Bus is not found. A BadRequest is only thrown if the caller sends wrong data. If a bus is not found, that's a 404.

BusController: you probably want to return the created bus entity? Otherwise you could only return an empty response. And you should return a CREATED, not ACCEPTED. Same for delete and update, it's not accepted but no content or OK.

updateBusInfo: Valid annotation is useless here and already checked in the controller.

UserRepo: should be UserRepository and you don't need public in interface methods.

Delete-Requests should be idempotent. So deleting a ressource that does not exist will just return that the ressource is not there any more. Don't return an error here.

UserSignUpService has a delete method? Doesnt make sense.

routeservice has multiple not used methods.

3

u/deecoder_01 Jul 02 '24

I have done some modifications, Things have I addressed

  1. Brackets for if statements

  2. RequiredArgsConstructor instead of AllArgsConstructors

  3. Make sure that no service method in any case can return a `null ` value instead throws a suitable exception.

  4. Put Optional in repository methods.

  5. Fixed naming conventions.

  6. One repo in each service.

  7. Fixed Route service.

  8. Fixed response status.

  9. Removed valid annotation.

  10. Remove public from repository methods.

  11. Made sure returning correct response when deleting entities.

5

u/deecoder_01 Jun 30 '24

This is exactly what I was looking for, Thanks.

4

u/payb4k Jun 30 '24

Nice work,

For DTOs I'd recommend using records, they're more concise and immutable so they encourage cleaner and safer data oriented programming, just a suggestion im still learning about them

Avoid using @Data for entities and prefer @Getter and @Setter

Use @Transaction in your service layer you don't always have to call .save on repos if using transactions. When exceptions are thrown no save will occur, and changes will be rolled back

Use Lombok @RequiredArgsContructor to inject dependencies that are final.

For runtime exceptions such as entity not found extend RuntimeExcetion instead. Not sure of the justification for this but checked exceptions can be unforgiving

Use Spring ProblemDetail in controller advice for errors that are consistent and cleaner

I think you did super well and I stared your repo. I can definitely learn from it. Take these above as suggestions

1

u/deecoder_01 Jul 02 '24

Addressed most of it, Please review it once.

1

u/redpanda543210 Jul 04 '24

hello sir, why should we use getter setter over data?

6

u/wolle271 Jun 30 '24

Why are there no tests?

1

u/deecoder_01 Jun 30 '24

Working on it, I'm still developing more feature and optimising APIs.

3

u/[deleted] Jun 30 '24

you can use records for dtos

1

u/deecoder_01 Jul 02 '24

Not well versed with it, once comfortable with it, I'll make sure to add them for models

2

u/Mikey-3198 Jun 30 '24

For me I'd consider moving your applications logic out of the service classes & into appropriate model classes.

For example, your RouteService has lots going on internally. The graph traversal part could live in it's own model class, say RouteGraph, with methods to find the routes between each station/ stop.

Doing this will decouple this from the service, allowing it to be tested in isolation & make things easier to read. Your tests won't need any framework related code or DBs etc.... just a plain old simple unit test!

One talking point in an interview (assuming they'd look indepth at your code) may be about what you'd do to scale this up to a very very large number of routes. How scalable it is to load all the routes to construct the graph? can this be done better? could I use something like neo4j to maintain the route graph externally from my application? how would i deploy this? etc....

Another thing i noticed was your use of @transactional. Normally this is on the boundary of the service, wrapping the service call in a single transaction. Doing so you could call multiple repos as part of a service method, in which case it's important for them to be atomic. This will help prevent you being left in an unintended state in the event of an error. The spring docs have plenty of documentation RE @transactional defiantly worth a read.

1

u/deecoder_01 Jul 02 '24

Shall I create a `RouteService` interface and put all the utils in that as static method?

Also I'm not very comfortable with testing, Any good resource for it?

Also I've added Transaction on each service method as required

2

u/Mikey-3198 Jul 02 '24

Shall I create a RouteService interface and put all the utils in that as static method?

Not sure what this would achieve.

Also I'm not very comfortable with testing, Any good resource for it?

There are plenty of resources online for junit, have a search about and read through the documentation.

Also I've added Transaction on each service method as required

I could still see some transactionial annotations on your repos. This annotation can also be applied at the class level & overidden for each method that is read only = false.

3

u/trodiix Jun 30 '24

Not bad. I would add mapstruct and swagger There is no roles for admin

2

u/deecoder_01 Jun 30 '24

Still developing authorizations for admin and user.

5

u/IronMedal Jun 30 '24 edited Jun 30 '24

The unfortunate truth is that a lot of interviewers wouldn't read over the whole thing.. they would skim over the following:

Documentation

  1. Lack of convention.. /bus/bus/all/{busId} would ideally be /buses/{id} for example. Definitely read up on REST convention and best practices.

  2. Spring Boot 2.6.6 is listed as a prerequisite, but that's just a maven dependency, not something which needs to be installed beforehand

  3. Git is required but isn't listed (I realise this is somewhat pedantic)

  4. Maven 3.8.1 is listed as a requirement, but you've included mvnw files so it's technically not needed - you could adjust the docs to use mvnw instead

  5. There are things like {username} and {Database_name} in application.properties but the setup instructions don't mention setting these.. haven't tried, but I assume it won't actually run if I follow the instructions. Could use docker for the DB, and have default creds in application.properties

Tests

  1. No tests (big minus)

Code

  1. Overall looks like a decent use of Spring - others in this thread have given some good points

  2. Definitely should be using mappers rather than having big methods in the services converting from dtos to models

  3. Inconsistent naming (e.g. BusRepository but AdminRepo?). Pick one.

  4. Some oddities.. one of the first places I looked was in CustomUserDetailsManager, and userExists returns a boolean but that boolean is never used, and then it always throws an exception? No tests so I assume this is a bug

try {
            userExists(user.getUsername());
            throw new IllegalArgumentException("User with user name already exists in the system.");
}

5. There's unnecessary exception-driven flow on happy paths. Take userSignUp in UserSignUpService as an example.. if somebody attempts to sign up and the account doesn't already exist, there's an exception thrown and a bunch of logic in the catch block. Either use an exists repository method or a get repository method which returns an Optional, and create the account if the Optional is empty - no exception needed.

6. (Minor) A lot of devs dislike if statements with no brackets

It's a decent project, but there's a lot of little things to tidy up

4

u/Shadowmas73r Jun 30 '24

Just had a glance at the project. Is there a specific reason why you aren't using the latest LTS versions of Spring Boot and Java?

Aside from creating a working application, upgrading your components is also a valued skill. It shows that you aren't just interested in the application itself, but also in things like security, performance, support and sometimes new features.

1

u/B511_1 Jun 30 '24

Write tests gradually as the project expands. Not after you finnish everything. I guess you just keep manually testing your application every time you refractor/reformat something. This must take a lot of time.

1

u/deecoder_01 Jul 02 '24

Any good resource for where I can learn testing in detail

1

u/EducationalMixture82 Jun 30 '24

Remove everything custom in the security package,everything you have built already exists, its called formlogin and all you need to implement is the UserDetailsService interface and create it as a bean and spring security will do all the authentication for you but better. I have no idea why you decided to build some homemade security when spring security is a framework that contains all of that.

A security framework, usually already contains security. Thats why its called a framework.

1

u/deecoder_01 Jul 02 '24

I have plans for Custom security methods, once Implemented, I'll update here.

1

u/EducationalMixture82 Jul 02 '24

Whatever you do, do not build homemade custom security solutions. The built in security written by the spring team is most likely 10 times better and follows security standards.

And DO NOT build some home made solution that hands out JWTs to browsers. This is also not recommended, and JWTs should only be used in service to service calls.

1

u/ConnectMain5294 Jul 01 '24

Folder structure not good enough, repos shouldn't be public unless necessary.

1

u/deecoder_01 Jul 02 '24

Repo classes or methods?

1

u/ziyoray Jul 01 '24

Do you have front-end side connected with backend.

1

u/javinpaul Jun 30 '24

nice project