What is the use case of skipping method execution in around advice? - spring

I understood what #Around Advice does, and when we need to share Before and after state then we can use it, and we call also skip method execution. My question is why Spring given us this power to skip method execution and what is the use case of skipping method?

Side effects as Nándor said are one thing. Maybe you even want to replace the return value altogether, possibly because there is a bug in a class you do not have the source code of or for other reasons:
Buggy Java class:
package de.scrum_master.app;
public class Earth {
public String getShape() {
return "disc";
}
}
Driver application:
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
System.out.println("The Earth is a " + new Earth().getShape() + ".");
}
}
Console log:
The Earth is a disc.
Bugfix aspect:
package de.scrum_master.aspect;
import de.scrum_master.app.Earth;
public aspect BugfixAspect {
String around() : execution(* Earth.getShape()) {
return "sphere";
}
}
Console log with aspect applied:
The Earth is a sphere.

Method calls usually have side effects. Whenever you decide in your aspect that those side effects are undesirable for whatever reason, it's a valid use case to skip executing the original execution. This includes use cases for caching for example, when the side effects are not in terms of data, but execution time.

Related

C# Attribute or Code Inspection Comment to Encourage or Discourage Call to Base Method from Virtual Method Override

I'm working on a C# project in Unity with Rider.
I sometimes see a base class with an empty virtual method, and then a derived class that overrides that method. The method override has an explicit call to base.MethodName() even though the base method is empty.
public class A
{
public virtual void Method1() { }
public virtual void Method2()
{
// Important logic performed here!
}
}
public class B : A
{
public override void Method1()
{
base.Method();
// Do something else ...
}
public override void Method2()
{
// Do something here ...
}
}
When looking at the method in Rider's IL Viewer, the call to the base method is included, even though the method is empty.
Are there any method attributes or code inspection comments in C# or Rider that could:
Generate a compiler or code inspection warning when calling a base method that is empty.
Generate a compiler or code inspection warning when not calling a base method that is not empty.
For example:
public class A
{
[OmitCallFromOverride]
public virtual void Method1() { }
[RequireCallFromOverride]
public virtual void Method2()
{
// Important logic performed here!
}
}
I can imagine a scenario where multiple derived classes override a method and one or more mistakenly failed to call the base method, which might result in unexpected behavior. Or situations where there are unnecessary calls to an empty base method, which may be wasteful, but unlikely to break anything.
While I'm primarily inquiring about whether such attributes or code inspection comments exist, I am also curious to know of how people might handle these situations, such as simply always calling the base method from an override, keeping important logic out of base virtual methods, or using some other method of communicating whether a base method call is unnecessary or required.
Generate a compiler or code inspection warning when calling a base
method that is empty.
In c#, as far as I know, there is no warning for an empty method. So, I think there is no warning when calling a base method that is empty.
But you are free to write one for you: Write your first analyzer and code fix
Generate a compiler or code inspection warning when not calling a base
method that is not empty.
Not in C#, and I think is not a good idea to force a derived class to call a base method. I can understand that in your scenario, it would be great if all your derived classes method call always the base method, but it will be a very uncommon case. And generally when we need tricky (not intuitive) rules, that means our solution is not very clear, or it will be error-prone.
keeping important logic out of base virtual methods
If you need A.Method1 to be called, maybe let it as a virtual method is not a good idea. You have a virtual method when you want to give to your derived classes the opportunity to use it OR to overwrite it with a more adapted version.
I propose you a solution that maybe you can adapt to your scenario.
abstract class A
{
public abstract void Method1();
public virtual void Method2() { }
public void MustBeCalled()
{
// Here you can put the logic you had in Method1, you need to execute this code, so this method can't be overwrited.
}
public void TemplateMethod()
{
Method1();
MustBeCalled();
// Do something else ...
}
}

Something missing using micronaut filter

