r/learnjava • • 16d ago

OOP DESIGN

I've been learning Java for about a month now. So far I've covered OOP principles, Java Collections, and I'm planning to dive deeper into exception handling next.

However, one area where I still struggle is OOP design and structuring. I understand concepts like inheritance, encapsulation, abstraction, and polymorphism, but when it comes to applying them in actual projects, I often find myself struggling to distribute them properly among classes.

No matter how many classes I create to separate different parts of the logic, I eventually end up with at least one class containing too many methods and responsibilities.

What are the best practices, concepts, or design principles I should study to improve my OOP design skills? How can I develop the ability to identify when a class is doing too much, decide when to create new classes, and structure a Java application in a clean, maintainable, and scalable way?

14 Upvotes

16 comments sorted by

•

u/AutoModerator 16d ago

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 - best also formatted as code block

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

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/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) 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.

10

u/CantRunNoMore 16d ago

There is an old statement - a class should do one thing and one thing well.

I loved OOP at Uni and then in industry found a lot of it to be BS.
The idea is correct, you move the language close to the problem domain. So you end up being taught over simplifications, a Car class, a Color, a Flower etc. In real life application may have Account, Statement etc but the trap is in inheriting from such classes.
If a class doesn't fully satisfy the is-a relationship then do not inherit from it. You can see when this isn't working well when you see code that uses instanceof to determine what type of object they are dealing with rather than using simple polymorphism.

Moving forward I would look at design patterns and see how the power is in polymorphism and not via inheritence

7

u/ITCoder 16d ago

As a newbie he should totally avoid design pattern right now. And the clarity he is looking for comes with exposure and experience. Maybe refer clean code, but i would not suggest that to a fresher yet.

1

u/SadCar1494 16d ago

https://github.com/sabinparajuli774-code/BankManagemntSystem

This is what I was talking about. The program does run and I am able to do what I wanted i.e. deposit the money, withdraw, transfer, and add the history, but it is all cluttered in a single class of Menu.

1

u/SadCar1494 16d ago

https://github.com/sabinparajuli774-code/BankManagemntSystem

This is what I was talking about. The program does run and I am able to do what I wanted i.e. deposit the money, withdraw, transfer, and add the history, but it is all cluttered in a single class of Menu.

3

u/ITCoder 16d ago edited 16d ago

For starter, don't use multiple classes in a single public class. Rather have separate public classes. Some classes are just the basic structure, with field and getter setter. These are known as POJO (Plain Old Java Object) or models, they should be in a single package maybe names models.

Your Menu class is doing most of the business operation. These are part of service layer. Better rename / refactor it banking service. Some of its methods can be clubbed together or refactored to a different service class, again inside a services package

The Bank class having main method, drives your application, better rename it to Driver or Main class. It will be outside of all packages.

Note that , if using a Java IDE you just don't rename a class, use refactor option to rename, so that the variable can be renamed at all the places it is used.

1

u/mandradon 16d ago

It also looks like some of the problem is from a lack of planning from the start. 

