Why does ByteBuddy route method delegation to the "wrong" method in this scenario? - byte-buddy

I am putting together a very simple ByteBuddy delegate/proxy class.
The intention is (again, very simple) to proxy a class such that any of its non-final, non-private, non-static methods and so forth get routed to equivalent methods on its proxiedInstance field as returned by its getProxiedInstance method. (There should be exceptions made for the usual suspects: equals, hashCode, wait and notify and so on.)
I've set up my proxy class using the subclass strategy. I've also defined two methods, getProxiedInstance and setProxiedInstance, along with a private field named proxiedInstance of the proper type. I've done this using the FieldAccessor.ofBeanProperty() strategy. I've omitted that here for brevity and clarity. The class does in fact contain this field and these two methods.
Then I've defined the method interception like this, statically importing the relevant ElementMatchers methods:
builder
.method(not(isFinal()).and(not(isStatic())).and(not(isPrivate()))
.and((isPublic().and(named("toString")).and(takesArguments(0)).and(returns(String.class)))
.or((not(isDeclaredBy(Object.class)).and(not(named("getProxiedInstance"))).and(not(named("setProxiedInstance"))))))
)
.intercept(MethodDelegation.toMethodReturnOf("getProxiedInstance"));
In English: not final, not static, not private, and either the public String toString() method inherited from Object (or overridden), or any other method not declared by Object.class and not named getProxiedInstance or setProxiedInstance.
Suppose I have a class like this:
public class Frob {
public String sayHello() {
return "Hello!";
}
}
When I create a proxy class for it, instantiate it, and then call toString() on the proxy, I get Hello!.
This suggests to me somehow that the recipe I've quoted above is somehow routing toString() to sayHello().
From reading the MethodDelegation javadocs, it seems that maybe sayHello on the target/delegate object is picked for delegation because it is more specific than the method invoked on the proxy (toString). I guess name matching is lower priority than that.
I think this use case I have is relatively simple. How do I best accomplish it?

The best I could do, which works, but seems perhaps a little clunky or verbose, was this:
builder = builder
.method(not(isDeclaredBy(Object.class))
.and(not(isFinal()))
.and(not(isStatic()))
.and(not(isPrivate()))
.and(not(named("getProxiedInstance")))
.and(not(named("setProxiedInstance"))))
.intercept(MethodDelegation.toMethodReturnOf("getProxiedInstance"))
.method(is(toStringMethod))
.intercept(invoke(toStringMethod).onMethodCall(invoke(named("getProxiedInstance"))));
(toStringMethod is the Method resulting from Object.class.getMethod("toString").)

I think using MethodCall is a better approach to this. MethodDelegation is meant for "catch all proxies" where you inject corresponding dispatchers into what is often a single delegate method, maybe two. Method call is also much more performance since it does not need to do the analysis but just reroutes to a method of a compatible type.

Related

When to use singletons in OOP?

When reading about singletons, I have found this explanation as a reason to use singleton:
since these object methods are not changing the internal class state, we
can create this class as a singleton.
What does this really mean ? When you consider that some method is not changing internal class state ? If it is a getter ? Can someone provide code examples for class that uses methods that are not changing its internal state, and therefore can be used as a singleton, and class that should not be a singleton ?
Usually, when people are explaining singleton pattern, they use DB connection class as an example. And that makes sense to me, because I know that I want to have only one db connection during one application instance. But what if I want to provide an option to force using the new connection when I instantiate DB connection class? If I have some setter method, or constructor parameter that forces my class to open new connection, is that class still a subject to be a singleton ?
I am using PHP, but may understand examples written in JAVA, C#...
This is the article reference. You can ctrl+f search for "internal". Basically, autor is explaining why FileStorage class is a good candidate to be a singleton. I do not understand this sentance
"These operations do not change the internal class state, so we can
create its instance once and use it multiple times."
and therefore I do not understand when to use singletons.
In their example, they have some FileStorage class :
class FileStorage
{
public function __contruct($root) {
// whatever
}
public function read() {
// whatever
}
public function write($content) {
// whatever
}
}
And they say that this class can be a singleton since its methods read() and write() do not chage internal class structure. What does that mean ? They are not setters and class is automatically singleton ?
The quote reads:
These operations do not change the internal class state, so we can create its instance once and use it multiple times.
This means that the object in question has no interesting internal state that could be changed; it’s just a collection of methods (that could probably be static). If the object has no internal state, you don’t have to create multiple instances of it, you can keep reusing a single one. Therefore you can configure the dependency injection container to treat the object as a singleton.
This is a performance optimization only. You could create a fresh instance of the class each time it’s needed. And it would be better – until the object creation becomes a measurable bottleneck.

