How should I handle basic functions in OOP? - java

In an OOP program, where would I put functions for basic operations?
For example, if I had a class that, in one of the functions needed code that could invert an array, I could just make a method called invertArray() within the class.
On the other hand, I could create a whole new Functions class, where I could dump all these basic functions like inverting an array into. However, with this approach, I would have to instantiate this class in pretty much every other class I use. In addition, it isn't really an "object," but more of a conglomeration of functions that don't belong anywhere else, which kind of defeats the purpose of "object-oriented" programming.
Which implementation is better? Is there a better implementation I should use?
Thanks in advance.
Edit: Should this kind of post even belong in Stack Overflow? If not, could you please guide me to a more appropriate Stack Exchange website? Thanks.

Depending on your language it can depend where you put things.
However, given your an example, an invertArray lives on an Array class. In some languages you might make an ArrayHelper or ArrayExtension class. But the principle is "invert" is something you want to tell an array.
You will generally find all your functions will generally live somewhere on some class and there will be a logical place for them.
It's generally not a good idea to make a class that holds a mishmash of functions. You can end up with things like "Math" which is a bunch of "static" functions ( they don't work on an object ) they simply do some calculation with parameters and return a result. But they are still grouped by the idea they are common mathmatical functions

As per your question is regarding Java:
if I had a class that, in one of the functions needed code that could invert an array, I could just make a method called invertArray() within the class.
Then yes you can do this, but if you are willing to implement OOPS concept in Java the you can also do :
I could create a whole new Functions class, where I could dump all these basic functions like inverting an array into.
For this part :
I would have to instantiate this class in pretty much every other class I use.
You can also create an interface as Java provides you this functionality where in you can just declare you functions and provide its implementation in their respective classes. This is also helpful if in case you want different functionality with same function then you can choose this way and you don't have to rewrite your function definitions again and again.
And, OOPS concept comes handy when your are dealing with big projects with n number of classes. It depends whether you are learning or implementing on projects.

Related

UML/OOP: Using an interface for similar methods in different classes

Suppose I have two different classes that need to print different things:
OrderManager wants to print the order history, and MenuManager wants to print perhaps a menu. Since both want to do a similar function (but actual implementation is different), is it advisable to use an interface like this? The problem is that the function "print" is not very well-defined and self-explanatory as opposed to "printOrderHistory", and I can only implement the method with the exact name as defined in the interface.
Is there a workaround to this or am I using the interface concept wrongly? In fact, nothing seems to be stopping me from just defining their own print functions for each class without an interface...
This is the purpose of an interface! It defines a set of operations, and any class that implements this interface needs to implement these operations. This allows then to refer to a Printable object and call print(), knowing that it will perform as relevant for that object.
Your UML diagram, is therefore ambiguous: as OrderManager realizes (in java, "implements") Printable it should have its own print(). There are three solutions in UML and in Java:
Comply to the interface, as your diagram promises, and rename printOrderHistory() into print(). This makes sense if there is only one meaningfull way to print and order manager, and if there are no other constraints.
Add a print() operation (in java, "method") to OrderManager(), that just forwards the call to printOrderHistory(). But this looks like overcomplicated. It's justifiable only if the order manager would really e a printable, and if print() would add some relevant functionality such as selecting the right printing function depending on some factors.
Use the adapter pattern and leave the OrderManager clean, using an intermediate object for the dirty things. This makes especially sense if the name of OrderManager's printing function is constrained, or if there are different printing functions for different purposes. THis is the most flexible approach
Here a possible diagram for solution 3:
The idea with interfaces is to have a contract to fullfill. That means, that you have to you use method names and parameters defined in the interface when you build an implementation.
From my personal experience, it's always a bad idea to force an interface on classes, that are not similar, as in they do have a different purpose. While you could work with print() in both classes, it only makes sense if they are exchangeable in your code.

