Eclipse supress compiler error - Is there a possible work around? - java

Here's the scenario:
I have a program that contains an annotation that I built out in my eclipse project, it's called 'flag'.
The 'flag' annotation has an 'id' element
I have a method in my class called 'connect' that establishes a socket connection.
I annotate the connect method by placing the 'flag' annotation before it and give it an 'id'
public class Foo {
#flag(id = 'slowConnection')
public boolean connect() {
// connect logic here...
}
}
Now, what I ultimately want is something like the following
public class Foo {
#flag(id = 'slowConnection')
public boolean connect() {
// connect logic here...
}
#flag(id = 'mediumConnection')
public boolean connect() {
// medium connection logic here
}
#flag(id = 'fastConnection')
public boolean connect() {
// fast connection logic here
}
}
Allow me to elaborate here. My objective is to be able to only include the correct 'connect' method at compile time based on an input parameter to the class. Method overloading is a similar way to do this, albeit I don't want to change the method signature. I'm also aware that inheritance would be a way to do this. Eclipse (rightly so) complains when I have the above code, saying that there's a duplicate method. Is there anyway that I could proceed with the above in Eclipse before I compile the program as I will perform some logic to strip out all but one of the 'connect' methods before the program is compiled? Is there a way to automatically disable auto-compilation in eclipse? Any tips or pointers would be helpful.

You move the connection logic to a separate interface and then use the factory pattern to generate the appropriate connection:
public interface IFoo {
void connect();
}
final class SlowFoo implements IFoo {
//Implementation for slow connections
}
final class MediumFoo implements IFoo {
//Implementation for medium connections
}
final class FastFoo implements IFoo {
//Implementation for fast connections
}
If the classes share common code, you should consider introducing a base class like FooBase.
The factory could then look like this:
public final class FooFactory {
public IFoo create() {
if (Connection.speed < 100) //Fictive value
return new SlowFoo();
if (Connection.speed < 1000) //Fictive value
return new MediumFoo();
return new FastFoo();
}
}
Messing around with the source code before compilation is not a good idea IMHO.

Related

Design pattern for similar functions with lambdas

I am trying to figure out a way or a pattern to simplify my Service class and make it very adjustable. My aim would be for the method in Service class to be accessed for example with lambdas or Predicates.
class Client {
#RequestLine("something/a")
public A fetchA() {}
#RequestLine("something/b")
public B fetchB() {}
//... lots of similar methods
#RequestLine("something/z")
public Z fetchZ() {}
}
class Service {
Client client;
public void fixA(){
client.fetchA();
method();
}
public void fixB(){
client.fetchB();
method();
}
// ... lots of similar methods
public void fixZ(){
client.fetchZ();
method();
}
void method() {}
}
So my point how I could change it so it would use lambdas or something that would leave my Service class with one of the "fix" methods but it would know what I need to fetch from my Client.
If this question is bad and does not comply with rules here then please point me in the right direction as I am lost.
I guess what you want is
class Service {
private Client client;
public void fix(Consumer<Client> consumer){
consumer.accept(client);
method();
}
private void method() {}
}
that you can call using
service.fix(Client::fetchB);
One way would be to pass the call to your client as an argument to the method of your service. You'd need to use generics:
class Service {
Client client;
public <T> void fix(Function<Client, T> clientCall) {
T result = clientCall.apply(client);
// Do something with result
method();
}
}
You would need to call your service fix method as follows:
service.fix(Client::fetchA);
This question may be somewhat opinion based but let’s give it a try.
From my point of view the first design flaw you made is to put all the fetchXYZ methods into one client. You could create an interface Client that might look like this
interface Client<T> {
T fetch();
}
And create implementations of this interface like this:
public class ClientA implements Client<A> {
#RequestLine(”something/a“)
public A fetch() {
// do fetch stuff
}
}
You could store instances of the client implementations locally in a map or use a Factory pattern to create the right client depending on your input. And finally the fix method in your service might look like this:
public void fix(String clientType) {
// returns instance of ClientA for ’a‘ for example
final Client client = getClientForType(clientType);
client.fetch();
method();
}
There‘re probably plenty of ways to solve your requirements and this is just one of them.
I personally don’t like the idea of passing the client function as parameter to your method (although you asked for it) as in your current design Client has different responsibilities (fetches A, B and so on). Using lambdas actually enforces this flaw and furthermore hides what Client actually does.
Just my 2 cents.
Usually the point of Service is to be a facade over the Client. If that is the case with your example and you dont want to expose Clent class to the caller of Service you can go with single method and an enum like this:
public class Service {
Client client = new Client();
public enum FixType{
A(Client::fetchA),
B(Client::fetchB),
Z(Client::fetchZ);
private Consumer<Client> c = null;
private FixType(Consumer<Client> c) {
this.c = c;
}
private void fix(Client client) {
c.accept(client);
}
}
public void fix(FixType ft) {
ft.fix(client);
method();
}
void method() {}
}
And call fix by passing one of enums:
new Service().fix(Service.FixType.B);
Why not just
class Client {
public A fetch (String identifier) {
ArrayList<String> identifiers = ...;
// validate user-provided identifier here
if (___.equals(identifier)) {
// specific code for each identifier
} else if {
// ...etc.
}
}
}
class Service {
Client client;
public void fix (String identifier){
client.fetch(identifier);
method();
}
void method() {}
}