I am attempting to implement a filter in a micronaut microservice, using the example code documented in Section 6.18 of the documentation:
https://docs.micronaut.io/latest/guide/index.html#filters
I have a HelloWord service that is essentially the same as the service provided on the documentation, with a controller that goes to "/hello" (as documented). I am also using the same TraceService and trace filter that is provided in Section 6.18. I am compiling and running the server without problems.
Unfortunately, the filter is not being engaged when I test the microservice.
I am pretty sure that something is missing in my code, but as I said I am using the same code that is in the example:
TraceService Class
import io.micronaut.http.HttpRequest;
import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;
import org.slf4j.*;
import javax.inject.Singleton;
#Singleton
public class TraceService {
private static final Logger LOG = LoggerFactory.getLogger(TraceService.class);
Flowable<Boolean> trace(HttpRequest<?> request) {
System.out.println("TRACE ENGAGED!");
return Flowable.fromCallable(() -> {
if (LOG.isDebugEnabled()) {
LOG.debug("Tracing request: " + request.getUri());
}
// trace logic here, potentially performing I/O
return true;
}).subscribeOn(Schedulers.io());
}
}
Trace Filter
import io.micronaut.http.*;
import io.micronaut.http.annotation.Filter;
import io.micronaut.http.filter.*;
import org.reactivestreams.Publisher;
#Filter("/hello/**")
public class TraceFilter implements HttpServerFilter {
private final TraceService traceService;
public TraceFilter(TraceService traceService) {
System.out.println("Filter created!");
this.traceService = traceService;
}
#Override
public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
System.out.println("Filter engaged!");
return traceService.trace(request)
.switchMap(aBoolean -> chain.proceed(request))
.doOnNext(res -> res.getHeaders().add("X-Trace-Enabled", "true")
);
}
}
The Controller
import io.micronaut.http.annotation.*;
#Controller("/hello")
public class HelloController {
#Get("/")
public String index() {
return "Hello World";
}
}
Note that the controller uses code from Section 2.2 of the documentation:
https://docs.micronaut.io/latest/guide/index.html#creatingServer
I did a number of things to try and see what was happening with the filter, including putting little printouts in strategic parts of the Service and the filter. These printouts are not printing out, which tells me that the filter is not being created or used by Micronaut.
Clearly I am missing somethning. I suspect that there is something I need to do in order to get the system to engage the filter. Unfortunately the documentation just tells how to make the filter, not how to use it in the microservice. Furthermore, there don't appear to be any complete code examples that tell how to make the request system utilize the filter (maybe there is an annotation I need to add to the controller???).
Could someone tell me what I am missing? How do I get the filter to work? At the very least, could someone provide a complete example of how to create the filter and use it in an actual microservice?
Problem solved.
It actually helps a great deal if one puts the filter and service files in the right place. It was late when I made the files and I put them in the test area, not the development area. Once placed in the right place, the filter was properly injected into the microservice.
Sorry for the waste of space here, folks. Is there any way a poster can delete an embarrassing post?

Inheriting default methods with the same name in the class without any compilation error

How a class can implement two interfaces with the same default method in Java 8.
I was not able to get the concept behind the same default method from different interfaces getting inherited in the sub class.Please explain the issue.
interface House {
default String getAddress() {
return "101 Main Str";
}
}
interface Bungalow extends House {
default String getAddress() {
return "101 Smart Str";
}
}
class MyHouse implements Bungalow, House {
}
public class TestClass {
public static void main(String[] args) {
House ci = new MyHouse(); //1
System.out.println(ci.getAddress()); //2
}
}
In the above code default method getAddress() in interface House is present.another method with the same name is declared as default in the extending interface Bungalow
How class MyHouse can implement both the interfaces without any compilation error(because it doesn't know which method has the preference in that case implementing should fail.)
If i call new MyHouse().getAddress(); gives compile error but it should give compilation error even without method calling from MyHouse class.
It seems that the answer is here, where there is a different example, but sort of makes sense and is really close to yours.
Ask me the exact same thing in 1/2 a year and I'll say it will fail at compile time and point me to this answer, so that I could read the JLS again. I guess this is how they decided to implement it. Without thinking too much, I, personally (may be wrong) think that this is at least counter intuitive...

Wicket Decorator to Listener when upgrade from 1.5.x to 6.x

I have been requested to upgrade the wicket version from 1.5.9 to 6.14.0 in a web-app.
I have found upgrading the (behavior) decorators to listeners very problematic.
https://cwiki.apache.org/confluence/display/WICKET/Wicket+Ajax#WicketAjax-o.a.w.ajax.IAjaxCallDecoratorisreplacedwitho.a.w.ajax.attributes.IAjaxCallListener
o.a.w.ajax.IAjaxCallDecorator is replaced with o.a.w.ajax.attributes.IAjaxCallListener.
I have succeeded in creating a POC where I upgrade the needed parts almost correctly.
In 1.5.9 the element script can be decorated like this (at low level, there is also other changes involved, but it ends to this)
public class MyBehavior extends AjaxFormComponentUpdatingBehavior {
#Override
// (removed in upgrade to 6.14.0)
protected IAjaxCallDecorator getAjaxCallDecorator() {
return new SmallDecorator();
}
private class SmallDecorator extends AjaxCallDecorator {
public SmallDecorator() {}
#Override
public CharSequence decorateScript(Component component, CharSequence script) {
return "alert('decorated onblur');" + script;
}
}
}
In 6.14.0 the same is done like this (as far as I have understood it correctly)
public class OnBlurBehavior extends AjaxFormComponentUpdatingBehavior {
#Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.getAjaxCallListeners().add(new
GenericListenerImpl("alert('Listener onblur')"));
}
private class GenericListenerImpl extends AjaxCallListener {
private String decoratorScript = null;
public GenericListenerImpl(String decoratorScript) {
this.decoratorScript = decoratorScript;
}
#Override
public CharSequence getPrecondition(Component component) {
return this.decoratorScript;
}
}
}
Now this works in basic, but when I want to edit or wrap the "script" like in the 1.5.9 version is done, how can I accomplish that in the 6.14.0 version?
This has proved to me extremely problematic as I haven't used Wicket for a (very) long time and kind of being a noob is specially what comes to the latest version. :)
I was in impression that the "script" part in 1.5.9 contains a single String of element attributes (or something like that) UI developer had added for the element in html. But checking that in detail reveals that the "script" content actually looks something like this:
var wcall=wicketAjaxPost('./?0-1.IBehaviorListener.0-input', wicketSerialize(Wicket.$('input')),function() { }.bind(this),function() { }.bind(this), function() {return Wicket.$('input') != null;}.bind(this));
So the "script" is something generated by the wicket and actually there is no content that could had been set by the (UI) developer and could require modification on the java side.
In general I consider such behavior bad (as in 1.5.9) when given the generated script to be modified and omitting this option alltogether in upgrade to 6.14.0 seems justified... Even that this causes gray hair and extra work to fix the functionality getting broken with the upgrade.
The code examples given above are correct, you just need to figure out what behavior to add (override) in GenericListenerImpl to gain the same functionality as with decorating the script with SmallDecorator.
The API for AjaxCallDecorator appears to be bad as it does not explaing the parameters with the 'decorateScript', thus I was mislead with the issue...
http://wicket.apache.org/apidocs/1.5/org/apache/wicket/ajax/calldecorator/AjaxCallDecorator.html#decorateScript%28org.apache.wicket.Component,%20java.lang.CharSequence%29

