If in a function which is getting called recursively with smaller arguments and within this function we are creating an object of a class. The objects created recursively will have the same name, hence we cannot preserve the name uniqueness. How can we handle such cases in Java?
I think this question stems from a misunderstanding. In Java, the name you give to a local variable is 100% irrelevant at the time the code runs - the only purpose is for you, the programmer, to specify which variable you are talking about (by giving its name, and having the compiler figure out what you mean by looking in the local scope, the scope above it and so on).
So, if you have a recursive method that calls itself, and in this method declare variables that hold new objects, then there is no clash as far as Java is concerned and they will all correctly refer to distinct objects in distinct places in memory.
If you actually meant 'I want to record all the new objects I make in my recursive method, but have them be distinctly referable to', then start by making a collection (ArrayList for example) one of the parameters to your recursive method - then you can add all newly made objects to this collection and when it fully returns, it will be full of your newly made objects. But if that's not distinguishing enough, then you need to ask 'what would distinguish these objects?' which will depend upon what the object is for (should some parameter of the recursive method be part of the 'name"? some other state? or does it just need to be random and unique?).
Related
I'm thinking about the solution for my application. Here's the situation: I have a class with a method that takes ObjectA as an input parameter and calls several small methods. Each one of these methods needs some parts of the ObjectA (they don't overlap, i.e. method1() needs ObjectA.field1 and ObjectA.field2, method2() needs ObjectA.field3 and so on...)
Given the general good code practices and performance, is it better to pass ObjectA to each one of these methods so they can extract the value they need on their own or is it better just pass them values? I mean:
method1(ObjectA);
method2(ObjectA);
or
method1(Object1.getField1(), ObjectA.getField2());
method2(ObjectA.getField3());
Keep in mind, with your code, you're not actually passing ObjectA. Namely, you're passing the reference type to ObjectA, so on a performance note the difference between passing a String object reference and a ObjectA object reference would be negligible.
The way I would write it
I would pass the whole object, if the method is pertinent to the class. My reasoning for this is to split up class knowledge as much as possible. What I mean by this is the following.
public void doSomethingRelatedToTheClass(String param)
{
// Do something with param.
}
My first criticism here is that this method assumes that the input is the correct field. My second, is that now, the class calling this code needs to know a little bit more about this method, because it has to call it like this:
doSomethingRelatedToTheClass(myObject.getValue());
And what this means is, if you find that another member of ObjectA works better inside this method, or you want to access other members of ObjectA, and you change doSomething() to reflect this change, you also need to change the method call, to:
doSomethingRelatedToTheClass(myObject.getOtherValue(), myObject.getValue());
So by passing in the whole object, you abstract that detail away, and the method can handle it; namely:
doSomethingRelatedToTheClass(myObject); // Doesn't need to know what you do with it.
public void doSomethingRelatedToTheClass(ObjectA object)
{
String val = object.getValue();
String otherVal = object.getOtherValue();
}
When a change to one class, results in a change in other classes, this is an Anti-pattern called Shotgun Surgery.
Edit
I've had chance to review my answer here and I've amended my original answer slightly because I believe it isn't the best solution for all situations. As above, if a method is related to a class specifically, then the instantiation of that class (or more preferably, its superclass or implemented interface[s]) should be the parameter.
The time this is not the case is when the functionality can be generic. An example of a generic function might be:
public String[] findNouns(String sentence);
In this case, finding the nouns in a sentence might be appropriate for lots of use cases, and not just the use cases that you have defined. As such, passing in the value is the only sensible approach because otherwise, you couple two pieces of logic together that have no direct relationship. The finding of nouns and the arbitrary object you have defined.
In Summary
If the method is logic that is related to the object, pass in the object
If the method has nothing to do with the object, and the object is just using it as a utility function, then pass in the value and name the function generically.
Let's examine a scenario. Now this may or may not be your scenario but it illustrates a point.
Lets say field1 and field2 in your case are two integers and method1 sums them and returns the result.
If you pass in the objects then that method can only ever sum those two fields. The method is also now strongly coupled with those objects.
On the other hand, if you pass in only the fields, the two integers in this case your method becomes more generic. You can now sum any 2 arbitrary integers regardless of which objects they are on.
In general though, always expose as little of your objects to other methods and classes. This promotes loose coupling.
Exceptions
AS maaartinus points out if for example field1 and field2 were Points and method1 calculated the distance between those two points, then I would have to agree that passing two Points would be better than passing 2 xy integer pairs (4 parameters)
Hope this helps
I'd say, it depends. A method may be clearer and more general if it operates on the arguments rather than requiring a whole object. Sometimes you have the arguments ready (e.g., x and y) and would have to aggregate them first into e.g. a Point in order to be able to call the method. Sometimes you have a different unrelated object (e.g., some ImmutablePoint, obviously not extending java.awt.Point) and would have to extract the coordinates and create an object to pass.
Usually, if the passed object is the proper abstraction, then passing it as a whole is the way to go. It's not a performance question, it's about readability and maintainability. See also the Law of Demeter which may lead to looser dependency on the passed object.
As others have said, it depends but in my experience passing entire objects makes code harder to read and maintain.
Lets consider this method getUserDetails(User user) which relies on few methods like getUserAddress(User user) getUserFamilyInfo(User user) etc which may further connect to different data sources to fetch the information.
There is no easy way to know that getUserFamilyInfo needs only userId or it needs userId and lastName or something else from user when entire object is passed. It makes it hard to understand dependencies among different services and do any refactoring.
I prefer to pass individual arguments if count is less than 3 or create a dto if handful of properties are required from a vary large object.
I have read a class is a model for creating objects and does not exist physically whereas Objects are real. But we are creating variables inside a class and are even manipulating them.
How is that possible when class does not exist physically?
When is the memory created for these variables?
Where is the memory created for these variables?
If you mean static class variables, they are quaranteed to be initualized and any static initialization code inside class is quaranteed to be run, before the class is used. Exactly when, that is not specified IIRC, and different JVMs may do it at different time. They are basically same thing as global variables in languages which have those.
So to reiterate: static stuff exists and is initialized before it is first used. JVM implementation takes care of that.
But there is an object: instance of the class object, which is subclass of class Class.
Addition: In fact, in Java classes exist so concretely, that they can be serialized, transferred over network to different JVM, deserialized there, objects of the class created there and code executed. Simple example of this are vanilla Java applets running in browser. Another example is slave nodes in Jenkins/Hudson CI system, where the slave program is very small and only contains code to receive, deserialize and instantiate both classes and objects of these classes, sent by the master server they're connected to.
Try thinking of it this way. This is NOT an accurate explanation of exactly how any Java runtime does this, but a way of thinking of the class/object duality that may help you.
When you write a class X, you describe both code and data. The runtime will need only one copy of some things -- the code and static variables, for instance -- and one copy per object of other things, like the instance variables. You describe both these things in the class file you write, even though they will be stored separately.
Think of the one-copy-per-class things as all being stored in a block of memory together -- it would be called a struct in C. In Java, the first time the class X is referenced in your program, the runtime allocates this block of memory and associates it with the class X.
When the program executes a statement such as "X x1 = new X()", the runtime allocates another block of memory (or struct) containing all the instance variables, and keeps a separate pointer to that associated with the x1 variable.
Now, when the program executes something like "Arc arc = x1.getArc();", the runtime uses the first pointer to reference the code in the method getArc(), and the second pointer to reference the instance variables associated with x1, and executes the indicated code using those instance variables.
OO programming provides this way of associating data with code that manipulates it, allowing us to organize the program as 'objects' of combined code and data. The runtime does the business of keeping track of the different copies of things for us.
And I think it's inaccurate to say the class will not exist, it just won't exist in the form in which you wrote it.
Classes do exist Physically in the JVM at runtime. The explaination that you read was trying to labour point A while leaving the rest of the detail for later. School and books do this all of the time.
Within the Oracle JVM classes have physical representation from the moment that they are loaded. Infact every object has a pointer to that class and many objects can point at the same class.
I wouldn't think of a class or objects as physical things, that seems confusing to me. A class is often described as a blueprint for an object. Objects must be instantiated (created) using the new keyword, when an object is instantiated the class of the object is used as a blueprint to create the basic default object. The object may then be manipulated, even at runtime, by referencing the location in memory where it is stored and using methods inside the object's class to manipulate the fields inside the object's class, at least this is the way it usually should be done, its what's known as encapsulation and is incredibly important in OOP so if you're not familiar with encapsulation I would recommend looking into it.
I mentioned an object can be manipulated at runtime, that is a major difference between an object and a class. Classes can as well using something called reflection but that's another topic for another day. A variable or field is sometimes described as an address, it is a reference to the location in memory where the object is stored. Objects are not accessed directly, they are referenced through variables.
JLabel label;
The code above is setting aside a location in memory to store a JLabel object when it is instantiated with the new keyword. So far there has not been an object created, we have declared a variable which is a reference to the location in memory where our object WILL be stored when it is created. We are not going to access our JLabel object directly, we are going to use the 'label' variable we've created to reference the actual object in memory. So if we create two JLabel objects and instantiate them, like this...
JLabel label;
label = new JLabel();
JLabel anotherLabel = new JLabel("this is another label");
we now have two JLabel objects. The first object first declares a variable to reference the object then instantiates it on a separate line. The second object declares the reference to it and instantiates it all in one line. You can create objects either way and there are different reasons for using both of these methods. When an object is created at least one of its constructor is called the first object calls the constructor inside of the JLabel class that takes no parameters; The second object uses the constructor inside the JLabel class that takes a String and creates the object displaying the text passed in to the constructor.
Now imagine the program is running and we want to change the first object so it will display some text because it currently is blank since we used the constructor that doesn't take any parameters. We can manipulate the object using the setText(String) method like this.
label.setText("now the first label displays text");
We have not altered the JLabel class in any way by using that method, however we have changed the object so now it displays text. I'm probably going to lose a bunch of reputation points, or whatever they are, for this answer because I probably didn't explain every detail exactly correct but I answered this question because you're asking something that was pretty difficult for me to understand for a long time, probably more so than most because I've never taken a programming class. There's so much to this I cant possibly explain this entirely without writing a book so I didn't go into things like scope, access modifiers, static, etc., but I tried to cover what I think is important to understand what you're asking. Like I said, I have no formal education so take my answer for what its worth but hopefully I was able to make it a little easier to understand.
Oh I forgot about your other question. A location in memory to store an object is declared when a variable for the object is created. At that point there is a location but the size in memory is still 0 or null because there is no object. The memory necessary to actually store the object will be filled when the object is instantiated.
So I want to find out what parameters were used to create a object. How would I do that?
For example:
Example temp=new Example(1,2,3);
How do I find out what values 1,2, and 3 are, without manually saving them.
A well defined object usually hides its members behind a set of methods. If you need to discover how an object was initialized, you should add methods to its class that allow those details to be determined. And yes, this would involve at least saving these details as part of the object's initializer.
You can't. (Indeed, if you could, that would cause a number of bad things to happen. Not all constructor arguments are meant to be saved.)
Save them manually as fields in the class, like you normally would.
Just a bit of idle curiosity here.
Basically, if I have an object that only has a few primitive data members, it takes up a small amount of memory and doesn't take very long at all to create. However, what happens if I have a lot of methods associated with that object? Does object instantiation have to take those into account at all?
For example, let's say I have a Class with (insert absurdly large number here) number of distinct methods I can call. Does the JVM take any longer to make an instance of that class than if I had no methods?
No, Class with methods is stored once in a separate memory location (namely PermGen) and each object of a given class has only a single reference to its type (Class).
Thus it doesn't matter how many methods your object has: two or two thousand - the object creation will take exactly the same amount of time.
BTW the same holds true for method invocation - there is no performance hit when calling methods of an object having plenty of them compared to object having only few.
See also
What's the method representation in memory?
I can't speak for java, but in C++ etc. non-virtual methods can be stored as global functions (wth approriate name mangling) and don't need extra space at instantiation time. Virtual methods will have to be filled into the VMT, which can probably be built at compile time and a single pointer stored in the object at instantiation.
So no, I don't see any hit for large numbers of methods.
No, I don't believe there's a performance hit that'll be measurable or matter to you. I'd say no and defy you or anyone else to come back with meaningful data to the contrary.
If your object is that big, I'd say it's time to refactor.
How can i get hold of the instantiating object from a constructor in java?
I want to store reference to the parent object for some GUI classes to simulate event bubbling - calling parents handlers - but i dont wanna change all the existing code.
Short answer: there isn't a way to do this in Java. (You can find out what class called you, but the long answer below applies there for the most part as well.)
Long answer: Code that magically behaves differently depending on where it's being invoked from is almost always a bad idea. It's confusing to whoever has to maintain your code, and it seriously hurts your ability to refactor. For example, suppose you realize that two of the places instantiating your object have basicaly the same logic, so you decide to factor out the common bits. Surprise! Now the code behaves differently because it's being instantiated from somewhere else. Just add the parameter and fix the callers. It'll save you time in the long run.
If you want to know the invoking class, then pass "this" as a parameter to the constructor.
Thing thing = new Thing(this);
Edit: A modern IDE allowing refactoring will make this very easy to do.
Intercepting method calls (including constructors) without changing a ton of existing code is one thing Aspect-oriented programming was made for.
Check out AspectJ for a start.
With AspectJ, you can define a "pointcut" that specifies that you want to intercept constructor calls for a certain object or set of objects (using wildcards if need be), and within the interception code ("advice"), you will be given method context, which includes information about the both the calling method and object.
You can even use AspectJ to add fields to your object's to store the parent reference without modifying their existing code (this is called "introduction").