Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does having lots of methods on a class increase the overhead of that class's object?

Tags:

java

c#

memory

Imagine I am using a class to bring back items from a database, say

class BankRecord {

public int id;
public int balance;

public void GetOverdraft() {
...
}
public void MakeBankrupt(){
...
}

}

Now, what would happen to the performance of using this if there were just 2 methods (as above) or 100 methods, maybe some of them very large.

Would instancing hundreds of these objects be worse if all the methods were on each object? This is for c#/java type languages, but it would be good to know for all languages.

Or is it good practice to have a seperate class, to perform all the actions on these objects, and leave the object as a pure data class?

like image 486
Chris Barry Avatar asked Aug 09 '10 15:08

Chris Barry


People also ask

How many methods are too many in a class?

b) A class should contain an average of less than 30 methods, resulting in up to 900 lines of code.

Can an object have several classes?

An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements. This means that if a variable is declared to be the type of an interface, then its value can reference any object that is instantiated from any class that implements the interface.

Does class has memory?

Defining a class in Java won't occupy any memory. It'll just be saved as a file on your hard drive. The memory allocation takes place only when you create objects because the objects is what implements the contents of the class.


1 Answers

The runtime does not duplicate the code when creating an instance of a object. Only the member fields are allocated space in memory when an instance is created. For this reason, you shouldn't be creating "data-only" classes unless you have some other design reason for doing so.

That being said, there are other best-practices reasons why you might not want a class with a multitude of methods (e.g. the God object anti-pattern).

like image 113
Joseph Sturtevant Avatar answered Sep 20 '22 12:09

Joseph Sturtevant