Are "passive" objects considered a good design practice?

I find myself very often creating an object that has no public methods and is self-contained. It typically handles events of arguments passed to its constructor in its private methods and does not raise any events or expose any public methods.
I am calling this type of objects "passive" objects - objects that do not have any public methods defined. All interaction occurs inside them in private methods and events of arguments passed in constructor.
Typically it is some utility class, like one that assures that two forms will be sticked together:
public class StickyForm : IDisposable
{
private readonly Form form;
private readonly Form parentForm;
public StickyForm(Form form, Form parentForm)
{
this.form = form;
this.form.StartPosition = FormStartPosition.Manual;
this.parentForm = parentForm;
this.parentForm.LocationChanged += new EventHandler(parent_LocationChanged);
this.parentForm.SizeChanged += new EventHandler(parent_SizeChanged);
SetLocation();
}
void parent_SizeChanged(object sender, EventArgs e)
{
SetLocation();
}
void parent_LocationChanged(object sender, EventArgs e)
{
SetLocation();
}
private void SetLocation()
{
//compute location of form based on parent form
}
public void Dispose()
{
this.parentForm.SizeChanged -= parent_SizeChanged;
this.parentForm.LocationChanged -= parent_LocationChanged;
}
}
But sometimes it is also some kind of controller, providing interaction between two views:
public class BrowseController
{
private IBrowserView view;
private IFolderBrowser folderBrowser;
public BrowseController(IFolderBrowser folderBrowser, IBrowserView view)
{
this.view = view;
this.folderBrowser = folderBrowser;
this.folderBrowser.NodeOpened += folderBrowser_NodeOpened;
}
private void folderBrowser_NodeOpened(object sender, Core.Util.TEventArgs<IPictureList> e)
{
this.Browse(e.Value);
}
public void Browse(IPictureList content)
{
//stripped some code
AddItemsToView(content);
}
private void AddItemsToView(IPictureList browser)
{
//call methods on view
}
}
Are such "passive" objects considered a good design practice?
Is there a better name for this kind of class?
Seems like fine design to me. I'm not sure about the name passive though. Those classes do seem pretty active. They react to events and do stuff. I would think a class is more passive if you have to call methods on it to get it to do stuff, but normally it wouldn't do anything unless poked.
How about the name "controller". "controller" is the more usual name for a class used in a UI that causes interaction between a view and data, and they quite often don't need to have public methods.
I'm sure there's other ideas for names.
I don't see anything wrong with that. If it results in clean, readable code, go for it!
I wouldn't call the objects that react to notifications and update their state completely passive.
One other thought, if the objects simply adjust their state to reflect changes in the outside world without providing much of their own, you may slice their "functionality" and put it into other more active "components". There may be not enough reason for these objects to exist.
If this organization however makes you code structure better, clearer and more maintainable, then use it and don't worry about it.
I think that there's one important criteria to meet with this design: can you test it? The designs you have seem to be testable, but you may have to be careful as I can see this leading to some rather untestable code.
In regards to the name, I think this may be an example of the Mediator pattern.
Conceptually this appears to be an implementation of strategy pattern. Although in this particular case the reasoning is different from strategy pattern', it still yields very readable and nicely granulated code. Go for it.
UPDATE: to make a little clearer what I mean consider two (or more) classes derived from StickyForm
public class VeryStickyForm : StickyForm
{
//some implementation here
//but interface is completely inherited from StickyForm
}
public class SomewhatStickyForm : StickyForm
{
//some implementation here
//but interface is completely inherited from StickyForm
}
And you decide which one to use dynamically depending on run-time state... you implement a strategy.
As I said your solution is conceptually similar to strategy: you select some behavioral aspect of your application that can be well abstracted into policy and move the implementation of the policy into separate class, that does not know about the rest of the application, and your application does not know much about guts of the policy. Even though you do not use it polymorphically, resemblance to strategy is clear.

Resources