making interface when methods have different parameters - java

I was recently making a small program that involves wrapping around a JFreeChart library and made a number of convenience classes to easily make the charts and provide ready objects that exted JPanel and can readily be placed around and realised that all the classes have basically the same functionality and very similar parameters. It does make sense to me to make an interface and make each of the classes implement it, however there is a small hickup.
Each type of chart requires slightly different parameter set as for example piechart doesn't care about the time axis, bar chart has very distinctive time points, line chart pretends to be real time, etc.
I know that a parameter can be specified as a generic type in the interface and defined as concrete type in the implementation of the method, but I have never seen a variable number of parameters, so I created numer of overloaded methods and this got me thinking:
What is the "correct" way to do it?
like I did it (the lazy way) - define every method as overload in the interface and make unused methods throw an exception when called in a wrong class.
Make a container object and pass it (Seems like a waste of resources to pass object containing for example time series data for a pie chart)
Drop use of interface completely as it does not fit in that case perfectly and make separate classes that are just very similar.
Something else?
I would like justification of answer if you suggest one option or another.
My justification for going with 1. is that it makes the purpose very explicit, but it does seem like a violation of principles behind interface.

Related

Android Java App: Extending two classes (walk around)

I have two classes, ImageMap, extending ImageView and PageView extending GLSurfaceView, I am using the ImageMap to mainly have hot spots on drawables but I also need to add a page flip/curl animation to it, in order to do that I need those two classes to act as one object, any idea how to do that?
It is totally clear to me that multiple inheritance is not allowed in java.
There is no way of really extend two classes. What you can do is:
You make a wrapper object, that holds one instance of each object. and simply do this.ImageMap.filed1 and so. This is more convenient while developing the class. This also allows you to proxy method invocations.
You define interfaces which should be implemented, and you make a new class which implements both. This is only for class that use this class to have the interface, without really caring about the implementation.
You may need both things, since the first is about "how to do it" and the second about "how it will be presented to objects that use it".
Your question is not about Android; it's about Java.
Java does not allow for multiple inheritance.
Your reasoning is inaccurate regarding the following:
in order to do that I need those two classes to act as one object
That's not the case. An 'Activity', for example, does not have to be an event handler; it's enough if your 'Activity' can have an event handler, e.g. as an inner class which can access the Activity's variables.

Storing large variety of objects with different functionalities

I'm developing a game in Java which I can only describe as a variant of The Sims.
The main interface for the game consists of a level and will have a large variety of furniture which can be placed on the map. My problem is that whilst I can think of ways to construct a system which will allow me to assign properties to each item of furniture, I want to make sure I do it the correct way before I head down a long path to completing it. For example, if I referenced an object with an identifier of "sofa", the furniture object's members could be accessed through searching through all available objects and finding the one with the matching identifier.
My method would be to make a very large .java file with instances from a base furniture class for each item of furniture, with each one having an identifier and all its different properties assigned, such as image, position, rotation etc, plus their own unique code for each different function they provide (eg. sitting, sleeping).
For saving/storing these objects in a text file, I would just store the name of the identifier in the string array in the text file and when loading, I could just create the object by instantiating the object the identifier points to.
Would I be correct in using most of these methods, or are better ones available? If you've found it a struggle to comprehend what I've written (and I had trouble writing it clearly), then a more simple question would be:
How are items of furniture managed in The Sims with respect to the sheer amount available and the many different variations/rotations they can be placed in (and stored/saved)?
I think what you need to do here is try and abstract as much of the common functionality to the base classes and then each item should extend as necessary.
Eg
A Sofa... Seat extends Furniture extends Object
A Office chair would be the same
A DiningTable would be different tho... Table extends Furniture extends Object
You will also want various Interfaces so that a Sofa implements Sittable think of the functionailty that might be common to different objects, like they might all be Placeable
Also for saving and loading you might want to make your objects serializable.
Read up on Abstraction, Interfaces and Serialization
Component-Entity-System may be a good thing for you to look into. It's basically what you're describing. There's a large collection of entities, each entity has a collection of Components, and there are systems which know what to do with certain components.
EG: A piece of furniture is an entity named "chair". It has many components, one of them is "Renderable". And your game loop passes all renderables into the "renderer" System which calls the Renderable.render() method.
Note, this isn't very object oriented, but I find it's tough to design games like this in an OO way because the object hierarchies explode. Everything has some things in common with everything else. You'd end up with generic classes like "Unit" and "Thing" which isn't very OO either.

Java design pattern: same method on multiple classes

I'm creating an Android application. I need to override the draw method on a number of UI classes to create a custom appearance. These classes all subclass View. I'm wondering what the best way to do this is. I'd like to be able to reuse code as much as possible, so I'm looking for help in organizing things. As I see it right now, I have 2 options:
Option 1 - Subclass Everything
If I want to use LinearLayout, I create CustomLinearLayout. If I want to use ImageView, I create CustomImageView. On each of these custom classes, I override draw exactly the same way. This doesn't seem efficient because I'm repeating code and extending a number of classes which do almost nothing.
Option 2 - Subclass a Super Class
My original thought was to extend View and create CustomView, because it's already a superclass of all the classes I want to use. This, however, doesn't work because all the existing subclasses I want to use are still extending View, not CustomView.
Is there a better way to do this? Am I missing something?
One possible solution would be to extract your draw logic into a separate class DrawingCode. This could contain a static method or you could even use instances of DrawingCode to customize your drawing code with other parameters. Of course you'll still have to overwrite the draw() method, but only write one line of code to call DrawingCode.draw(param1, param2). This way you get to store your drawing code in one central place and don't repeat yourself.

How to make a design "loose coupling"?