"Abstract" methods in Yii Behaviors

I've been developing Yii application. And I'm wondering if it's possible to declare in model behavior some kind of "abstract" method. I know that it impossible to use directly following declaration:
abstract class FantasticBehavior extends CActiveRecordBehavior
{
public abstract function doSomethingFantastic();
}
because we need an instanse of this class. But also I know that Yii is full magic:)
I just want to make owner class to redeclare method from the behavior in obligatory order. Sure, I can use interface in addition to behavior but ...
Sorry if I've missed something to tell or something is not clear. Just ask and I'll try to explain what I mean.
Does anybody know something about this?
Thanks in advance.
UPD
I do understand that Yii is just PHP. It doesn't extend PHP. It is superstructure over it. And it doesn't have multiple inheritance since PHP doesn't.
I do understand behavior method can't be declared using abstract keyword. That is why I have written word "abstract" in quotes. But whatever. I know how behaviors work.
My question was if I can somehow oblige model(e.g. child of CActiveRecord) to declare some method.
For example, for my purposes I can do something like this:
class FantasticBehavior extends CActiveRecordBehavior
{
public function doFantasticThings()
{
$this->owner->prepareForFantastic();
// some code
}
}
Therefore, if I attach this behavior to my model and call method doFantasticThings this method will try to call method prepareForFantastic from model(owner). And if model doesn't have method prepareForFantastic declared new exception will be thrown because non-declared method are called.
Looks like I've answered my question myself :) What do you think about this?
UPD2
Yes, I know that if we don't call "abstract" method we won't know that it is not declared. It is a "charm" of interpretable languages :) We don't know if there is any error untill the code is run. Although, it would awesome if we could know about this as earlier as possible. For example, once instance of FantasticBehavior-class is attached to the model we could throw some child of CException to show what required methods must be declared in model. To achive this we can use something like listed below:
class FantasticBehavior extends CActiveRecordBehavior
{
public function attach($owner)
{
if(!/*$owner has declared methods list this->abstractMethods*/)
{
throw new CAbstractMethodNotDecalared('....');
}
parent::attach($owner);
}
public function abstractMethods()
{
return array('prepareForFantastic');
}
}
We need to override method attach from class CBehavior and check if "abstract" methods declared. Method abstractMethods is used to get list "abstract" method.
I don't know if there is attachBehavior event exists. If so, we can use it instead of overriding attach method.
Using this idea Base class for behaviors with "abstract" methods.
What do you think about this?
Maybe in future I'll make extention for Yii and become famous and rich? :))
This might be a little confusing to explain...
No, you cannot "attach" abstract methods to your CActiveRecord model using Yii's Behaviors. All Behavior's do is some clever overrides of __call(), __get() and __set() that give the illusion of multiple inheritance. (This is a good article about it). Behaviors do not provide true "multiple inheritance" support for core language features like abstract classes and interfaces. So if you attach that Behavior and add doSomethingFantastic() to your CActiveRecord class, you will still get an error.
You can, of course, declare abstract Behaviors that other Behaviors extend. So if you created another SuperFantasticBehavior Behavior that extended FantasticBehavior and implemented doSomethingFantastic() in it, you'll be fine. But it won't force you to declare the doSomethingFantastic() method in the CActiveRecord itself.
For a little deeper understanding: The way Yii's CComponent::_call() override is structured, when you call a method it will first see if any of the behaviors have that method, and call the method on the class itself.
Behavior's seem cool at first (mixins!), but sometimes it's just better to remember that PHP is a single class inheritance language and keep is simple. ;)
UPDATE:
The difference is that if you could use abstract methods in this case you'd see a "Class must implement method" error when you try to run your code (any code), and your IDE would highlight the error. This is more of a "compile" time error (not that it really exists in an interpreted lang like PHP).
Instead you'll see a "non-declared method" error (as you mention) at runtime. But you won't see it until that method is actually called, meaning you don't get that nice early warning like an abstract definition would give you. And if that method is never called, you won't get the error, which to means it's not really "obliging" the declaration in the same way an abstract def would.
Sorry if my initial answer was starting out at too basic of a level, I just wanted to be sure there was no misunderstanding. It's an interesting discussion, and made me think more about what an abstract declaration really does. Thanks, and happy coding! :)
Cheers

