How setter methods changes business requirements? - java

I am working on Mockito and JUnit integration. For mocking the objects I created some setter method
#Mock
private SomeDaoImplClass someDaoImplClass
jdbcTamplate = Mockito.mock(NamedParameterJdbcTamplate.class)
someDaoImplClass.setNamedParameterJdbcTamplate(jdbcTamplate)
So method setNamedParameterJdbcTamplate(jdbcTamplate) was not there and I created this setter method in class.
I got some information that you can't create these set method in business class
b'coz its effecting business unit.
Please someone can suggest me how set methods affecting BU.

No business object should allocate its own dependencies (you know, due to that Inversion of Control/Dependency Injection thing)
So if you need to provide something to you objects you can do it either with setters or via constructor (the latter is preferred)
It's true that adding methods just for the sake of testing is a bad practice. In this case it can be even worse: adding a setter prohibit us to make the object immutable which is something desirable when working with multiple threads and adds some security restrictions (no attribute is without initialization after the constructor has finished.
If you need to add these methods document it and set its visibility to default so it's only visible from the same package (the tests will be at that same package) in order to minimize the impact in production
If you can't add a setter or modify the constructor... Well, it's not all lost. You can make use of reflection. By using this you can modify any attribute of your object even without accessors or even final attributes. Notice that this will be slower at runtime and will require some exception handling

Related

How to intercept field accesses (without getter/setter) using Bytebuddy

I am trying to use bytebuddy to intercept getfield and putfield accesses. I have read the rather comprehensive documentation on the site, but from what I can understand, it covers adding getters and setters to fields, rather than intercepting field accesses.
Here is basically what I am trying to do:
...
obj.prop = value;
x = obj.prop;
...
That in both these cases, I am trying to have some method called (or some bytecode inserted) before/after the field access. I was thinking of using Advice to do it, but I am unable to find a way to have it for something other than methods.
Edit:
I am using a Java Agent to do it.
I had an idea of adding a dup to duplicate the object reference followed by the call to a static method I defined to intercept the access (I only care about the object being referred to, not the field).
There is a new component that is still under development but that is already exposed with a basic API. It is called MemberSubstitution and allows you to replace a method call or field access with another execution.
This component does however rely on replacing the code that executes an instruction. Field access is non-virtual, therefore it is not possible to create any proxy class that would intercept a virtual access. Instead, you have to redefine any existing class that reads or writes the field, for example by using a Java agent.
As for your more specific question: At the moment, there is only a 1-to-1 substitution possible. I have not yet had the time to include a mechanism for adjusting the stack and local variable sizes. Also, you would also have to dup objects lower down on the stack if the field is non-static. The problem is not trivial so to say but I hope to offer such functionality some day.
At the moment you can however replace the field access with a static method call. Possibly, you can execute the original field operation from this method.

How to understand annotation in java And How to implement my annotation in java?

What I have known are:
annotation was added in java 5
annotation can be using in method, class, and property
annotation can work in RUNTIME, CLASS, SOURCE( I don't know how to work with CLASS and SOURCE, and their's features)
annotation with retention which is RUNTIME can be implement when java program is running.
And I want to implement a annotation to have follows features:
ensure class only being allowed to create a instance
ensure methods only being allowed to access method in the class
it is like as friend in c++
it is same as public and private , but more dynamicall, like
#MyAnnotation(allowMethods={xxx.doSomething})
public void getValue(){}
the getValues method only can be accessed in the instance self and xxx.doSomething() method
What should I do and learn in next?
And Where can I learn about these?
I think you might be misunderstanding something there. Annotations are descriptive elements, not parts of your program. You can write as many annotations as you want, and people who use your code will still be able to ignore them.
That said, an annotation that enforces a policy (as yours does) can actually be implemented, either at compile or at runtime, but you need an external mechanism to help you. I can think of 3:
Annotation processing lets you interact with the compiler and process annotations by generating code or by omitting compiler errors. Unfortunately, I don't think it will work for your case, as you want to protect your annotated type from instantiation, and that means the call site doesn't actually have an annotation. Annotation processing only gives you access to the actual code pieces that have annotations, not to those that refer to them.
AspectJ allows you to write policy enforcement aspects and omit compiler errors, based on static pointcuts. The problem here is that static pointcuts have very limited semantics, so while you could forbid the instantiation of your class altogether, or from certain packages, you could not limit the your class instantiations to 1.
The third way, and probably the only sane way is that you use a container like Spring or Guice and configure your class as singleton. As long as you only retrieve your class from the container, it will never create a second instance.
Finally: If you want to limit the number of instantiations of your class, you can always use a classic Singleton pattern approach.

How to call methods that inject parameters in a unit test?