There's a class for validation of input, which doesn't need to be a separate class in this instance (well, we won't get into writing a class for handling validation and whatnot, especially for a beginner).

There's a few other things that are split out to their own classes that problem should be restored into one class. 

I agree also on splitting things out into discrete files.

I also recommend taking time to clearly plan out your design from the start.  Think through how things are going to work (as much as you can, it won't always work out that way) from the start.  Think through the relationships and it can help you identify where things should be. 

Otherwise what happens is you'll realize you need some functionality and you end up just putting it somewhere.  Then you end up with spaghetti. 

1

u/KillerCodeMonky 16d ago

These are known as POJO (Plain Old Java Object) or models, they should be in a single package maybe names models.

Disagree. Data types are as much part of any domain as the logic that acts on them. They should be in the same package as the rest of the domain.

1

u/ITCoder 16d ago

Yeah, i have seen them both in package domains and models. Tbh i never paid much attention to theoretical aspects of DDD. iirc, one of mapper plugins in maven call them as models. Been some time since i used that tho

4

u/KillerCodeMonky 16d ago edited 16d ago

You should study (and follow) the SOLID principles:

  • Single responsibility

  • Open-closed

  • Liskov substitution

  • Interface segregation

  • Dependency inversion

https://en.wikipedia.org/wiki/SOLID

IMO, the most important one that I see violated the most often is Liskov substitution.

Interface segregation and dependency inversion are mostly free in Java, as long as you code to discrete interfaces and inject the implementation of those interfaces via constructor or Spring or whatever. 

4

u/Direct-Ad3630 16d ago

Normal at first; the skill is noticing it and refactoring. Quick tips:

  • If you can't describe a class in one sentence without "and," split it.

  • Names like Manager/Helper/Util are often a warning sign.

  • Learn Single Responsibility first, then SOLID. Prefer composition over inheritance.

  • Make it work, then refactor. Unit tests force better design.

  • Read Head First Design Patterns, then Effective Java.

You're doing well for one month in.

2

u/0b0101011001001011 16d ago

I'm gonna go in completely opposite direction as others. They are not wrong, but I feel like there is an important thing people seem to miss when learning OOP.

What is a class? You make a class, when you need a new type. For example, Random is not a number. It's not a byte. It's not text. It's a new thing, that has a purpose.

Java has a pitfall in this regard, because everthing must be in a class. This forces you to make classes also when they are not strictly needed. In the ideal world, you would define the types that you need using classes or structs, and then write the main program outside of them.

The other people say things like class should do one thing. They are correct and I suggest reading their comments properly as well. Just saying that don't overcomplicate things: never use interfaces, unless you actually need to. Never inherit anything, unless you actually need to.

1

u/Safe_Fun3368 16d ago

if u are comfortable with hindi you can watch indian programmer videos and work on some project , more the projects more you understand thats it

1

u/Far-Bullfrog161 16d ago

Feeling like everything ends up in one big class is completely normal a month in, and the fix is mostly practice plus a couple of rules of thumb. The one that helps most is the Single Responsibility Principle: try to describe a class in one sentence without using "and". If you say "this class reads the input and validates it and saves it", that's probably three classes. Another quick smell test: if a class has lots of fields but each method only touches a few of them, it's likely several classes stuck together. When starting a project, write a short paragraph describing the problem, underline the nouns (candidate classes) and the verbs (candidate methods), then decide which object should own each piece of data. Prefer composition over inheritance for now, since deep inheritance trees are where beginners get tangled. Once that feels comfortable, look up the SOLID principles and refactor one of your old projects with them, because cleaning up your own messy code teaches more than reading about patterns.

1

u/Dedios1 15d ago

I like to think of code like an extension of data. If you’re familiar with databases and normalization, you know that a table should have one purpose. Example don’t mix messages and who sent them in the same table. They should be separate. Then you create relationships between them (equivalent for coding is inheritance polymorphism etc). 🤷🏽‍♂️

But again it won’t feel natural without writing more code. Just write code. You’ll start to gain the intuition for structuring/modularize your code. What matters is that it’s readable AND you know exactly where to go to fix a bug or at least diagnose. You can actually edit code forever. Big PR differences between year 2-3 and year 10 😂

1

u/yel50 13d ago

the main opposing paradigm is FP, which preaches the separation of code and data. however, that separation is impossible. you cannot write functions that work with whatever data you hand them. functions always make assumptions about their input. they cannot be separated from their data.

for example, if you have a function to add to a list,

fn add(list, item)

there is nothing stopping you from calling it with a hash table, integer, or whatever else instead of a list. that add function requires a list be the first argument. classes make it impossible to pass the wrong type as the first argument.

list.add(item)

now, the add method cannot be handed a hash table or something by accident. even in fully dynamic languages, like js or python, classes give a certain amount of type safety.

in short, classes are a data type combined with the functions that operate on that type. or, in FP terms, they're partial function application applied to a group of functions instead of only one.

abstract methods, which include interfaces, are how continuations are done in OOP.

in good OOP design, each class has one job, holds the state for one type of data, and only includes the methods that are needed to operate on that data.