Public Java class named differently than file - java

At one of the university classes we have to develop programs in Java. One of the requirements is to name all our files with pattern surname_firstname_exerciseN_className.java. Another requirement is that we must split our programs into multiple files. As you can imagine, these two don't play well together.
I'm trying to work around this by "translating" my class names. For example, if I write a class named "Something", I do this in my long_prefix_something.java file:
public class long_prefix_something extends Something {}
class Something {
// class code
}
And I want to use class Something in another file. So I do this in that other file:
class Something2 extends long_prefix_something { }
What bothers me, is that I can't translate long_prefix_something back to Something because of circular inheritance error, I have to use Something2 instead.
Is there anyway to overcome this? Any annotation to use or something similar?

Necessity of such hacks is usually sign of bad design. Circular (and multiple) inheritance is not allowed in java.

I agree (with other commenters) that this sounds a little scary to me... But there, nevertheless, exist a few java conventions for dealing with problems similar to yours.
It appears that you need classes which are "more descriptive" of their internal
derivation then standard java classes in an inheritance hierarchy.
Your need can be satisfied in 2 standard ways : Interfaces (compile-time) or Reflection (runtime).
Although an exact solution is not clear because you seem to have a very complex code scenario here,
the two examples can address the problem your having :
First method: By using interfaces.
1) Convert "Something" into an interface
2) Take the implmentation methods from and port them to a class SomethingImpl
3) Just have "abcde12345_something" Implement the "Something" interface.
2nd method: By using introspecting the classes.
This is a somewhat strange approach, but if interfaces won't work, you can add more hooks to your class that allow it to describe, to other objects,
what type it is derived from.
1) It is clear that you are "wrapping" classes - so , you can add an API to your wrapped classes, such that each one provides a "getRootClass()" method, like this :
public class abcde_12345_something extends Something implements RootClassProvider{
public Class getRootClass()
{
return Something.class;
}
}
2) Now, at runTime - if you can't (for some reason) when you need to do special logical operations on "Something" objects, you can
call
if(myabcd_12345.getRootClass().isAssignableFrom(Something))
Something s = (Something) myabcd_12345;

I think the best way to do what they are intending to do is to use packages, instead of cluttering the class names... I'd suggest that to your teacher if I were you:
i.e. surname_firstname.exerciseN.ClassName instead of surname_firstname_exerciseN_className.java

No, this isn't possible in Java.
Extending won't work and aliasing such as it seems you want doesn't exist in Java.

Related

Is there any convention to store methods not particularly related to any class? [java]

I am currently learning Java and, while making a project, I created some methods that do not suit logically in any given class but are useful in the whole context of the project.
The best example I have is a method that splits camelCase worlds like this:
splitCamelCase -> Split Camel Case.
I have thought about creating a new abstract class called Toolbox and storing those methods there, but I wonder if there is any convention or best practice regarding this topic.
It's not uncommon to have utility classes (commonly named SomethingUtils) when it just doesn't make sense to put a method in an existing class.
There's nothing inherently wrong with it, but if you find yourself having a lot of methods or utility classes, then your design might be a bit off and you're programming in a more procedural than object oriented way.
As mentioned in comments, you don't make it an abstract class. It's a class filled with static methods working entirely on the parameters passed to them.
As kayaman sir has said if you are having too many utility classes and method it means that you code is more procedural rather than object oriented.
Nut if you still want to have a class which is just used to provide some utility then you can have such a class in java , just put some static method in them.
One of the best example of such a class is java.lang.Math.
for example following code will work
class MyUtilityClass
{
private MyUtilityClass()
{
// no object creation will be allowed
}
// make as many static methods you want
}
You can create your ToolBox Class and then you declare it as a package. After that you can import your ToolBox at the beginning of classes you want to use the methods from that ToolBox.

Creating a Java container class

I have been given an java assignment in school that requires me to create a StockQuote class. This would normally be easy, however the teacher has referred to it as a simple container class. I'm confused because everything that I read says container classes are things like java.util.Vector, java.util.Hashtable, and java.util.HashSet. I get the feeling he is using this term to mean something else, perhaps even just to mean a strightforward StockQuote class. I tried emailing him but he hasn't responded and I'd like to get a jump on the assignment. Here is the description from the assignment:
"A StockQuote class or interface. This a simple container class. Typically you would not use an interface for container classes, but you could. One rule for when to use an interface or not is to decided if there ever possibly could be more than one implementation of the class. If more than one implementation is possible, then using an interface definitely makes sense. In the case of simple container classes like this one, there probably will only be one implementation"
Any help or nudge in the right direction would be great. Thanks
In your case This a simple container class. == This a simple class..
In general your class may have some fields of other types, like String, Collections, etc. If so, you would say I have a container class because it contains/stores some data.
Interfaces don't have fields, so they are not containers.