There is a pattern which is widely used in my current project:
private Collection<Converter<T>> converters = new HashSet<>();
#Inject
private void init(#Any Instance<Converter<T>> converters) {
for (Converter<T> converter : converters) {
this.converters.add(converter);
}
}
This way I can create as many converters as I want and they are automatically injected to my bean.
My problem is now with testing: the converters collection is used in my code, but Junit doesn't call the init(..) method and I need to call it to set the mocked converters.
I could make the method protected, but I don't feel OK with it because I would be changing the visibility scope of the method.
I could also call the method using reflection, but this also doesn't feel right.
This brings me to the conclusion that this code could be improved to be more testable.
Is there anyway I change this code so the testability is improved but the references are still automatically injected?
Just go ahead and make it 'public' or 'protected'.
You are not actually gaining any protection from someone changing the collection post-instantiation this way (you've just made it a little more awkward), so you don't lose anything by exposing that method (in fact I'd argue you make your class slightly better, because than you let people chose how they want to construct, rather than forcing a use of injection/reflection).
If you did want to fully prevent post-instantiation modification, than you're going to have to go to a 'final' variable anyway, with an unmodifiable collection type and change to constructor injection, but I don't get the impression that this is what you want to do.
Thing is: if you can't "trust" the people who can write code within your "package" ... I guess having "private" on a method doesn't really help you anyway. Because if people want to mess up, and they can write code in your package, they will find ways to mess up anyway.
Meaning: if you drop the "private" on your method, yes it becomes package-visible. But you can place a javadoc on it that says: "Don't call directly; used for unit test/auto-wiring only" or something like that.

Accessing fields from a proxied object

I've run into an interesting problem while developing an ORM framework for Android. I'm using a library called dexmaker for bytecode manipulation, which enables me to create proxies for persistent objects in order to implement lazy loading.
The proxied instance has an associated InvocationHandler such that when a method is called on the proxy, the invoke method is called on the InvocationHandler, which then calls the proxied object's respective method assuming it's been lazily loaded. Nothing too surprising -- it's just like Java's Proxy class but allows me to proxy actual classes instead of interfaces (see dexmaker's ProxyBuilder).
The part that's become problematic is that I also use reflection to retrieve field values from persistent objects and -- now that I've introduced lazy loading -- proxies. Here is what I'm currently doing:
for (Field f : getPersistentFields(model.getClass()) {
...
Object val = f.get(model); // model is either a persistent object or a proxy for one
mapField(f, val, map);
}
This of course works for regular model instances, but for proxied instances, f.get(model) is not retrieving the proxied object's field value. Instead, it's returning the default value assigned in the class's constructor. The access on the proxy's field is not being intercepted obviously.
My question is this: is there any way I can intercept an access on a proxy's member variable made through reflection? If not, how can I retrieve the value of a proxy's field in a "reflection-like" way?
One possible workaround I'm thinking of would be to retrieve and then invoke the field's getter method using reflection, but I'm wondering if there's a more direct solution. This workaround, if it actually works, would require the object to have a getter method for all persistent fields -- a requirement that should typically be followed from an OO-design point of view but also forces more work onto the user of the framework.
I'm open to any ideas.
A good solution is to access the fields using setter/getters rather than using Field class. (I believe this is more than a workaround)
On the other hand, if you want to go with the direct field accessing approach. As far as I see there is no easy way to intercept field accesses. Please check the answers to this question. Altough the question is related with intercepting field modification rather than reading
the field, it may provide some insights and direction.

Is there ever a case for 'new' when using dependency injection?

Does dependency injection mean that you don't ever need the 'new' keyword? Or is it reasonable to directly create simple leaf classes such as collections?
In the example below I inject the comparator, query and dao, but the SortedSet is directly instantiated:
public Iterable<Employee> getRecentHires()
{
SortedSet<Employee> entries = new TreeSet<Employee>(comparator);
entries.addAll(employeeDao.findAll(query));
return entries;
}
Just because Dependency Injection is a useful pattern doesn't mean that we use it for everything. Even when using DI, there will often be a need for new. Don't delete new just yet.
One way I typically decide whether or not to use dependency injection is whether or not I need to mock or stub out the collaborating class when writing a unit test for the class under test. For instance, in your example you (correctly) are injecting the DAO because if you write a unit test for your class, you probably don't want any data to actually be written to the database. Or perhaps a collaborating class writes files to the filesystem or is dependent on an external resource. Or the behavior is unpredictable or difficult to account for in a unit test. In those cases it's best to inject those dependencies.
For collaborating classes like TreeSet, I normally would not inject those because there is usually no need to mock out simple classes like these.
One final note: when a field cannot be injected for whatever reason, but I still would like to mock it out in a test, I have found the Junit-addons PrivateAccessor class helpful to be able to switch the class's private field to a mock object created by EasyMock (or jMock or whatever other mocking framework you prefer).
There is nothing wrong with using new like how it's shown in your code snippet.
Consider the case of wanting to append String snippets. Why would you want to ask the injector for a StringBuilder ?
In another situation that I've faced, I needed to have a thread running in accordance to the lifecycle of my container. In that case, I had to do a new Thread() because my Injector was created after the callback method for container startup was called. And once the injector was ready, I hand injected some managed classes into my Thread subclass.
Yes, of course.
Dependency injection is meant for situations where there could be several possible instantiation targets of which the client may not be aware (or capable of making a choice) of compile time.
However, there are enough situations where you do know exactly what you want to instantiate, so there is no need for DI.
This is just like invoking functions in object-oriented langauges: just because you can use dynamic binding, doesn't mean that you can't use good old static dispatching (e.g., when you split your method into several private operations).
My thinking is that DI is awesome and great to wire layers and also pieces of your code that needs sto be flexible to potential change. Sure we can say everything can potentially need changing, but we all know in practice some stuff just wont be touched.
So when DI is overkill I use 'new' and just let it roll.
Ex: for me wiring a Model to the View to the Controller layer.. it's always done via DI. Any Algorithms my apps uses, DI and also any pluggable reflective code, DI. Database layer.. DI but pretty much any other object being used in my system is handled with a common 'new'.
hope this helps.
It is true that in today, framework-driven environment you instantiate objects less and less. For example, Servlets are instantiated by servlet container, beans in Spring instantiated with Spring etc.
Still, when using persistence layer, you will instantiate your persisted objects before they have been persisted. When using Hibernate, for example you will call new on your persisted object before calling save on your HibernateTemplate.

Categories

Resources