adapter pattern and dependency

I have little doubt about adapter class. I know what's the goal of adapter class. And when should be used. My doubt is about class construction. I've checked some tutorials and all of them say that I should pass "Adaptee" class as a dependency to my "Adapter".
e.g.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
This example is copied from wikipedia. As you can see AdapteeClass is passed to my object as dependency. The question is why? If I'm changing interface of an object It's obvious I'm going to use "new" interface and I won't need "old" one. Why I need to create instance of "old" class outside my adapter. Someone may say that I should use dependency injection so I can pass whatever I want, but this is adapter - I need to change interface of concrete class. Personally I think code bellow is better.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
{
mInstance= new AdapteeClass();
}
}
What is your opinion?
I would say that you should always avoid the new operator in a class when it comes to complex objects (except when the class is a Builder or Factory) to reduce coupling and make your code better testable. Off course objects like a List or Dictionary or value objects can be constructed inside a class method (which is probably the purpose of the class method!)
Lets say for example that your AdapteeClass is a Remote Proxy. If you want to use Unit Testing, your unit tests will have to use the real proxy class because there is no way to replace it in your unit tests.
If you use the first approach, you can easily inject a mock or fake into the constructor when running your unit test so you can test all code paths.
Google has a guide on writing testable code which describes this in more detail but some important points are:
Warning Signs for not testable code
new keyword in a constructor or at field declaration
Static method calls in a constructor or at field declaration
Anything more than field assignment in constructors
Object not fully initialized after the constructor finishes (watch out for initialize methods)
Control flow (conditional or looping logic) in a constructor
Code does complex object graph construction inside a constructor rather than using a factory or builder
Adding or using an initialization block
AdapteeClass can have one or more non-trivial constructors. In this case you'll need to duplicate all of them in your SampleAdapter constructor to have the same flexibility. Passing already constructed object is simpler.
I think creating the Adaptee inside the Adapter is limiting. What if some day you want to adapt a pre-existing instance?
To be honest though, I'd do both if at all possible.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
: base (new AdapteeClass())
{
}
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
Let's assume you have an external hard drive with a regular USB port and you are trying to hook it up with a Mac which only has type-c ports. Yes, you can buy a new drive which has a type-c port but what about the data in it?
It's the same for the adapter pattern. There're times you initialize AdapteeClass with tons of flavors. When you do the conversion, you want to keep all the context.

Whats the correct way of creating objects?