Starting a new project, how to structure it? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a very simple task in Java, and I am not sure which structure to give to my project.
I want to create a little project in Java, that makes some statistical calculations. For example, I will need to create a method that gets an array, and returns the mean, another method gets an array, and returns a standard deviation, I will also need a method that gets two arrays, and returns the correlation coefficient.
What I want to know, is how to do this now that I have opened a new project in Eclipse ?
Should it all be in one class ? Should I have a separate class for each method, making it a static method ? At the end, I want to give this code for someone else to integrate it in his project. I need to do it as simple and efficient as possible.
Can you please guide me on how to do it ? One class, several classes ? Public / private ? I am not familiar with these things, but I can program the methods themselves.
Thank you in advance
All your methods have the following attributes:
That they don't possibly have another implementation as long as your give them specific enough names. After all mathematical doesn't change. This means you don't possibly need structure like interfaces or subclasses.
That when people use them they have tendency to use several of them or group by functionality. That means you should group your methods by usage e.g. statistical methods; signal processing methods; and so on.
That the methods don't keep internal status and all the output is returned without any side effect of other callers/threads. Thus your methods don't have to have class contain themselves or any statue variables.
That your methods essentially provider utility to the main program but the semantics of the methods doesn't vary due to the caller or calling context.
So as all the above shows, your methods should be inside 1 or several classes as grouped by their nature or usage. The methods should be static methods without any side effect. That's exactly what java.lang.Math does.
I want to create a little project in Java, that makes some statistical calculations. For example, I will need to create a method that gets an array, and returns the mean, another method gets an array, and returns a standard deviation, I will also need a method that gets two arrays, and returns the correlation coefficient.
Looks to me that you are interested in creating a utility class for statistical calculation. The scope of how to achieve is this quite broad but it is advised to follow common coding conventions and basic OOP concnepts.
Should it all be in one class ? Should I have a separate class for each method, making it a static method ?
Since each of the methods ( mean, standard deviation ...) are related to the same core background (i.e to perform some statistical calculation), it seems logical to have a single utility class with a separate static methods for each of the function that you need to create.
Of-course you will have to take care of the basic OOP concepts like (data hiding) keeping the fields private and exposing them properly public getter/setters. Also, it would be a good idea to keep your calculation methods private and just exposing a public method which calls your private functions. Something like
public class MyUtilityClass{
// A bunch of private fields
int field1; ...
private MyUtilityClass(){} // We don't want anyone to create an object of this class
// method exposed to user
public static float calcArithmeticMean(float[] arr1, float[] arr2){
return getMean(arr1, arr2);
}
// method for internal use
private float getMean(float[] f1, float[] f2){
//do your calculation here
}
// remember to expose only those fields that you want the user be able to access
// getter/setters here
}
At the end, I want to give this code for someone else to integrate it in his project.
If you follow proper OOP coding conventions, then your utility class will be portable and anyone will be able to understand and extend it in their application.
I would create a single class representing the array of numbers itself.
public class DataSet extends HashSet<Double> {
public double mean () {
// implementation
}
public double standardDeviation () {
// implementation
}
public double correlationCoefficient (DataSet other) {
// implementation
}
}
My first suggestion is to start your project using Maven. It gives you a solid project structure with a great tool to manage your jar file dependencies and build lifecycle. In addition, all major Java IDEs, including Eclipse, easily create, understand and use your Maven settings.
Secondly, for your application design, it is recommended to avoid using lots of static methods because they hurt testability of your code as for example explained here.
Regarding the number of classes and methods, it depends on your specific use case but the guideline is to try to aggregate similar methods, based on their responsibilities, in one class while separating classes if there are too many responsibilities being handled by a single class. Low coupling and high cohesion are your friends in this case.
Arrays may be slightly faster than collections but be careful with them because they are reifiable and do not mix well with generics. Generally, rely on Collections. Also, if you can use Java version 8, have a look at Streams API.
Last but not least, Java has tons of open source code out there. So, always look for a library before starting to write one. In case of Math, have a look at this and that.
Create one class with a different methods with public access for each calculation type(one method for each of mean, standard deviation and so on). These methods can internally refer to helper methods in another utility class(es) not publicly accessible, as per your convenience.
Put all these classes in a single package and export it for integrating in other projects.
Since it will be used by others as a library by others , make sure you document and comment it as much as possible.
I vote for single class. The methods should be static and the parameters that you don't want to show should be private.
It depends on many thing such as other part of project, future changes and extensions,...
I suggest to start with single-class/public-static and change it in demand when you expand the project.

Better to extend a class or modify it directly?

