IntelliJ and built in Java Function Interface - java

My Spring components implement java.util.function.Function. The idea behind this is to force a functional style with small encapsulated functions.
#Component
public class MyFunction implements Function<In, Out> {
public Out apply(In in) { .... }
}
// example usage
#RestController
public class MyApi {
private MyFunction f;
public void foo() {
someList.stream()
.map(f)
. // whatever
}
}
Two problems arise with IntelliJ 2018.1:
"Find Usages" offers a choice to find usages of the base method. If I accidentally hit "Yes", IntelliJ finds a zillion usages and slows down until it almost freezes. Well, I should definitely select "No" here, but it is still a small issue.
Using the function in a Stream (e.g. filter) with "Method Reference" (as IntelliJ suggests) is even more problematic. Using "Find Usages" and selecting "No" will not show the "real" usage(s) im looking for. This makes it hard to navigate in the code.
This leads me to my questions: Is it a good practice to use the built-in Function Interface or should I write my own Function without declaring it as a FunctionalInterface? Do you consider the mentioned problems as an IntelliJ bug? Are there workarounds you know of?

Your approach seems valid to me, yet I try to avoid directly implementing Function as much as possible. The main reason is: naming.
I can understand that if a class has a meaningful name (e.g. InOutMapFunction), you might not feel the need for the method to have a meaningful name too. Still, I prefer names like InOutMapper.mapInToOut to InOutMapFunction.apply.
Besides, if you can think of more than one InOutMapper, make it an interface and let the component implement it.
Some may believe it's not worth to create your own functional interfaces if they "correspond" to the existing ones, but I hardly ever regret it, especially that in real uses cases, this impacts readability a lot, e.g. compare:
SomeParticularTypeContextFinder, and
Function<SomeParticularType, SomeParticularTypeContext>.
Here's how I'd implement your example:
#Component
public class PlainInOutMapper implements InOutMapper {
#Override
public Out mapInToOut(In in) { .... }
}
#FunctionalInterface
interface InOutMapper {
Out mapInToOut(In in);
}
// example usage
#RestController
public class MyApi {
private List<In> someList;
private InOutMapper mapper;
public void foo() {
someList.stream()
.map(mapper::mapInToOut)
. // whatever
}
}

You can limit the scope of the search via the 'Find Usages Settings' (default on Windows: CTRL+ALT+SHFT+F7)
The settings apply to the search via ALT+F7 as well as the Mouse Wheel Click one. Maybe limiting it to your current module does the trick?

Related

Java interface and class definition

