This question already has an answer here:
-
What is the One Class, One Responsibility Principle?
5 answers
I know the power of the OOP when it comes to separating the code into related classes. But, when should I separate my code into classes?
I think more classes need more objects to call some methods from these classes. Is this overuse of memory?
Generally separate your code in more classes following the Single Responsibility Principle.
Each class should do only one thing.
If your class do too much, split it in different classes.
Try to search on internet about Single Responsibility Principle to have some nice example.
Generally problems are not linked to the memory but to the bad programming. The code should be easy to read even for people who don't know anything about it. Try to enhance performances only when you are a very advanced programmer and your code needs these enhancements.
There are 5 design principles. They can be remembered with the acronym SOLID that stay for:
- Single Responsability Principle
- Open Closed Principle
- Liskov substitution principle
- Interface segretation principle
- Dependency Inversion principle
Here I talked only about the single responsibility principle.
The design patterns are something closer to the code. A pattern is a solution to a recurrent problem. Instead a principle is an idea to follow to drive the design of the code. You will find dozens of patterns that can split your code to solve a specific problem. All of them follow the guideline to maintain a single responsibility for each class.
Just as point of start I add a link to a nice site explaining each principle and many patterns in detail. Link
Treat each each class as a real life entity.
For example if you are creating library management system, There will be class called Library which will contain a List variable which will basically hold list of object of "Book" class. You have to think in this way. Though its very simple but you have to think in this way only.
Memory depends on number of object you created. More object will need more memory
In java, you instantiate an object from a class just to clarify some basic terms. The Object in oop is a conceptual object, sort of saying you should organise your code into related entities, so that it is easier to maintain and adapt to future changed using principle mentioned by others in their answers like inheritance, encapsulation etc
You can always relate to real life concepts is it easier to find a document in a single thick file of lots of paper randomly put together or in files properly labelled accordingly to category etc.
Maybe to make objects in granul size we can use flyweight pattern .As to that pattern We can move common code to common object and helper method.That will help us save memory.
Thx