For example, i see myself doing things like this latley, when i create an object, if it has a logical path of tasks then
public Class Link
{
public Link(String value)
{
callMethodA(value)
}
public void callMethodA(String data)
{
CallMethodB(doSomethingWithValue)
}
...
...
}
Here you can see, as soon as you instantiate the object, yours tasks get completed automatically.
The other way i can see of doing it is by creating an object, that doesnt link via the constructor, then calling methods individually.
Which was is right and why?
Thanks
Either way we can implement.
Recommended way is to do tasks like initialization stuffs within the constructor and rest of the things can be implemented by way of calling the method with its reference object.
for such scenario one should go for Factory pattern
for example:
Calendar.getInstance();
Constructor should do ALL that requires to make an object complete. That is, if without calling method callMethodA , if the object is incomplete then callMethodA must be called from constructor itself. If the callMethodA is optional API then the user of class Link can call the method when he wants.
I prefer second method. Constructor's job is to initialize the class members. Any modification to change the state of the object needs to be done seperately by member functions.
As long as the objects that are created do not have nothing in common the current way of creating them is fine. Factory Method or Abstract Factory pattern makes sense when there's similarity between created objects. They'll help you isolate the parts that are always the same and moving parts that define differences between objects.
It depends on business logic involved. Both ways are practical. If you want to simply initiate instance specific data, then better to do it in constructor method itself which is more logical and simple. It will save calling other methods explicitly unnecessarily. If instanciating your data is based on certain buisiness condition, then it is good to have main functionality in separate method and then conditionally call it from constructor. This is easy to manage in such scenario.
A constructor is meant to bring the object in the correct initial state. So use it for that purpose. As a general rule of thumb, only use a constructor to set properties. Basic calculations are also ok.
I would not recommend calling very time consuming methods, or methods that are likely to throw exceptions (like calling a webservice or access a file).
When you need to do very special things to bring the object in its initial state, make the constructor private and use a static method to create the object.

Rule of thumb for naming wrapper classes

I find myself creating a significant number of wrapper classes, purely because I want to mock out the behaviour of
Classes that don't lend themselves well to the RhinoMocks isolation model (for instance like DirectoryInfo or WindowsIdentity)
Native Win API methods (I normally collect all the methods I need into a single class and wrap the native calls as a class method)
I then find myself appending the class that is wrapped with a 'W' (to indicate that it's a wrapper) and so I end up with DirectoryInfoW (as opposed to DirectoryInfoWrapper which seems rather verbose). Similarly, I end up with wrapped native methods called NativeMethods.DuplicateTokenW.
What would be a good rule of thumb to follow when naming wrapper classes?
Naming conventions are whatever works for the team that you're working with. As long as everyone's ok with a particular convention, then it's ok.
I tend to prefer the more verbose version though, i.e. DirectoryInfoWrapper, rather than having a single letter that doesn't explain anything to anyone who's not familiar with the code. But that's just me.
I'll agree with aberrant80 , if everyone agrees with the convention you are using, then it'll work.
I personally prefer using names that are shorter and descriptive to the class's purpose. At least at the interface level. If you're using a mock framework, then IDirectory or IDirectoryInfo would be a decent set of names, while DirectoryInfoW or DirectoryInfoWrapper would be an interface implementer.
A better example might be wrapping an HttpRequest; define an IRequest to state 'this is what is important to my application', then Request, HttpRequestWrapper, Request, etc would be implementers.
So, to summarize, try and use descriptive, non-overly-verbose interface names.
Just as a side note, I found a more aesthetically pleasing (well, to me) way of wrapping native method calls:
public class NativeMethods
{
// made virtual so that it can be mocked - I don't really want
// an interface for this class!
public virtual bool RevertToSelf()
{
return WinApi.RevertToSelf();
}
...
private static class WinApi
{
[DllImport("advapi32.dll")]
public static extern bool RevertToSelf();
...
}
}
i.e. avoid name collision by encapsulating native method calls in a private nested class.
No 'good' solution to the wrapper class naming issue though, I'd probably go with aberrant80's suggestion and explicitly call my wrappers wrappers.
If you are using C++, you can use namespaces and then just re-use the same class name. For example:
namespace WrapperNamespace
{
class MyClass {...};
}
namespace InternalNamespace
{
class MyClass {...};
}