permaculture playing cards
The moose likes Beginning Java and the fly likes object-encapsulation vs performance / class-file-size Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "object-encapsulation vs performance / class-file-size" Watch "object-encapsulation vs performance / class-file-size" New topic

object-encapsulation vs performance / class-file-size

nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
I have a object and I am not sure to place a (long) method within this object to set some properties which only belongs to this object-instance.

What if I retrieve (for example, 100000) object-instances.

Would it be not better,
to place this (long) method out of that object-instance in a separate class
(for example, a business-class) and invoke it from that class?

In this case,
I only have one method which sets the properties of a instance instead of 100000 methods,
where each instance has this method in it.

However, when doing this, it disturbs my object-encapsulation.

What should I do?
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Place it inside the object. If you create 10000 objects the method will only be loaded into memory once.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15002

There is not a copy of the byte code of a method for each instance of a class. If this would be so, it would be extremely wasteful - the byte code is the same for each instance and will never change. So having long methods does not mean that your objects are going to take up more memory, there's no reason to put long methods somewhere in a utility class.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: object-encapsulation vs performance / class-file-size
jQuery in Action, 3rd edition