Encapsulating and mocking

Suppose I have class with simple dependency:
public interface Dependency {
int doSomething(int value);
void doMore(int value);
int doALotMore(int value);
}
public final class A implements SomeInterface {
private final Dependency dep;
public A (Dependency dep) {
this.dep = dep;
}
#Override
public int add(final int x) {
dep.doMore(x);
return x + dep.doSomething(x) + dep.doALotMore(x);
}
}
And I'm writing test using mocks:
public class TestA {
private Dependency mockDep;
private SomeInterface a;
#Before
public void setUp() {
mockDep = Mockito.mock(Dependency.class);
a = new A(mockDep);
}
#Test
public void shouldAdd() {
final int x = 5;
when(mockDep.doSomething(x)).thenReturn(6);
when(mockDep.doALotMore(x)).thenReturn(7);
int actual = a.add(x);
assertThat(actual, is(18));
verify(mockDep, times(1)).doSomething();
verify(mockDep, times(1)).doALotMore();
verify(mockDep, times(1)).doMore();
verifyNoMoreInteractions(mockDep);
}
}
So far so good.
So the question is: do we violate encapsulation of class A by verifying how exactly the dependency was used? Does it really needed to test that dependency was used in exactly that way? Shouldn't we test A like a black-box (delete verify invocations from test case and leave just assertThat)? And how to deal with dependencies in such case?
The reason I'm asking is that I caught myself writing good amount of verification dependency code and it seems that we start to test actual internal realization details about class. And I feel uncomfortable about that because when I will try to rewrite this realization details in another way I need to rewrite test cases although the result of add for example will be the same. If I would test my class as a black-box I can change realization details and still be sure that given input will give same output.
Or it is necessary to actually test exactly the realization details and that is the point of unit-test itself? It seems somewhat wrong for me.
Consider this test instead:
public class TestA {
private Dependency mockDep;
private SomeInterface a;
private final int x = 5;
#Before
public void setUp() {
mockDep = Mockito.mock(Dependency.class);
a = new A(mockDep);
when(mockDep.doSomething(x)).thenReturn(6);
when(mockDep.doALotMore(x)).thenReturn(7);
}
#Test
public void shouldAdd() {
int actual = a.add(x);
assertThat(actual, is(18));
}
}
It really depends on logic which you're testing. Since your example don't provide any context, I'll give you a case when I feel not only comfortable to test such interaction, but even mandatory:
Let's say you're testing authentication token validation. You pas some token to your validator and it returns true/false. Inside of your validator you're calling some jwt.validate or any other 3rd party hash validation method. In this case I need to know that this validator will be called every time, because I can introduce some if token == null condition inside which will bypass this validation call and just return false. Then your tests could still pass but your code is now vulnerable to timing attack.
It's one kind of example. The other type of test I'm comfortable of testing that way is so called border testing. I want to know that my class triggers stripe payment gateway - so I mock it and just make sure it gets called without checking anything sophisticated in this particular test.