Is it a good idea to merge all helper classes into one gigantic class?

As I develop my software, I tend to find myself creating a whole ton of ThingyHelper.java, FooHelper.java, BarHelper.java etc. I counted, and in the current project that I am working on, there are something like over 40 classes that look something like this:
public final class FoobarHelper {
// Prevent instantiation
private FoobarHelper() {throw new AssertionError();}
public static void doSomething() {}
public static int foobar() {}
// And many more
}
My question is this: Is it a good idea to merge all these classes into a huge Helper.java class? Looking around, there seems to be nothing written on this topic. My view is:
I should do it, because:
I don't have to remember which helper class is it in. (Was it FooHelper, or BarHelper?)
Just convenience. I don't have to decide if the new helper method deserves its own helper class, or if it fits into one of the existing 40 helper classes.
If I make a new helper method, and decided it deserves its own helper class, I will probably spend the rest of my day "hey, won't foobar() be better off in this new class?"
If #3 is true, other programmers would be like "where on earth did foobar() go? Its not in FoobarHelper!"
Is there a convention for helper classes, or if not, would it be a terrible idea?
I argue that your problem is not the fact that you have too many of those classes, it is that you need these classes altogether.
It is the core idea of object-orientation to merge functionality and data into objects which then represent your program flow. Without knowing your application, your utility classes suggest that you use inanimate bean classes which are then handled by a layer of service functions. This is a sign of procedural programming and nothing you want to implement with Java.
Besides that, there is no reason to merge your utility methods. So I would answer no to your question. There are some legitimate uses of utility classes such as Java's Math, Collections classes (those would also suite better as object methods but the language limits / limited this sort of definition) and you might just have encountered one of them. Note how Java decided to group such utility methods by their semantics. It makes sense to define utility methods in one name space such that your IDE can help you to pick a function when you only type the class (which does not represent a true class but rather a function namespace in this context). In the end, it is about finding a balance. If you have a single utility method per class, it is difficult for others to locate these methods as they need to know about the class's name. If there is only one utility class, it might be problematic to locate a function of all those offered. Think about the utility class as a form of navigation helper (name space) and decide after what you find intuitive.

Naming convention for interface / class / mockClass in Java?

I'm creating a mock class for a Lexer object, and I think I may need to do some refactoring. I have two options:
Create an interface Lexer, and rename the current Lexer to something like RealLexer. Have MockLexer implement Lexer, and method calls take anything of type Lexer. I dislike that my precious Lexer class is now renamed to something that has no meaning if you don't know that there's a mock class.
Create an interface LexerInterface (which I already dislike, since it has Interface in its name), but allowing myself to keep the current Lexer the way it is. MockLexer then implements LexerInterface. Another downside is that method calls take LexerInterface as params.
Both options smell bad to me, so I figured I'd let standards decide for me. Has anyone had experience with this?
I'd definitely vote for using Lexer as your interface name. How about adding some information about how or why your implementation does its thing as part of the name?
E.g.:
StringParsingLexer
TokenizingLexer
SingleThreadedLexer
{ThirdPartyLibraryName}DelegatingLexer
Also, do you really need to be explicitly constructing a MockLexer? Using a framework like Mockito can make your testing considerably easier and faster; You can get started as easily as:
Lexer mockLexer = Mockito.mock(Lexer.class);
Mockito.when(mockLexer.doFoo()).thenReturn("bar");
My recommendation, as I stated in the comments, is to use Lexer for your interface and DefaultLexer for the default implementation. This pattern is used quite frequently and as such is very understandable to anyone who will be maintaining your code. As for the mock object, it would also be understandable to name this something like MockLexer.
As an example of a naming convention that Java uses:
javax.swing.table.TableModel is an interface
javax.swing.table.AbstractTableModel is an abstract class implementing TableModel
javax.swing.table.DefaultTableModel is an implementation of AbstractTableModel.
There is however, no recommendation in the Java Codding Conventions outside of using capital letters, nouns, etc.
I usually use option 1 - interfaces called Lexer, with default implementations called either DefaultLexer or LexerImpl. I like this, because I think it lets you talk about the classes easily - if you have multiple implementations of Lexers, then their concrete names can describe the implementation type - eg NativeLexer or TreeBasedLexer or whatever. As a commenter mentioned, then your mock class (if you have one) can follow this pattern with a name like MockLexer.
However, with mocking libraries such as the excellent Mockito, you can mock concrete classes anyway - so you no longer need to use interfaces everywhere in order to test things easily. Here is the example they give in their documentation:
//You can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
That said, I would still recommend using interfaces instead of tying method signatures to concrete classes, because then things that use Lexer do not need to be tied to the implementation - this can be a massive gain in maintainability (eg if you need to have multiple implementations later).
In my experience there are two standards.
"Tag" your interface. (ILexer, LexerInterface, etc)
Use the name for your interface and use a different name for the concrete implementation.
I know these are already the options you presented. The trouble is, not one of them is firmly the "standard."
I strongly prefer option 2). A class name for an object should tend to be a noun that fits within the context of an "is-a" sentence. It feels weird to say that an object "is-a" LexerInterface whereas it is natural to say that an object "is-a" DefaultLexer.
Since ultimately my class or interface name represents a type, I shy away from "meta" information in a class or interface name.