So I'm working on creating a visualization for a data structure in Java. I already have the implementation of the data structure (Binary Search Tree) to start with, but I need to add some additional functionality to the included node class. As far as conventions and best practices are concerned, should I create a subclass of the node with this added functionality or should I just modify what I have and document it there?
My question is similar to what's asked here but that's a little over my head.
I know it probably doesn't matter much for what I'm doing, so I'm asking this more as a general thing.
Edit: I probably should have been more clear. My modifications don't actually change the original implementation other than to add a couple of extra fields (x and y coords plus a boolean to set whether that node is highlighted) and functions to access/modify those fields. Also the node class I'm working with is included in the BST implementation
From reading your answers it seems like there's arguments to be made for either case. I agree that creating a separate class or interface is probably the best thing to do in general. Creating another class seems like it could get tricky since you'd still need a way to extract the data out of the node. The BST implementation I'm using is generic and doesn't have any such functionality by itself in the Node class or the BST class to just return the data so at minimum I have to add that.
Thanks for the informative replies.
The question to answer is, is the 'base functionality' useful, even disirable, when you're not visualizing the data structure?
You might not even want to extend the class at all. Without more detail, it seems to me that you have a datastructure that works. You could create a NEW class that knows how to vizualise it.
That is, instead of a datastructure than knows how to visualize itself, you have a datastructure, and another class that knows how to visualize the datastructure. Heck - you may find that that evolves into another whole class hierarchy because you might need to visualize queues, stacks, etc. etc. NOTHING to do wiht your binary search tree.
Since you're asking in general, here's the short answer: it really depends on the situation.
First off, subclasses are assumed to have an "IS-A" relationship with their parent classes. If you can't say that your new subclass IS A specific kind of the original class, you're asking the wrong question, and should be making a new, unrelated class.
If the new code is closely related to the core purpose of the class, and applies to all members of the class (e.g. all BSTs), it may be better to modify. High cohesion is good.
If your new code is related to the core purpose of the class but has to do with only some objects of that type (e.g. only BSTs that are balanced), subclassing is probably the way to go.
Depending on what you're changing, how many places your code is used, how many different people/organizations are using it, &c., your changes might lead to unexpected behavior in other code, so you should think twice before modifying existing code. That doesn't mean automatically subclassing commonly used things; that would often be wrong for the reasons described above.
In your specific case, I agree with n8wrl; since visualization has nothing to do with data structures, it's probably better to implement a whole separate Visualizable interface than make a DrawableBSTNode subclass.
I would say that in the general case of adding functionality to an existing implementation, you should extend the existing implementation rather than modify it.
And here's my reasoning. If that node is used anywhere aside from the Binary Search Tree implementation, then when you modify it you'll need to find everywhere it is used to ensure that none of those places conflict with your modifications. While just adding functionality in the form of new methods generally won't cause problems, it could cause problems. You never know how an object is used.
Second, even if it is only used in the Binary Search Tree, you'll still need to make sure that the BST's implementation will play nice with your modifications.
Finally, if you do extend it, you don't have to worry about points one and two. And you get the added bonus of having your modifications kept separate from the original implementation for all time. This will make it easier to track what you have done and comment on it.
There's no simple answer, knowing when and how to add functionality is a something you have to learn over time.
Just adding to the base class seems like the easy solution, but it's polluting your base class. If this is a class you could reasonably expect another program (or even part of your program) to use does the functionality you are adding make sense in the context of your class's responsibility? If it doesn't this is probably a bad move. Are you adding dependencies linking your base class to your specific use? Because if you are that's throwing code reuse right out the window.
Inheriting is the solution a lot of engineers gravitate to, and it's a seductive route. But as I've grown as an engineer it's one that I use sparingly. Inheritance should only be used in true is-a relationships, and you need to respect behavioral subtyping
or you are going to regret it later on. And since Java only allows single inheritance it means you only get one shot at subtyping.
Composition (especially with interfaces) is often a better idea. Often what looks like a is-a relationship is really a has-a one. Or sometimes all you really need is a helper class, that has many functions that take your original class as an argument.
However with composition there is one issue, want to store these objects in your tree. The solution here is interfaces. You don't want a tree that stores Nodes. You want to objects that have an interface that can give you a node.
public interface HasNode {
public Node getNode();
}
Your node class is a HasNode with getNode just returning this. Your NodeVisualizer class is also a HasNode, and now you can store NodeVisualizers in your tree as well. Of course now you have another problem, your tree could contain NodeVisualizers and Nodes, and that wouldn't be good. Plus when you get a HasNode back from the tree functions you have to cast them to the right instance and that's ugly. You'll want to use templates for that, but that's another answer.
Mixing up logically independent functionalities will cause a mess. Subclassing is a very special relationship, often overused. Subclassing is for Is-a-Kind relationships.
If you want to visualize something, why not create a fully independent Class for that? You could simply pass your Node object to this. (Or even better, use an Interface.)