I'm making a simple 3D CAD software. in the class diagram, many objects need to distinguish with others by (x,y,z). I create a class so-called "Position", but the problem is it looks highly-coupling because many classese work with position.
Any ideas?
It is not a problem per se if a type is used by many other types. In your case, graphical objects obviously (usually) have a position so the coupling looks natural and reasonable from the perspective of the domain model.
Also, the Position class is probably going to be a fairly low-level class whose interface (and probably implementation too) is not going to change very often in the long run. So there is not much chance of such changes breaking client code.
First let me say after 12 years that your design is not bad. Assuming that the positioning logic of your classes shall be called from outside, all your classes need to have and offer this logic. So it is part of the interface and you must bring the functionalities in. And this means, you must depend on it and there is a coupling. The coupling is not between your objects. So it is not as bad.
But there are always alternatives. It is known that inheritance establishes a very tight coupling. Consider for example that the positioning logic is only called internally in your class. Then you don't have any benefit in inheritance. You could as well have another class (let us call it Position). And instead of deriving from this class, you integrate an object of this class. And whenever you want to do something with the position, you call the corresponding methods of this object.
This alternative looks like a nonsense change. Why should you do this? But let us have a look at the consequences. Assume you have a class Circle. Circle has such a position object as proposed above. (By the way, see the wording "has a position" instead of "is a position". The "object-and-composition" solution seems to be quite natural.) Somewhere in a file X of your code you may have created such a Circle. And now you decide you change the positioning logic. In X you don't have to worry that this has a side effect, because the interface of Circle has not changed. It is just one object inside of Circle that has changed. That is just an implementation detail. In contrast if you would have used inheritance, you cannot just change the base class without looking if this has a negative effect to X. So this "object-and-composition" solution has actually reduced the coupling between X and the positioning logic.
You can even reduce the coupling further. With the object-and-composition solution, whenever you change the positioning logic, you have to check all your classes if this has an effect. But what about using an interface for Position. Your classes don't see an object of a type Position, but an object that fullfils an interface Position. And the actual positioning logic implements this interface. This way most of your classes' code has no dependency to the implementation of the positioning logic.
That is not the end of the game. There is still a coupling, because your classes must somehow create the position objects. So at least the constructor must go into detail and for example pass x,y,z. But what if you use something like a factory for this purpose, so that your objects just get the position without even knowing how these have been created. Then you are absolutely flexible. You can use your classes in completely different situations. For example in a two dimensional coordinate system. There is no coupling between your positioning logic and your classes any more.
I hope you see that all these options exist. I suppose in your example this is a bit over-engineered. But your question was how to reduce the coupling. And there are always ways. Combinations are of course possible. For example you can have the object-and-composition and make the position object public in your base class. But then I would ask if not inheritance would have been the better option?

Java Design Questions - Class, Function, Access Modifiers

I am newbie to Java. I have some design questions.
Say I have a crawler application, that does the following:
1. Crawls a url and gets its content
2. Parses the contents
3. Displays the contents
How do you decide between implementing a function or a class?
-- Should the parser be a function of the crawler class, or should it be a class in itself, so it can be used by other applications as well?
-- If it should be a class, should it be protected or public class?
How do you decide between implementing a public or protected class?
-- If I had to create a class to generate stats from the parsed contents for eg, should that class be protected (so only the crawler class can access it) or should it be public?
Thanks
Ron
I think Andy's answer is very good. I have a few additions:
If you believe that a class will be extended in the future, you can set all your private methods (if any) to protected. In this way, any future extending classes can also access these.
I like the rule that a method shouldn't be longer than that you can see its opening and closing brackets ({ }) without scrolling. If a method is longer than that, try to split it up into several methods (private, protected or public by your preference). This makes code more readable, and could also save on lines of code.
So let's say a method is getting big and you split it up into several private methods. If these new methods are only used within the first "mother"-method, it makes sense to move all of that into a class of its own. In this way you will make the original class smaller and more readable. In addition, you will make the functionality of the new class easier to understand, as it is not mixed up with that of the original class.
The best guidance I've seen for these types of questions is the "SOLID Principles of OO Design."
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
The most basic of these principles, and the one that sort of answers your first question is the "Single Responsibility Principle." This states that, "a class should have one, and only one, reason to change." In other words, your classes should each do exactly one thing. If you end up needing to change how that one thing works, you only have one class to change, and hopefully just one place to make the change within that class. In your case, you would probably want a class to retrieve the content from the URL, another class to parse it into some sort of in-memory data structure, another class to process the data (if needed), and yet another class (or classes) to display the content in whatever format you need. Obviously, you can get carried away with classes, but it's typically easier to test a lot of small, single-operation classes, as opposed to one or two large, all-encompassing classes.
The question on public vs. protected depends on how you plan to use this code. If your class could be used independently outside your library, you could think about making it public, but if it accomplishes some task which is specific or tied to your other classes, it could probably be protected. For example, a class to retrieve content from a URL is a good general-purpose class, so you could make it public, but a class that does some specific type of manipulation of data might not be useful outside your library, so it can be protected. Overall, it's not always black and white, but ultimately, it's usually not a huge deal either way.
I like to think of classes as "guys" who can do specific stuff "methods".
In your case, theres a guy who can fetch the content of an url if you tell him which url that is.
Then there is this another guy, that is really good at parsing content. I think he does that with a tool called rome, but i'm not sure. he keeps that private (hint ;) )
Then we have that third guy, who displays stuff. He's a bit retarded and only understands stuff that "another guy" produces, but hey thats fine.
Finally the project needs a boss guy, who gives orders to the other 3 guys and passes messages between them.
ps: I never really though about making classes protected or not. Usually they are simply public without any specific reason. As long as it don't hurt, why bother?

Categories