Shadowing variable used in a default method of an interface in Java 8

Today I was thinking about a nice way to write less code for a common functionality that is required for different objects.
Inheritance can do the job but then the classes won't be able to inherit from anyone else, so I chose Interfaces.
So I have my interface with the functionality I will need for some objects:
public interface Test {
String message = "Hello from Interface!";
default void printMessage() {
System.out.println(message);
}
}
And then I can use it in any object without having to override/write any code more than just simply calling the method when needed:
public class TestingTest implements Test {
public String message = "Hello from Class!";
public TestingTest() {
printMessage();
}
public static void main(String[] args) {
new TestingTest();
}
}
It works like a charm! But... Then I thought, what if I want some of those objects to specify a different message without being required (optional), well first thing I thought was to shadow the interface variable, but it doesn't work, the default method keeps using the variable from the interface instead of the class variable (which shadowed it).
A solution of course would be to overload the printMessage method in the interface so it recieves the message as a parameter for when the user requires to specify the message, but is there any more elegant way? Something like simply just declaring a new message in the class?
The String message in the interface is static (AFAIK). So that scheme does not work.
You might do something (ugly) as:
default void printMessage(String... messages) {
if (messages.length == 0) {
messages = new String[] { "arrgg" };
}
System.out.println(messages[0]);
}
Fields have no inheritance, so the value can only stem from an overridable method like
public String message() { return "..."; }
What you want is a functionality in n classes that should also be modifiable, if needed.
To be honest, your example is a little bit abstract and thus my answer will be abstract, too.
public interface Test {
void printMessage();
default void printMessage(String message) {
System.out.println(message);
}
}
public class TestingTest {
private final test;
public TestingTest(Test test) {
this.test = test;
}
public void someMethod() {
test.printMessage("Hello from class");
}
}
Additionally, you would have a class that implements the interface and offers the message. This way you could group your objects, change the message, make more complex logging and you would actually see the dependency from outside.
In my opinion, you are misusing the interface. An interface offers public methods to call it from outside, but you want to use them inside like they were private functionalities for the class.
Just use objects instead.

How to make this code DRYer

So I have a generated class (PartnerConnection) that provides DML operations to the SalesForce cloud platform. We were having issues where our long running integration process was failing due to connection issues with either SalesForce or the system running the code.
In order to solve this issue, I extended the PartnerConnection class with what I name an AdvancedPartnerConnection. The AdvancedPartnerConnection just overrides the methods of the PartnerConnection and wraps them with try/catch/retry logic.
#Override
public QueryResult query(String queryString) throws ConnectionException{
int attempt = 0;
ConnectionException lastException = null;
while(true){
if(attempt < maxAttempts){ //maxAttempts constant
if(lastException != null){
try {
//exponentially increase wait times
Long sleepTime =(long) Math.pow(sleepBase, attempt) * 300;
Thread.sleep(sleepTime);
} catch (InterruptedException e1) {
// something bad has happen, throw the connection exception
throw lastException;
}
}
attempt ++;
try{
//call super class method
return super.query(queryString);
}catch(ConnectionException e){
lastException = e;
}
}else{
throw lastException;
}
}
}
I've implemented this for a handful of the super class methods and the only difference is the method being called and its' parameters. It has become a real pain if I decided to change any of the retry logic as I want it to be consistent across all methods.
Does anyone have a way I could extract the retry logic into a separate class or method and maybe pass in the function call? I've done stuff like this in .NET but I'm not sure how to do it in java.
You basically want to capture all calls to all object methods and apply some logic to all of them.
You could create a Proxy and retry in the handler invoke method.
With this approach based on the method signature you decide what to do.
Another approaches could use AspectJ or any other AOP framework, but your use case is very simple to add that kind of dependencies, IMO.
If the class which you want to add some behaviour is not yours then this solution might not be the most elegant. But if you are willing to sacrifice some elegance to gain maintainability (since you are not replicating code) then you could:
class NotYourClass {
public void voidMethod() {}
public int intMethod(int n) { return 0; }
}
To create a proxy you must create an interface with all the methods of the class. This is the crappy part, but this do not add any dependency to your application.
interface YourInterface {
public void voidMethod();
public int intMethod(int n);
}
Next thing you need is an InvocationHandler that will contain the behavior.
class YourInvocationHandler implements InvocationHandler {
private final NotYourClass target;
public YourInvocationHandler(NotYourClass target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// Here you must look to the methods that are the ones that you want.
return method..invoke(target, args);
} catch (Exception e) {
// Retry?
method.invoke(target, args);
}
}
}
Please bear in mind that this is from the top of my head. But should be something along those lines.
If creating that interface is something unnacceptable for you then you can look at some AOP frameworks.

