I have the ability to run code that lets me make calculations and/or get variable information from a program. However I do not have access to the base code, and wondering if there is a way to print out all the methods an Object has available (public)?
Example the Class Shape, with sub classes of Circle and Square.
If I was able to print out methods to Circle I would possibly see:
.getRadius()
.setRadius(newValue)
but Square would have
.getSide()
.setSide(newValue)
I have a myObject, where I know I can get
myObject[1].GetLength()
myObject[1].getDimUom()
myObject[1].getQuantity().getValue()
However I am unaware of what I can set only certain things like (by trial and error)
myObject[1].setClass(newValue)
So I would like to be able to find a way to print out the method names from an Object; again without any ability to see or modify base code (like adding reflection)
What you basically want is to brake the information hiding principle which is the most fundamental principle in OOP.
What You (most likely) really want is to define a common behavior that could be implemented by the subclasses in their specific way. Regarding your example this could be a method changeSizeTo(int newValue) defined in an interface that would be implemented by your classes and each class would do something specific.
[update]
I mean anything available to public is it really hiding? – Edward
The point is not about the actual access modifiers but the question: "Does this force the caller to know what subclass this object actually is?"
Solution
You can use reflection.
Class clazz = circle.getRadius().getClass();
Method[] methods = clazz.getMethods();
for ( Method method : methods ) {
System.out.println( method.getName() );
}
With that said, you should listen to the advice given by #Timothy Truckle. You most likely have a design problem if you need to use this, assuming you aren't writing a framework or a library
Related
I'm building an app that needs to use multiple types of similar sensors. Since the sensors could also have different behaviours, or combinations of behaviours, I decided to use the decorator pattern.
In short, I have a hierarchy that looks like this:
So any of the concrete ISensorDecorator classes can decorate (wrap) any of the concrete IMeasureSensor classes, but since a concrete ISensorDecorator also is a concrete IMeasureSensor, they can wrap each other. So for example
IMeasureSensor sensor = new FilteredSensorDecorator(
new CalibratedSensorDecorator(
new AccelerometerSensor()
)
);
is a valid statement that declares a filtered and calibrated accelerometer sensor.
Now let's say I have a method called setCalibration() in CalibratedSensorDecorator. Obviously I can't call
sensor.setCalibration();
because IMeasureSensor doesn't have a setCalibration() method. And trying to use
((CalibratedSensorDecorator)sensor).setCalibration()
won't work either, since sensor is a FilteredSensorDecorator.
How can I get to the CalibratedSensorDecorator in this particular case, and more generally to any specific decorator in any "chain" of decorators? I don't want to store them as separate variables, I want to do it dynamically.
Since its a design question, there won't be any right answer, you need to make choice which could be good or not that good.
You shouldn't add a method for particular class since it will violate the Liskov substitution principle
Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.
You can initialize the calibration in constructor CalibratedSensorDecorator and use it while executing your required function.
If that doesn't meet your requirement, then may be CalibratedSensorDecorator doesn't belong in your sensor hierarchy. Consider separating it and use Strategy pattern to decide which one to use.
Edit 1:
what I understand it doesn't say that you shouldn't add methods to subtypes?
Yes, you are right. It doesn't prohibit from adding methods but if the methods are changing the state of an Object, then it should be re-considered. All these patterns are just the guidelines which can be tweaked as per our needs.
To explain my rationale:
Imagine you have create the setCalibration() on CalibratedSensorDecorator. You have following way to expose CalibratedSensorDecorator to either internal developer or to external developer. You have created a Factory which just returns IMeasureSensor as follows:
public IMeasureSensor getCalibratedSensor(){
...
}
Now the user of your API simply gets this and is happy that his/her current code is working. But realizes that he/she missed to setCalibration() which was found after hours of debugging. Moreover he/she has to write the type checking and type casting code to make use of this feature, which might not be great for clean code.
You should try to keep your classes as immutable as possible so that the debugging and maintenance are at ease. There is no harm in recreating the object since the older will be garbage collected.
Again its just my suggestion, its your decision to carefully consider what's best for your use-case. You can still go ahead with your new approach to create the method if its mandatory and ensure proper documentation has been made to make user understand the usage.
While the answer by Sagar discusses some (valid) reasons for considering using another approach than the decorator pattern, I came up with a working solution for the actual problem of finding the correct decorator.
/**
* Walks the decorator hierarchy recursively from the outside in (excluding the final
* IMeasureSensor which is not a ISensorDecorator), and returns the decorator of the given class.
* If none can be found, null is returned.
*/
IMeasureSensor findDecorator(IMeasureSensor sensor, Class decoratorClass){
if( ISensorDecorator.class.isAssignableFrom(sensor.getClass()) ){
return (sensor.getClass() == decoratorClass)
? sensor
: findDecorator(((ISensorDecorator) sensor).getDecoratee(), decoratorClass);
}
else
return null;
}
The method ISensorDecorator.getDecoratee() simply returns the "decoratee", i.e. the IMeasureSensor that the decorator decorates.
public IMeasureSensor getDecoratee(){
return mMeasureSensor;
}
You can then use findDecorator() to find a (the outermost) decorator of a given type like this:
IMeasureSensor sensor;
...
CalibratedSensorDecorator s = (CalibratedSensorDecorator) findDecorator(sensor, CalibratedSensorDecorator.class);
When calling a method, I get that you have to use instanceName.method() or className.method(). However, in some cases the instanceName or className is omitted in the code and just method() is written.
Programming language is Java. Just covering this for the AP Computer Science test and I have relatively limited knowledge of coding outside of the parameters of the course so a easy to understand explanation would be greatly appreciated.
My book says something about client programs but I'm not exactly sure what it means (both in general and about client programs specifically).
I'll put my explanation as simply as possible - Usually you would use instanceName.method() when trying to effect the variables within a class. For example a "Cat" object, you could make a cat - Cat catOne = new Cat() and then use its methods catOne.setName("Kitty");. This will set this objects name to "Kitty", leaving all other cat objects with the ability to have their own unique name.
Using className.method() is done when using a static method within a class, eg public static int method(), and then using it in another class. This does not require you to instantiate an object for that class, and can use them willingly. For example, having a class called MathConstants and using something like MathConstants.getPi() ( Sorry for the crude example ).
When methods are called like methodName() , this means that the method is located within the class itself. Usually we use this , as in this.methodName(), but just using methodName() is okay.
Hope that is easy to understand
Let's say I have a labyrinth with AI characters, where the users define the characters. Each user provide the classes for their individual characters. All the characters/classes extend some class/type C which has method control().
I want to do call each user's control() method, but I don't know how many users there will be or what classes they will provide. How do I resolve this problem?
EDIT: I wanted to convey that I do not know how many subclasses there are, or what their names are. Therefore, I am not able to place those subclasses in the code statically.
EDIT 2: Is there a way of doing this WITHOUT using reflection? I am aware that reflection solves the problem, but I hoped there was a cleaner implementation.
EDIT 3: It completely necessary to have the users create the different classes, as the point of the program is to test competing AIs.
btw, I am writing this in Java.
First of all, you need to decide if the different characters' behavior is really going to be as differentiated as to need Java code to implement the particular behaviors. Perhaps the behavior can be expressed with a single class and only modified by setting different values for parameters such as speed, health, attack strength etc. In this case you would get rid of the inheritance problem altogether and use a single class while users would only provide different configurations.
Now, if you really need very custom behavior and load custom Java classes, I see two main solutions.
First is the standard one. It uses just a tiny bit of reflection. You define an interface, for example:
public interface C {
void control(); //Params skipped for brevity
}
Now, your users create classes which implement this interface. The only problem is how to create an instance of the player's class. Once you have it, you call its control() or other methods via the interface. First, users need to make this class loadable. Thiscan be done through the network or in other complex ways but the simplest is that they put their .class or .jar file in their classpath when they run your application. Now all you need is to create an instance of the class. Assuming you specify the requirement that the class have a zero-argument constructor (you can define a method in your interface to load some configuration and perform initialization later on), you would be doing something like:
C gameCharacter = (C)Class.forName("your.fully.qualified.ClassName").newInstance();
Apart from error handling, that's all the reflection you need. You can now call all methods of interface C on your gameCharacter object - without knowing who or how wrote it and what exactly the methods do.
The other solution would be to use Groovy or another similar language to compile and run code on the fly. In this case you don't need the custom JAR in the classpath and you can even get around the need to know the name of the class to be loaded. Your user can provide the Java code of control() method in the form of text, and you can have a stub class whose control() method only compiles and executes the Groovy code the user provided. This may be more convenient, but requires the custom character code to be provided to you as source code, not compiled JAR, which may be a problem for some users. Also, this solution is more convenient if the implementations are going to be short and self-contained while the separate JAR and loading via reflection is better if the loaded code is more complex, uses helper classes apart from the main class etc.
The whole thing about inheritance is that you don't need to know the exact type.
If you have a reference to an object that is of type C or a subclass of C, you can call your "control()" method on them and it will call the right method, i.e. the one implemented by the child class.
Not knowing how many users means you'll have to use a list or something and loop over it.
public class AIGame {
public static void main(String[] args) {
List<AICharacter> characters = new ArrayList<AICharacter>();
characters.add( new ReallySmartAICharacter() );
characters.add( new ReallyDumbAICharacter() );
for ( AICharacter c : characters ) {
c.control();
}
}
}
interface AICharacter {
public void control();
}
class ReallySmartAICharacter implements AICharacter {
#Override
public void control() {
// TODO do something clever here
}
}
class ReallyDumbAICharacter implements AICharacter {
#Override
public void control() {
// TODO do something stupid here
}
}
If all the characters extend some common class, for convenience let's call it Character, then you can use polymorphism to dynamically call each of the control() methods.
In other words, if each subclass of Character overrides control(), then all you need to do is call it normally and Java will figure out which control() method to call.
e.g.
Character[] characters = new Character[2];
characters[0] = new Man(); // Man is a subclass of Character
characters[1] = new Woman(); // same with Woman
character[0].control(); // <- this will call the control() method as defined in Man
The mechanism for this is called late (or dynamic) binding, which you can read more about here: http://en.wikipedia.org/wiki/Late_binding
If the subclasses are not known at compile-time (i.e. they are specified at run-time), then you will need to use reflection to load them.
To keep track of each user, use a dynamically sized List type like a LinkedList or ArrayList. This way you don't need to know how many users there are beforehand.
I've just read this article here: http://hamletdarcy.blogspot.com/2008/04/10-best-idea-inspections-youre-not.html, and the last bit in particular got me thinking about my code, specifically the advice:
What in the world is a public method doing on your object that has no dependency on any fields within the object? This is certainly a code smell. The problem is that the "auto-fix" for the inspection is to apply the static keyword. Nooooo. That's not what you want to do. A public method without any dependency on object state can't possibly be part of an object that has one clearly stated charter. It's just not cohesive and should be placed somewhere else. So: if the method is private, accept the auto-fix, but if the method is public then don't.
The code in question is essentially an object transformer. It takes an object of type A and converts it to a different type.
My hierarchy is like this:
Interface ObjectTransformer -> GenericObjectTransformer
and then below this, GenericObjectTransformer is extended by ObjectTransformerA and ObjectTransformerB
Now, some functionality is required by both ObjectTransformerA and ObjectTransformerB, but doesnt actually depend on any instance variables of GenericObjectTransformer, so its a protected static method in GenericObjectTransformer.
Is this a violation of the rule above? Obviously this is protected rather than public, but its still a method accessible from outside of the class that has nothing to do with the class itself?
Any thoughts?
I disagree with the excerpt you pulled.
A public method without any dependency on object state can't possibly be part of an object that has one clearly stated charter. It's just not cohesive and should be placed somewhere else. So: if the method is private, accept the auto-fix, but if the method is public then don't.
Just because a method is static and has no relation to state, doesn't mean it falls under the "low cohesion" category. Cohesion/Functionality isn't based on state.
When you are trying to determine Cohesiveness think about the role of the class as a whole, not just the instance variables. If the logic you are looking at is related to the generic concept (GenericObjectTransformer) then leave it there.
If it is a routine to calculate the orbit of the moon, or the depth of the ocean move it to a utility class (another smelly area of our field).
It feels slightly unclean, but is seem preferable to the alternatives I can think of.
I think that the original
A public method without any dependency
on object state can't possibly be part
of an object that has one clearly
stated charter.
You reference is too black and white, and your situation is even greyer.
By having your protected method you are nicely documenting that its intended for use by derived classes. If you don't put it in the base class, then presumbly it's got to go in some ObjectTransformUtility class. Is that win? More artefacts, more places to look.
One thought: if your ObjectTransormer class undergoes significant change then how likely are you to need to change these utility methods. After all if their business is to work agains the object's interface then in fact their cohesion is quite high.
When I was programming a Form Validator in PHP, when creating new methods, I needed to increase the number of arguments in old methods.
When I was learning Java, when I read that extends is to not touch previously tested, working code, I thought I shouldn't have increased the number of arguments in the old methods, but overridden the old methods with the new methods.
Imagine if you are to verify if a field is empty in one part of the form, in an other and in yet an other.
If the arguments are different, you'll overload isEmpty, but, if the arguments are equal, is it right to use isEmpty, isEmpty2, isEmpty3, three classes and one isEmpty per class or, if both are wrong, what should I have done?
So the question is:
If I need different behaviors for a method isEmpty which receives the same number arguments, what should I do?
Use different names? ( isEmpty, isEmpty2, isEmpty3 )
Have three classes with a single isEmpty method?
Other?
If that's the question then I think you should use:
When they belong to the same logical unit ( they are of the same sort of validation ) but don't use numbers as version, better is to name them after what they do: isEmptyUser, isEmptyAddress, isEmptyWhatever
When the validator object could be computed in one place and passed around during the program lifecycle. Let's say: Validator v = Validator.getInstance( ... ); and then use it as : validator.isEmpty() and let polymorphism to it's job.
Alternatively you could pack the arguments in one class and pass it to the isEmpty method, although you'll end up with pretty much the same problem of the name. Still it's easier to refactor from there and have the new class doing the validation for you.
isEmpty( new Arguments(a,b,c ) ); => arguments.isEmpty();
The Open/Closed Principle [usually attributed to Bertrand Meyer] says that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification". This might be the principle that you came across in your Java days. In real life this applies to completed code where the cost of modification, re-testing and re-certification outweighs the benefit of the simplicity gained by making a direct change.
If you are changing a method because it needs an additional argument, you might choose to use the following steps:
Copy the old method.
Remove the implementation from the copy.
Change the signature of the original method to add the new argument.
Update the implementation of the original method to use the new argument.
Implement the copy in terms of the new method with a default value for the argument.
If your implementation language doesn't support method overloading then the principle is the same but you need to find a new name for the new method signature.
The advantage of this approach is that you have added the new argument to the method, and your existing client code will continue to compile and run.
This works well if there is an obvious default for the new argument, and less well if there isn't.
Since java 5 you can use variable list of arguments as in void foo(Object ... params)
You will need to come up with creative names for your methods since you can't overload methods that have same type and number of arguments (or based on return type). I actually personally prefer this to overloading anyway. So you can have isEmpty and isEmptyWhenFoo and isEmptyWhenIHaveTheseArguments (well meybe not the last one :)
Not sure if this actually answers your question, but the best way to think about OO in "real life" is to think of the Nygaard Classification:
ObjectOrientedProgramming. A program execution is regarded as a physical model, simulating the behavior of either a real or imaginary part of the world.
So how would you build a physical device to do what you are trying to do in code? You'd probably have some kind of "Form" object, and the form object would have little tabs or bits connected to it to represent the different Form variables, and then you would build a Validator object that would take the Form object in a slot and then flash one light if the form was valid and another if it was invalid. Or your Validator could take a Form object in one slot and return a Form object out (possibly the same one), but modified in various ways (that only the Validator understood) to make it "valid". Or maybe a Validator is part of a Form, and so the Form has this Validator thingy sticking out of it...
My point is, try to imagine what such a machine would look like and how it would work. Then think of all of the parts of that machine, and make each one an object. That's how "object-oriented" things work in "real life", right?
With that said, what is meant by "extending" a class? Well, a class is a "template" for objects -- each object instance is made by building it from a class. A subclass is simply a class that "inherits" from a parent class. In Java at least, there are two kinds of inheritance: interface inheritance and implementation inheritance. In Java, you are allowed to inherit implementation (actual method code) from at most one class at a time, but you can inherit many interfaces -- which are basically just collections of attributes that someone can see from outside your class.
Additionally, a common way of thinking about OO programming is to think about "messages" instead of "method calls" (in fact, this is the original term invented by Alan Kay for Smalltalk, which was the first language to actually be called "object-oriented"). So when you send an isEmpty message to the object, how do you want it to respond? Do you want to be able to send different arguments with the isEmpty message and have it respond differently? Or do you want to send the isEmpty message to different objects and have them respond differently? Either are appropriate answers, depending on the design of your code.
Instead having one class providing multiple versions of isEmpty with differing names, try breaking down your model into a finer grained pieces the could be put together in more flexible ways.
Create an interface called Empty with
one method isEmpty(String value);
Create implemntations of this
interface like EmptyIgnoreWhiteSpace
and EmptyIgnoreZero
Create FormField
class that have validation methods
which delegate to implementations of
Empty.
Your Form object will have
instances of FormField which will
know how to validate themselves.
Now you have a lot of flexibility, you can combine your Empty implemenation classes to make new classes like EmptyIgnoreWhiteSpaceAndZero. You can use them in other places that have nothing to do with form field validation.
You don't have have have multple similarly named methods polluting your object model.