Where to put potentially re-useable helper functions?

This is language agnostic, but I'm working with Java currently.
I have a class Odp that does stuff. It has two private helper methods, one of which determines the max value in an int[][], and the other returns the occurrences of a character in a String.
These aren't directly related to the task at hand, and seem like they could be reused in future projects. Where is the best place to put this code?
Make it public -- bad, because Odp's functionality is not directly related, and these private methods are an implementation detail that don't need to be in the public interface.
Move them to a different class -- but what would this class be called? MiscFunctionsWithNoOtherHome? There's no unifying theme to them.
Leave it private and copy/paste into other classes if necessary -- BAD
What else could I do?
Here's one solution:
Move the method that determines te max value in a two-dimensional int array to a public class called IntUtils and put the class to a util package.
Put the method that returns the occurrences of a character in a String to a puclic class called StringUtils and put the class to a util package.
There's nothing particularly bad about writing static helper classes in Java. But make sure that you don't reinvent the wheel; the methods that you just described might already be in some OS library, like Jakarta Commons.
Wait until you need it!
Your classes wil be better for it, as you have no idea for now how your exact future needs will be.
When you are ready, in Eclipse "Extract Method".
EDIT: I have found that test driven development give code that is easier to reuse because you think of the API up front.
A lot of people create a Utility class with a lot of such methods declared as static. Some people don't like this approach but I think it strikes a balance between design, code reuse, and practicality.
If it were me, I'd either:
create one or more Helper classes that contained the methods as static publics, naming them as precisely as possible, or
if these methods are all going to be used by classes of basically the same type, I'd create an abstract base class that includes these as protected methods.
Most of the time I end up going with 1, although the helper methods I write are usually a little more specific than the ones you've mentioned, so it's easier to come up with a class name.
I not know what the other languages do but I have the voice of experience in Java on this: Just move to the end-brace of your class and write what you need ( or nested class if you prefer as that is accepted canonical convention in Java )
Move the file scope class ( default access class right there in the file ) to it's own compilation unit ( public class in it's own file ) when the compiler moans about it.
See other's comments about nested classes of same name if differing classes have the same functionality in nested class of same name. What will happen on larger code bases is the two will diverge over time and create maintainability issues that yield to Java's Name of class as type of class typing convention that forces you to resolve the issue somehow.
What else could I do?
Be careful not to yield to beginner impulses on this. Your 1-2 punch nails it, resist temptation.
In my experience, most large projects will have some files for "general" functions, which are usually all sorts of helper functions like this one which don't have any builtin language library.
In your case, I'd create a new folder (new package for Java) called "General", then create a file to group together functions (for Java, this will just be a class with lots of static members).
For example, in your case, I'd have something like: General/ArrayUtils.java, and in that I'd throw your function and any other function you need.
Don't worry that for now this is making a new class (and package) for only one function. Like you said in the question, this will be something you'll use for the next project, and the next. Over time, this "General" package will start to grow all sorts of really great helper classes, like MathUtils, StringUtils, etc. which you can easily copy to every project you work on.
You should avoid helper classes if you can, since it creates redundant dependencies. Instead, if the classes using the helper methods are of the same type (as kbrasee wrote), create an abstract superclass containing the methods.
If you do choose to make a separate class do consider making it package local, or at least the methods, since it may not make sense for smaller projects. If your helper methods are something you will use between projects, then a library-like approach is the nicest to code in, as mentioned by Edan Maor.
You could make a separate project called utils or something, where you add the classes needed, and attach them as a library to the project you are working on. Then you can easily make inter-project library updates/fixes by one modification. You could make a package for these tools, even though they may not be that unified (java.util anyone?).
Option 2 is probably your best bet in Java, despite being unsatisfying. Java is unsatisfying, so no surprise there.
Another option might be to use the C Preprocessor as a part of your build process. You could put some private static functions into file with no class, and then include that file somewhere inside a class you want to use it in. This may have an effect on the size of your class files if you go overboard with it, of course.