Accessing public methods of a Private Inner Class, from outside the Enclosing class

I have the following code class Agent.java :
public class Agent {
Helper helper ;
private class SpecificBehaviour extends Behaviour{
private Apple a;
public SpecificBehaviour(Apple a){
setApple(a);
}
public void setApple(Apple a){
this.a=a;
}
public Apple getApple(){
return a;
}
}
public void someMethod(){
helper = new Helper(this);
}
}
In the Helper.java ( another class within the same package) I would like to access the getApple() method. did some search and found this link
I am wondering if there is a better/ easier way of doing this ?
There are at least two issues here:
Helper doesn't know of the existence of SpecificBehaviour, because it's a private class. It could potentially know about the Behaviour class, which you haven't given any details of. If getApple() is declared in Behaviour, and if Behaviour is visible to Helper, then the visibility part needn't be a problem.
Helper will need a reference to an instance of SpecificBehaviour, which means you'll need to instantiate SpecificBehaviour. For that, you'll also need an instance of Agent, because SpecificBehaviour is an inner class. It's not clear whether you have such an instance.
Basically I think the presence of a private inner class is adding confusion here. If you're reasonably new to Java, I'd strongly recommend sticking to top-level classes for the moment. They have a few subtleties around them, and it's best to try to learn one thing at a time.
If this doesn't help, please give more context - your question is quite vague at the moment. Where do you want to use getApple within Helper? Should part of the state of Helper be a reference to an instance of SpecificBehaviour, or should it be a method parameter? Have you created an instance of Agent? What does Behaviour look like? You may find that in the course of answering these questions one at a time, you're better able to figure out the problem for yourself.
- Use Composition principle to get the access to the getApple() method.
Eg:
public class Agent {
Apple a = new Apple(); // Agent class has a reference of type Apple.
.....
.....
}
- Second way would be to make the getApple() method static in Apple class, and then access it from Agent class using the Class name with . (dot) operator.
Eg:
public class Agent {
public void go(){
Apple.getApple();
}
.....
.....
}
You need to ask the Agent object you are passing to the Helper for the instance of the private class SpecificBehaviour. This is the way it works. Encapsulation remember.
Jon Skeet stated that and I completely agree on it:
Helper will need a reference to an instance of SpecificBehaviour,
which means you'll need to instantiate SpecificBehaviour. For that,
you'll also need an instance of Agent, because SpecificBehaviour is an
inner class. It's not clear whether you have such an instance.
Actually, you can understand how weird your try is by testing the sample code below:
Agent.java
public class Agent
{
private class SpecificBehaviour
{
public String toString()
{
return "specific behaviour";
}
}
public Class getInner()
{
return SpecificBehaviour.class;
}
}
Helper.java
public class Helper
{
public static void main(String[] args)
{
try
{
Agent agent = new Agent();
System.out.println(agent.getInner().newInstance().toString());
}
catch (InstantiationException e) { e.printStackTrace(); }
catch (IllegalAccessException e) { e.printStackTrace(); }
}
}
The code above just compiles fine. And let's see what the output is:
java.lang.InstantiationException: Agent$SpecificBehaviour
at java.lang.Class.newInstance0(Class.java:340)
at java.lang.Class.newInstance(Class.java:308)
at Helper.main(Helper.java:5)

Categories

Resources