Java: extending Object class

I'm writing (well, completing) an "extension" of Java which will help role programming.
I translate my code to Java code with javacc. My compilers add to every declared class some code. Here's an example to be clearer:
MyClass extends String implements ObjectWithRoles { //implements... is added
/*Added by me */
public setRole(...){...}
public ...
/*Ends of stuff added*/
...//myClass stuff
}
It adds Implements.. and the necessary methods to EVERY SINGLE CLASS you declare. Quite rough, isnt'it?
It will be better if I write my methods in one class and all class extends that.. but.. if class already extends another class (just like the example)?
I don't want to create a sort of wrapper that manage roles because i don't want that the programmer has to know much more than Java, few new reserved words and their use.
My idea was to extends java.lang.Object.. but you can't. (right?)
Other ideas?
I'm new here, but I follow this site so thank you for reading and all the answers you give! (I apologize for english, I'm italian)
If it is only like a "research" project in which you want to explore how such extension would work, you could provide your own implementation of the Object class. Simply copy the existing object implementation, add your setRole method etc, and give -Xbootclasspath:.:/usr/lib/jvm/java-6-sun/jre/lib/rt.jar as parameter to the java command. (I will look for api-classes in . before looking in the real rt.jar.)
You should consider using composition rather than inheritence to solve this problem; that way you can provide the functionality you need without using up your "one-shot" at inheritence.
For example, the JDK provides a class PropertyChangeSupport, which can be used to manage PropertyChangeListeners and the firing of PropertyChangeEvents. In situations where you wish to write a class that fires PropertyChangeEvents you could embed a PropertyChangeSupport instance variable and delegate all method calls to that. This avoids the need for inheritence and means you can supplement an existing class hierarchy with new functionality.
public class MyClass extends MySuperClass {
private final PropertyChangeSupport support;
public MyClass() {
this.support = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
support.addPropertyChangeListener(l);
}
protected void firePropertyChangeEvent() {
PropertyChangeEvent evt = new ...
support.firePropertyChangeEvent(evt);
}
}
you can extend Object - every class extends it.
you seem to need something like multiple inheritance - there isn't such a thing in Java
if you want to add functionality, use object composition. I.e.,
YourClass extends Whatever implements ObjectWithRoles {
private RoleHandler roleHandler;
public RoleHandler getRoleHandler() {..} // defined by the interface
}
And then all of the methods are placed in the RoleHandler
If you're talking about adding a role to all your objects I would also consider an annotation-based solution. You'd annotate your classes with something like #Role("User"). In another class you can extract that role value and use it.
I think it would need an annotation with runtime retention and you can check, run-time, whether the annotation is present using reflection and get that annotation using getAnnotation. I feel that this would be a lot cleaner than extending all your classes automatically.
I believe there are some frameworks which use exactly such a solution, so there should be example code somewhere.
If you are doing what you are doing, then inheritance is probably not the correct idiom. You may want to consider the decorator pattern, whereby you construct a class that takes as its parameter some other class with less functionality, and adds some additional functionality to it, delegating to the existing class for functionality that already exists. If the implementation is common to many of your decorators, you may want to consider putting that functionality in class that can be shared and to which you can delegate for all your decorators. Depending on what you need, double-dispatch or reflection may be appropriate in order to make similar but not quite the same decorators for a large variety of classes.
Also, as has been pointed out in the comments, String is declared "final" and, therefore, cannot be extended. So, you should really consider a solution whereby you delegate/decorate objects. For example, you might have some object that wraps a string and provides access to the string via getString() or toString(), but then adds the additional functionality on top of the String class.
If you just want to associate some objects with additional attributes, use a Map (e.g. HashMap).
What you really want to do would be monkey patching, i.e. changing the behaviour of existing classes without modifying their code.
Unfortunately, Java does not support this, nor things like mixins that might be used alternatively. So unless you're willing to switch to a more dynamic language like Groovy, you'll have to live with less elegant solutions like composition.

Categories