Would this be the correct place to use the java keyword "interface"?

I'm rather new to Java. After just reading some info on path finding, I read about using an empty class as an "interface", for an unknown object type.
I'm developing a game in Java based on hospital theme. So far, the user can build a reception desk and a GP's office. They are two different types of object, one is a Building and one is a ReceptionDesk. (In my class structure.)
My class structure is this:
GridObject-->Building
GridObject-->Item-->usableItem-->ReceptionDesk.
The problem comes when the usable item can be rotated and the building cannot. The mouse click event is on the grid, so calls the same method. The GP's office is a Building and the reception desk is a ReceptionDesk. Only the ReceptionDesk has the method rotate. When right clicking on the grid, if in building mode, I have to use this "if" statement:
if (currentBuilding.getClass.equals(ReceptionDesk.getClass)
I then have to create a new ReceptionDesk, use the rotate method, and the put that
reception desk back into the currentBuilding GridObject.
I'm not sure if I'm explaining myself very well with this question. Sorry. I am still quite new to Java. I will try to answer any questions and I can post more code snippits if need be. I didn't know that there might be a way around the issue of not knowing the class of the object, however I may also be going about it the wrong way.
I hadn't planned on looking into this until I saw how fast and helpful the replies on this site were! :)
Thanks in advance.
Rel
You don't want to check the class of an object before doing something with it in your case. You should be using polymorphism. You want to have the Interface define some methods. Each class implement those methods. Refer to the object by its interface, and have the individual implementations of those objects return their values to the caller.
If you describe a few more of the objects you think you need, people here will have opinions on how you should lay them out. But from what you've provided, you may want a "Building" interface that defines some general methods. You may also want a "UsableItem" interface or something more generic. Hospital could be a class that implements building. ReceptionDesk could implement UsableItem. Building could have a grid of UsableItem inside it.
If rotate() was a common method to all furniture that actually did some work, you may consider making an AbstractUsableItem class that was an abstract class implementing UsableItemand providing the rotate() method. If rotate was different in each implementing class, you would have that method in the interface, but each class, like ReceptionDesk would do its own thing with the rotate() method. Your code would do something like:
UsableItem desk = new ReceptionDesk();
desk.rotate()
In your example, if your mouse click on a screen rotated the object under it, and you really did need to check to see if the object could be rotated before doing something like that, you'd do
if (clickedObject instanceOf UsableItem) {
((UsableItem) clickedObject).rotate();
}
where UsableItem was the interface or abstract class. Some people feel that all design should be done via an interface contract and suggest an interface for every type of class, but I don't know if you have to go that far.
You might consider moving in a totally different direction and having the objects themselves decide what kind of action to take. For example, the GridObject interface might specify function declarations for handleRightClick(), handleLeftClick(), etc. What you'd be saying in that case is "any class who calls themselves a GridObject needs to specify what happens when they are right-clicked".
So, within the Building class, you might implement handleRightClick to do nothing (or to return an error). Within the ReceptionDesk class, you would implement handleRightClick to rotate the desk.
Your code snippet would then become:
currentBuilding.handleRightClick(... any necessary parameters ...);
You are correct to be worried. A good rule of thumb for Object-oriented design is that whenever you use a construct like if(x instanceof Y) or if(x.getClass().equals(Y.class)), you should start thinking about moving methods up or down, or extracting new methods.
Elliot and John have both presented good ideas on very different directions you could go, but they're both right in that you should definitely move in some direction. Object oriented design is there to help your code become more legible by making branching for different sorts of behaviors more implicit. Examining what sort of object you're looking at and determining what to do based on that can defeat the purpose of using object-oriented design.
I should also warn you that an interface isn't exactly an empty class. There are some significant differences between empty, abstract classes with abstract methods and interfaces. Instead of thinking of an interface as an empty class, think of an interface as a contract. By implementing an interface, your class promises to provide each of the methods listed in the interface.

Categories