I am trying to understand a Java code that I received (I am a C# programmer)
public interface BaseDA {
...
}
public class BaseDAImp extends HibernateDaoSupport implements BaseDA {
...
}
public interface TxnDA extends BaseDA {
public Txn getTxn(long id);
}
public class TxnDAImp extends BaseDAImp implements TxnDA {
public Txn getTxn(long id) {
....
}
}
And in another class it is used this way
protected void ShowTxn(long int) {
TxnDA txnda = (TxnDA) appContext.getBean("txnDA");
txnda.getTxn(id)
}
All classes extend a base class and implements an interface. This is almost done for every single class in the java code.
Question
1 - Can someone please explain this code to me? I already know we use interfaces (in C#) when we might want to couple software, plugin, hide implementation details.
2 - As none of above conditions are true for this java library, is it safe to modify the code like below?
public class BaseDA extends HibernateDaoSupport {
...
}
public class TxnDA extends BaseDA {
public Txn getTxn(long id) {
....
}
}
This is a classical approach which, in theory, should ensure the code being easily expandable and loosely coupled. If you look in old Java books you will find this in many code-architecture examples.
However, this approach is NOT clean, not really profitable and you definitely should not do it yourself, unless it is your preferred style (which it is not I assume, as you are trying to understand it).
Software engineering has evolved a great deal and the modern approach is to focus on the code being understandable and, well, clean. Writing it in the above way will result in very hard debugging and a lot of time required for a new programmer to get the hand of the project.
On the other hand, this is simply an architectural decision, so it is not straightforwardly 'bad'. It is simply outdated :-)
As for Question #2 - yes, this seems reasonable, although I can not guarantee it will work, you did not provide enough code nor context.

Intellij/ Java - identify calls to annotated methods

I need to be able to identify calls to methods with specific annotations in Intellij Idea 13, during compile time or by using static code analysis, like calls to #Deprecated methods are identified.
I have looked into doing a structural search in idea, these are supported in static code analysis, and am able to identify method calls from there, but I can't find a way to limit these to calls to method with annotations.
For example
public class A {
#Foo
public void foo(){
// do something...
}
public void bar() {
// do something else....
}
}
public class main {
public static void main(String... args){
A a = new A();
a.foo(); // <---- should be highlighted
a.bar();
}
}
You can by defining your own structural search template like this:
#Foo
$ReturnType$ $Method$($ParameterType$ $Parameter$);
save it e.g. as "methods annotated with #Foo"
and then do a structural search for
$expression$
with the filter reference=methods annotated with #Foo
(to add filter to $Expression$ hover with the mouse over it and then there will be a popup asking you if you want to edit filters and then you add a reference filter)
You could do this in IDEA (which would involve using IDEA's internal interfaces; I don't know offhand which ones give access to annotations).
Depending on your use case, another alternative would be to use an external tool such as the Checker Framework. The advantage is that it is externally supported and has a lot of existing functionality, so there would be less of your own code to write and maintain. Additionally, other people who don't use IDEA would be able to run the analysis. The disadvantage is that there would be less tight integration with the IDE; you would need to configure IDEA to run the analysis, which is straightforward.

How can one add breakpoints or custom code to an interface method implemented by many subclasses?

I am working on source that has a lot of subclasses (call them A and B) implementing a common interface Visitor, with a method visitProgram. Is there any way to break when any of the subclasses hits this method (i.e. A.visitProgram or B.visitProgram)? Alternate language solutions would be fine, but I cannot rewrite the existing source.
Since you're debugging I assume you can add some new code and build the whole thing.
That said, you can use Aspect Oriented Programming (AOP) to get a pointcut that captures the execution of visitProgram, and in theory you can put your breakpoint in the pointcut. You can think of AOP as a technique to cut laterally through your program (as opposed to OOP which builds "vertical" structure).
In this instance, you want to perform something just before each time visitProgram (of any instantiation of your Visitor interface) is run. This is a lateral cut, so AOP should fit your need.
Basically, you'll have a function in which you can set a breakpoint such that any time visitProgram gets called your program will halt just before it executes.
I'd recommend using Spring AOP, it's pretty straight forward, just follow the manual for setup instructions. Your pointcut should look like this:
#Aspect
public class BeforeVisitProgram {
#Before("visitProgram()")
public void doStuff() {
// break in here
}
}
Use an abstract class between the calling code and your implementations, such as:
interface DoesStuff {
void doStuff();
}
abstract class AbstractDoesStuff implements DoesStuff {
void doStuff() {
doStuffToo(); // debug point
}
abstract void doStuffToo();
}
It does mean though that all your implementation must be subclasses of the abstract class, so this approach might not suit every situation.

Automated way to Extract Interfaces from a Java Class

I've got a collection of concrete Classes which define an API, and I would like to extract the Interface of these classes (ie: essentially the type hierarchy and public methods) from the actual implementation of the API.
So for example if one of the public classes in the API is
public class Foo extends Bar {
/* some fields which I don't care about */
public void method() {
/* implementation here */
}
public void otherMethod() {
/* implementation goes here */
}
/* some non public methods which I don't care about */
}
I would like to break into an interface and an implementation
ie
public interface FooInterface extends BarInterface {
public void method();
public void otherMethod()
}
public class Foo implements FooInterface {
/* etc etc */
}
and
Is there a tool I can use to do this separation in automated way, or am I going to have to roll my own program to do the job? It needs to be a tool that requires minimal interaction.
I found the solution!
Eclipse, has support for refactoring scripts, the scripts are in xml yet not very human friendly but I have generated the scripts anyway that makes eclipse perform all the refactoring.
For details of eclipse script refactoring, look here and use eclipse to generate a few examples for you so you know what the script should look like
Many IDEs, like IntelliJ, have an "Extract Interface" command which performs a refactoring for you: http://www.jetbrains.com/idea/features/refactoring.html#Extract_Interface
javap, a tool in the JDK, will get you most of what you want. However, be prepared for it to not handle some things correctly - sorry, I forget what, maybe annotations, inner classes, something like that.
If embedding javap in you own Java app would help, you can do something like this:
import sun.tools.javap.Main;
...
void javap(String className) throws IOException
{
bos = new ByteArrayOutputStream();
ourOut = new PrintStream(bos);
PrintStream oldOut = System.out;
System.setOut(ourOut);
String[] params = new String[] {"-public", className};
Main.main(params);
System.setOut(oldOut);
String str = bos.toString();
}
This requires the Sun JDK tools.jar in the classpath.
I'm pretty sure you'll have to roll your own tool to do this job; it's not something that many developers would use, and those who did use it wouldn't use it often. Extract Interface, to be done right, really needs intelligence (the real kind) guiding it. A tool that blindly extracted all public & protected elements, and blindly built an interface hierarchy to mirror an implementation hierarchy, is far from smart, and the end product wouldn't be pretty. Developing the (artificial) intelligence to make good decisions about what to include and what to lead out - that would be a useful tool, but I confess unimaginably difficult for me. What current IDEs offer - guided assistance - is probably the best compromise. Cheer up; it's massively less tedious than doing every step by hand!

Java: Is there a way to you enforce a implementation of private methods?

I have 5 or 6 classes that I want to have follow the same basic structure internally. Really most of those that the classes should follow are just for the use of the function itself, so I really want these methods to be private.
Is there any way to achieve this? I know interfaces would work great but they won't take private members and won't allow you to redefine the scope in the implemented method. Is there any workaround for this?
Thanks
I think the closest you can get is using an abstract class with abstract protected methods:
abstract class A {
protected abstract void foo();
}
class B extends A {
protected void foo() {}
}
To define common logic, you can call the protected method from a private method in the super class:
abstract class A {
private void bar() {
// do common stuff
foo();
}
protected abstract void foo();
}
This way, you can allow subclasses to fill the private common template method with specific behavior.
Create an abstract base class that outlines the structure and common flow. Specify abstract methods for the steps in the flow that must be implemented by the inheriting classes.
Hmm, private functions can't be called by any other classes, even by subclasses. So what's the point in having private functions with the same name in different classes?
There is no way to enforce it at compile time, but you can write a unit test or a simple program to test for the existence of the methods using reflection.
I assume you are doing this to make the classes consistent for aesthetics/design reasons. If you are doing it for some other reason you should really use the abstract protected way others are suggesting.
Here is some code to get you started on such a tool/unit tests (you should improve the error messages at the very least, and I would really suggest unit tests rather then what I have here):
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Main
{
public static void main(String[] args)
{
check(B.class, Modifier.PRIVATE, void.class, "doit", new Class<?>[] { int.class });
check(C.class, Modifier.PRIVATE, void.class, "doit", new Class<?>[] { int.class });
}
private static void check(final Class<?> clazz,
final int modifiers,
final Class<?> returnType,
final String name,
final Class<?>[] params)
{
try
{
final Method method;
method = clazz.getDeclaredMethod(name, params);
if(method.getModifiers() != modifiers)
{
System.out.println("modifiers do not match");
}
if(method.getReturnType() != returnType)
{
System.out.println("return type does not match");
}
}
catch(final NoSuchMethodException ex)
{
System.out.println("could not find method");
}
}
}
interface A
{
void foo();
}
class B
implements A
{
public void foo()
{
doit(0);
}
private void doit(final int x)
{
}
}
class C
implements A
{
public void foo()
{
doit(0);
}
private int doit(final int x)
{
return (5);
}
}
Create an outline 'common' class, with all your private methods on them.
Then create your 5 or 6 classes , each which have a field on there of type 'common'.
You won't be able to call the private methods of course (but you say these are really internal to the class) - you'll have to advertise some public methods to alter state as well of course.
public class common {
private method1() { ; }
private method2() { ; }
public other() { ; }
...
}
public class myclass1 {
common commonMethods;
}
public class myclass2 {
common commonMethods;
}
or even (assume 'common' is defined as above):
public class template {
common commonMethods;
}
public class myclass1 extends template {
...
}
So you get a (package-protected) 'commonMethods' field for 'free' on each of 5 or 6 subclasses.
After subsequent discussion on this thread, it appears the author doesn't actually want to share logic : just method signatures essentially , so this answer doesn't fit with that requirement.
While the interface methods themselves must always be public, you could make the interface package private and keep all of your Car (for example) implementations in the same package.
package com.some.car.pkg;
interface Car
{
public void gas();
public void brake();
}
Even though the methods are public, it doesn't matter since outside of the package com.some.car.pkg, Car is not visible. This way, all of your implementers would not be forced to extend an abstract class. The fact that you want common methods means truly private isn't the real solution, and IMHO, you want an interface, since it sounds like in your case an abstract class isn't quite right as there is no shared logic.
My 2 cents.
The "throw MethodNotImplementedException();" might be a useful construct.
If abstract protected really isn't protected enough, I wonder what the concern is. In any case, an alternative similar to monojohnny's would be to use the strategy pattern. This ensures that:
derived classes must define the behavior
derived classes can't access the behavior after defining it
instances can't access one another's behavior
E.g., with apologies for borrowing the car metaphor despite no automotive chops:
public interface GearBoxStrategy {
public void changeGear(int newGear);
}
abstract public class Car {
private GearBoxStrategy gearBox;
public Car(GearBoxStrategy g) {
this.gearBox = g;
}
public void accelerate(double targetSpeed) {
int gear = getTargetGear(targetSpeed):
gearBox.shift(gear);
}
}
public class AutomaticTransmissionCar {
public AutomaticTransmissionCar() {
super(new AutomaticTransmissionGearBoxStrategy());
}
}
public class ManualTransmissionCar {
public ManualTransmissionCar() {
super(new ManualTransmissionGearBoxStrategy());
}
}
Create an abstract base class with a method marked final that describes the common flow that includes your private methods. Marking it as final means that it can't be extended by subclasses and thus the business logic is enforced as long as your calling code utilizes it. Extension points can be created by marking methods as protected. For example say you have a class that represents a retail store.
private final void doTransaction() {
float amountDue;
// a protected or abstract method that extenders can override
Collection items = this.unloadShoppingCart();
for (Object item : items) {
// another protected or abstract method
amountDue += this.getPrice(item);
}
// your private method
amountDue += this.getSalesTax(amountDue);
}
Is it possible to make all the classes inherit from the same base class?
If so, one thing you could consider would be at runtime in the base class's constructor use reflection to validate that the subclass is following the rules you describe, and throw an exception if it fails your validation rules.
The naive implementation of this test of course would have significant performance issues, so you'd have to be pretty clever about the way you implement the test.
For a start, the test should only be run once for all instances of a particular subtype T. So, you would have to cache the validation information somewhere. One way to do this would be to use some kind of static (global) hash table in the base class keyed on the type of each subtype.
You would also have to perform some kind of thread safe synchronization around this cache. What you really need to avoid on this is a performance hit for reads. What I've done in a similar case before was use a combination of the double check locking pattern and the use of an immutable hashtable so that you only take a performance hit for locking when attempting to write to the hashtable (i.e. when you create the first instance of a particular subtype T).
I'm actually not experienced in Java, what I describe, I implemented in .NET, which is why I can't provide you with a code example, but all the concepts should be easily transferable to Java - everything I mention is (AFAIK) available on both platforms.
Take a look at XDepend, it uses reflection to create a database based on your compiled code.
http://www.xdepend.com
It's aimed at software architects who wish to be able to quickly check potentially large libraries of compiled code for potential problem areas. It has inbuilt reports and visualization for such things as relationships between classes, cyclomatic complexity, coupling etc. etc.
In addition, it includes an inbuilt sql like query language "CQL" (for "code query language"). Using CQL you can define your own reports. You probably should be able to use it to define a report for violations of the rules you describe. Also, you can embed CQL queries directly into your code using annotations.
I haven't looked into it, but have used it's .NET equivalent 'NDepend', and it's a very cool tool.
Of course, you could also write your own custom tool which uses reflection to check your specific rules. XDepend may still be worth looking at though - it should be a lot more flexible.
Here's an idea: write a simple text parser to check for the existence of the methods. Include it as a task in Ant. As long as you are insisting on some form of coding standard, some simple text-matching should do it, ie, simply look for the formatted signature in the required source files.
In a comment you wrote "Yes that is the whole point. I know they can be called different things but I don't want them to be."
Now, some people might just say "that's impossible" but like most things in programming, it's not actually impossible, it's just a lot of work.
If you really want to do this, you can create a custom Java Annotation for your class and then write an Annotation processor and call apt as part of your build process.
Like I said a lot of work, but it might be worthwhile if you want to learn how Annotations work.
Writing annotations is actually pretty simple. They work kind of like regular classes. For example, if you just want to mark a class for some reason you can create an empty or marker annotation like this
public #interface Car { }
Then in your Annotation Processor you can check to make sure Car has the right private methods.
I've written my own annotations, but I checked them at Runtime using the reflection API, rather then at build time. They are actually pretty easy.

Categories