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.
Related
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.
I'm writing a library which has like 25 classes. 4-5 of them are meant to be a public api. The other classes are package private at the moment. My problem is that I want to arrange them to their own packages but this is not possible with the current setup because that way those classes won't be able to see each other.
So should I just leave them as-is without arrangement or make them all public so I can rearrange them? The latter I think is not a good solution because a lot of classes are not meant to be used by the end user but I don't like them just dumped into a root package as it will only grow in size.
Is there an idiomatic way in java to solve this problem?
Example:
I have a class named HexagonalGridBuilder. It is public and part of the api. Same stands for HexagonOrientation which is an enum and holds the value of (FLAT_TOP and POINTY_TOP) and HexagonalGridLayout which is an enum as well and holds the values for the types of hexagonal grids like RECTANGULAR and TRIANGULAR. The end user can use those enums to parametrize the HexagonalGridBuilder object which reuturns a HexagonalGrid which is an interface.
All of the implementation classes are package private like HexagonalGridImpl or TriangularGridLayoutStrategy. I can't move these classes into different packages without making them all public because of this packaging problem I described.
Aside for waiting for Java Project jigsaw there are several work arounds to your solution:
Keep the code as is with package-private classes, users won't see these so only you will be bothered by lots of classes in the package.
You can make packages with names like my.package.internal but have the classes public so they could be usable by others, but hopefully the name "internal" tells them not to.
Use something like OSGI which can enforce public vs private API and not let others ourside your jar directly access classes you don't want them to. However, this will only be enforced if your users are also using OSGI.
Any possibility to divide a class into multiple physical files using Java?
No, the whole of a class has to be in a single file in Java.
If you're thinking of C#'s "partial types" feature, there's no equivalent in Java. (If you weren't thinking of C#, ignore this :)
Yes You Can!
For the sake of completion:
Since Java 8, you have the concept of default methods.
you can split up your class into multiple files/subclasses by gently abusing interfaces
observe:
MyClassPartA.java
interface MyClassPartA{
public default int myMethodA(){return 1;}
}
MyClassPartB.java
interface MyClassPartB{
public default String myMethodB(){return "B";}
}
and combine them:
MyClass.java
public class MyClass implements MyClassPartA, MyClassPartB{}
and use them:
MyClass myClass = new MyClass();
System.out.println(myClass.myMethodA());
System.out.println(myClass.myMethodB());
You can even pass variables between classes/files with abstract getters and setters that you will need to realize/override in the main class, or a superclass of that however.
This might be a good idea if the class is really so large such that the implemented concepts are not easy to grasp. I see two different ways to do this:
Use inheritance: Move general concepts of the class to a base class and derive a specialized class from it.
Use aggregation: Move parts of your class to a separate class and establish a relationship to the second class using a reference.
As previously mentioned, there is no concept like partial classes in Java, so you really have to use these OOP mechanisms.
Using just javac, this is not possible. You could of course combine multiple files into a single .java file as part of your build process, and invoke javac afterwards, but that would be cumbersome on so many levels that it is unlikely to be useful.
Maybe you could explain your problem, then we can help better.
If you feel your .java files are too large, you should probably consider refactoring.
Of course it is possible, but I don't think it's useful at all.
To start off, divide isn't really the question I guess, you just compile the file and split it up whichever way you want.
Now to put them back together all you need to do is to write a custom class loader which loads all the pieces, combines them into a single byte array, then calls defineClass().
Like I said, it does look pretty pointless and is probably not what you want and definitely not what you need, but it is technically possible.
(I did something similar once as a joking way of obfuscating code: bytes of the class file were scattered in constants of all the other classes in the application. It was fun, I have to admit.)
No, in Java this can not be done.
No you can't. If your class is too big than you should split it into two or more.
Is it a bad practice to have a package with only one class in it? Would it make more sense just to move the single class to a util package that would contain other random useful classes?
Is it a bad practice to have a package with only one class in it?
Not necessarily. It could be a sign of somebody getting obsessed with classifying things. On the other hand, it could just be a logical consequence of a sensible general classification scheme applied in an unusual case.
An example of the latter might be where you have a general API, and multiple implementations of that API, where each of the implementations consists of multiple classes. But one of those implementations (lets call it the Null implementation) consists of just one class.
The real test is whether the package structure is serving its purpose(s):
Is it making it easier to find library classes?
Do the packages organize the application classes along the lines of the application's logical module structure?
Does the structure allow you to effectively make use of "package private" visibility?
Would it make more sense just to move the single class to a util package that would contain other random useful classes?
Not necessarily. If the class is just another "randomly useful" leaf class, then there is a good case for moving it. On the other hand, if it has a specific function and is not intended to be used generally, then it may be better to leave it where it is.
It is best not to get too obsessed with creating elegant package hierarchies, or with rejigging them when they turn out to be not as elegant (or useful) as you first thought. There are usually more important things to do, like implementing functionality, writing tests, writing documentation and so on.
No
Package is used to put similar classes together,
In your system if there is no similar class then obviously you can put it .
Is it a bad practice to have a package with only one class in it?
Not necessarily. Packages are using to group together logically related entities. It doesn't prevent you from having just one such entity in a package.
Would it make more sense just to move the single class to a util package that would contain other random useful classes?
Not to me, for two reasons:
Util has a specific meaning. Moving an arbitrary entity to util for reasons of loneliness would be a borderline case of util-abuse.
This is premature organization. With Java the IDE support is rich enough to reorganize easily and effectively using a few clicks. Wait a while to see how your project evolves and then take a call.
There are different stategies for static util classes. I use this one :
if your util class is generic (String utils, DB utils, etc.), I put it in a "util" package, that is used in all the application.
if the util class is specific to a domain, I call it "DomainHelper" by convention, and put it in the domain package, at the same level as domain classes.
Yes, it's a definite code smell.
This doesn't mean it's necessarily wrong, but there should be a really good reason for a lone class in a package.
Most instances of a package with a single class that I've seen have been erroneous.
Packages should implement features. It's rare that a feature is implemented using only a single class.
Its not 'bad' to have a single class in a package, Create a new package to group more than one related classes and in case if you expect more related classes to your present single logically unrelated class in future to avoid refactoring. Moving all the random utility type classes to a single package is a common practice seen in many places.Its a matter of choice really.
I guess it depends. It is quite rare in to have a package with one class in it because in addition to the answers listed above, packages also serve the purpose of creating a layered system. A package with only one class in it indicates that the decomposition of the system has not surfaced some objects in the system. So, yes, I would take a closer look at this package and question what the purpose is.
It is better not to stick random stuff in an Util package precisely because of the reason mentioned above. You should ask yourself whether you would think to look in Util for your class in the future before putting it there. When Util grows large it starts to get difficult finding the Utility one is looking for.
Is there anything out there (for Java specifically) that allow you to automatically test the behavior of an interface? As an example, let's say I have a bunch of tests for the Comparable interface, that should apply to anything that implements Comparable. What I'd like is to be able to include "ComparableTests" automatically in the test fixtures for any of my classes which implement Comparable. Bonus points if this would work with generic interfaces.
I know the .NET framework mbUnit has something similar, and when you're using something like TestNG's generator functions you could set up a test fixture for Comparable and have the generator create an instance of each of your classes that implement Comparable. But I'd rather have it be automatic, and located at the test fixture for each of my classes (since I'll already have them around for testing other parts of that class).
Clarification: I could definitely build something like this. I was asking if there was anything out there that already enabled this.
Based on your last paragraph, what you're trying to do is inject some 'extra methods' into unit testing since you're already testing a specific class. I do not know of a testing harness that allows you to attach tests based on the hierarchy of a class.
However, with your own suggestion of using TestNG for building something similar, I think you might be very close. You could very well incorporate some base code that adds your class to a list of 'default test classes', which are in turn tested if they implement a specific interface.
Still, regarding the general case, I think you're out of luck, since the Java type system is one-way, you can only (easily) find out what interfaces a class implements, not the other way around. Furthermore, the problem is 'where to stop looking': if you have a test that checks all your comparable implementers, do you want it to check the validity of String's one too, since that is in your Java environment?
Try this
http://www.xmlizer.biz/java/classloader/ClassList.java
In .NET it would be pretty simple to set up a method that looks through an assembly and identifies each class's inheritance/implementation hierarchy. I'm sure you could do it in Java, too, if you research the Java reflection API.
You could then create an array of ITargetInterfaces and call a test method on each one.
One way would be to search through the jar file for all the .class files (or search through the classes directory), use the Class.forName() method to load the class file and check MyInterface.class.isAssignableFrom(myClass).
This wouldn't deal easily public inner static classes (you could parse the class file name), but would never work with private inner classes or anonymous inner classes.