Does assignment precede logical operator?

I have encountered a weird situation while I’m writing a piece of code in Ruby. Here is the sample code extracting the essence of the problem I have faced. First, I tried to get the matching result with a line of code as follows.

p1 = /hello/
p2 = /world/

s = "hello, world"

if m1 = s.match(p1) || m2 = s.match(p2)
    puts "m1=#{m1}"
    puts "m2=#{m2}"
end
`"

It shows:

`"
m1=hello
m2=
`"

Oops, I forgot that the logical operator `||` does the short-circuit evaluation. It makes `m2` nil. What I wanted to do was checking both regular expressions are matching with the given string. Here is the correct one.

```ruby
if m1 = s.match(p1) && m2 = s.match(p2)
    puts "m1=#{m1}"
    puts "m2=#{m2}"
end

But it shows:

m1=world
m2=world

Hmm, the result was unexpected. Why is m1 assigned by the outcome of p2 pattern? I expected that the result of the matching of p1 pattern is assigned to m1 and so forth for m2. Is the precedence of the operators correctly working?

According to the Ruby operator precedence, the logical operator && precedes the assignment operator =. Therefore, the evaluation order of the previous code should be same as:

if (m1 = s.match(p1)) && (m2 = s.match(p2))
    puts "m1=#{m1}"
    puts "m2=#{m2}"
end

Obviously, its outcome is expected.

m1=hello
m2=world

In reality, the evaluation looks like:

if m1 = (s.match(p1) && m2 = s.match(p2))
    puts "m1=#{m1}"
    puts "m2=#{m2}"
end

The logical operator follows the assignment to m2.

Since the result seems weird and I’m still not sure the mechanism behind this behavior, I posted one question in StackOverflow

I would very much appreciate it if you could find the answer to this problem. Thanks!

Reference

When to use var in Java 10

Java 10 officially introduced the var keyword to declare the local variable without typing the type information. Java developers have needed to keep typing the class name explicitly for a long time.

var keyword allows us to declare the local variable without type information supported by the power of type inference of Java compiler. We can simplify the following code.

String str = "Hello, Java!"

like this

var str = "Hello, Java!"

But is it beneficial for practical use? Does it make the code better from the viewpoint of the readability and maintainability?

I have found an interesting discussion in the Presto community about the var usage. Let me summarize the point here.

Pros

  • Speeding the type typing
    • We do not need to write the code as follows anymore.
      AnOverlyLengthyClassName instance = new AnOverlyLengthyClassName();
      
  • Since it’s just an implicit typing, we already use it in the lambda expression.
  • We can avoid the trouble caused by forgetting the L in the long literal.
  • It can have a use when we want to simplify the expression.
    abc = doSomething(somethingElse());
    // ↓ Extracting variables
    List<Map<SomeLongNameHere, List<BlahBlahBlah>>> foo = somethingElse();
    abc = doSomething(foo);
    
  • It encourages developers to use a more descriptive variable name like Kotlin, Scala.

Cons

  • It makes the readability worse by imposing the burden to infer the type by ourselves.
  • The primary purpose of the code is readability, not the speed of typing.
  • Even if we use the var declaration, we can save only a few characters in most cases.
  • Although we can check the actual type by jumping the code with IDE, we cannot do that in GitHub.

Overall, the Presto community does not prefer using the var for now. That’s pretty reasonable. From my experience, the var usage did not improve the readability even though it could worsen it. Thanks to the power of IDE (e.g. IntelliJ IDEA), it would not be much trouble to type lengthy class name in Java anymore.

Therefore, we may need to be careful to use the var declaration in general. If we are sure to simplify the expression by eliminating the tiring generic type declaration (See 4th item in Pros), there might be room to use it.

I am also interested in how the other Java community treats the var usage in their project.

Reference

ALB Listener Rule with Terraform

Terraform is one of the heavily-used infrastructure tool in my daily work recently. It allows us to write the wireframe of the cloud infrastructure we use by simple configuration language called HCL. Thanks to that, we can safely modify the underlying infrastructure and quickly track the history of the change. Therefore, I’d like to collect some knowledge about the usage of Terraform based on the actual use cases.

Today, I’m going to show you how to construct the application load balancer in AWS with Terraform. That is what I did to prepare the load balancer running in front of our service.

Create ALB

First, we need to create the ALB itself. aws_lb resource will form the ALB as follows.

locals {
  this_alb_name = "myalb"
  redirect_to   = "redirect.to"
}

resource "aws_lb" "myalb" {
  name               = "${local.this_alb_name}"
  internal           = false
  load_balancer_type = "application"
  security_groups    = ["${aws_security_group.lb_sg.id}"]
  subnets            = ["${aws_subnet.public.*.id}"]

  access_logs {
    bucket  = "${aws_s3_bucket.lb_logs.bucket}"
    prefix  = "${local.this_alb_name}"
    enabled = true
  }
}

Create Listener

Next, we can attach a listener to the ALB we have created. It is necessary to get the ARN of the previous ALB for aws_lb_listener resource. Let’s use the data source for retrieving the ARN this time.

data "aws_lb" "myalb" {
  name = "${local.this_alb_name}"
}

resource "aws_lb_listener" "mylistener" {
  load_balancer_arn = "${data.aws_lb.myalb.arn}"
  port              = "80"
  protocol          = "HTTP"

  default_action {
    type = "redirect"

    redirect {
      host        = "${local.redirect_to}"
      port        = "80"
      protocol    = "HTTP"
      status_code = "HTTP_301"
    }
  }
}

Note that this listener has a default action. This action returns a 301 response with the redirection to the specific location by local.redirect_to. If no other actions are matched, the default action will be taken.

Add Listener Rule

Lastly, you can add your custom rules as you like with aws_lb_listener_rule. We can get the ARN of the listener without using the data source if the listener is created in the same Terraform configuration.

resource "aws_lb_listener_rule" "redirect_to_cdp_bi" {
  listener_arn = "${aws_lb_listener.mylistener.arn}"
  priority     = 100

  action {
    type             = "forward"
    target_group_arn = "${local.this_tg.arn}"
  }

  condition {
    path_pattern {
      values = ["/forward_to/*"]
    }
  }
}

The final diagram can look like this.

ALB Listener Rules

All requests matching with the path /forward_to/* are routed to the target group this_tg. The others go to the host https://redirect.to.

The best thing about using Terraform is that we can do that in a reproducible manner. Once the Terraform configuration is written, we can get the same resource by just applying it.

Reference

Remove Msgstars from iPhone Calendar

These days, I have started receiving a new type of spam on my iPhone calendar. I have found several unrecognized schedules on my calendar. Moreover, the number of schedules is increasing day by day.

According to this article, that is called Msgstars. Unless we click the link attached in the schedule, it’s harmless. Even it’s possible to disable the notification altogether. It seems not so noisy at first glance.

But it’s too annoying to ignore it because my calendar was filled up with this spam schedules. My original schedules are concealed completely. How can we remove the existing spam schedules from my calendar?

Delete the Calendar Subscription

The reason why we see the new schedules continuously is the subscription of the external calendar. Somehow we may subscribe to the calendar accidentally. The deletion of the subscribed calendars will resolve the problem for sure. You can find the configuration to remove the calendar by typing password in the search window.

Setting to remove calendar

Password & Accounts will provide the list of all subscribed calendars. You can remove them one by one. The schedules from Msgstars immediately disappear.

I hope this article is helpful for your case too!

How to inject Jersey Resource in Dropwizard with Dagger

Dependency Inject (DI) is one of the most notable practices to create reliable and high-quality software. This effort enables us to keep the extensibility without losing readability and testability. You may have encountered a situation where you would want to replace any objects in the software flexibly like me. Many frameworks or libraries are allowing us to make use of the dependency injection in our software project. In my case, I would like to use Dagger in our web application using Dropwizard. But I was ignorant of what Dagger was and how to use it in our Dropwizard project. Hence, this article is for writing down the process to get started with Dagger in your web application using Dropwizard.

What is Dagger

First of all, what is Dagger? Dagger is a Java-based dependency injection library originally invented by Square. For now, it’s mainly maintained by Google as an open-source project.

Dagger

You might hear about Guice before, which is also maintained by Google. It has a more extended history than Dagger. Despite that, Dagger has a more significant number of stars in its GitHub repository. Why is Dagger more popular than Guice? There are several reasons from my perspective.

  • Dagger is compiling time DI library, while Guice’s injection happens at runtime
  • Guice often causes challenging error to solve relating to its reflection usage
  • Dagger provides more simple APIs to use
  • Dagger has notable use cases due to the adoption in the Android development

Therefore, I try to use Dagger in our web application this time.

How to integrate Dagger in Dropwizard project

What I’m going to do is integrate Dagger in a Dropwizard project to inject Jersey resources flexibly. Before going deeper into this goal, we need to be familiar with some Dagger terminologies.

  • Module: Has associations between the interface and actual injected objects.
  • Component: Constructs a whole graph resolving the dependencies of injected objects

Unlike Guice, what I’ve found is that we needed to construct one more class called Component. The component is a sort of highest level class managing all objects injected by Dagger. Therefore, all objects should be injected from the component.

In our case, we will create WebResourceModule for the module and WebappComponent for the component.

The client of the injected class can use the javax.inject.Inject annotation. Constructor injection or field injection is recommended in Dagger.

@Path("/users")
class UserResource {
  @Inject
  public UserResource(UserConfig userConfig) {
    // Used for the user resource specific configuration
    this.config = config;
  }
}

We are going to inject UserConfig as we like by using Dagger.

The dagger library can be imported with the following code in build.gradle.

dependencies {
  implementation 'com.google.dagger:dagger:2.28.1'
  annotationProcessor 'com.google.dagger:dagger-compiler:2.28.1'
}

Module and Component

First, we define the module to illustrate how to construct the target UserConfig class.

import dagger.Module;
import dagger.Provides;

@Module
public class WebResourceModule {
    private final UserConfig;

    public WebResourceModule(Configuration configuration) {
        this.userConfig = configuration.getUserConfig();
    }

    @Provides
    UserConfig provideUserConfig() {
      return this.userConfig;
    }
}

@Provides annotation lets the compiler know how to construct the class at the compile time. Therefore, all classes in the application use the UserConfig constructed by the method, provideUserConfig. Next, we can create a module class for building the whole dependency graph.

import dagger.Component;

@Component(modules = {WebResourceModule.class})
public interface WebappComponent {
    UserResource getUserResource();
}

The argument of @Component annotation specifies the modules knowing how to construct the injected objects. All WebappComponent interface needs to provide is the method to build the object we finally want to get. In this case, the web resource which will be registered into the Dropwizard later. That’s all that we must do with Dagger.

But here comes one question. Who creates the instance of WebappComponent? The answer is Dagger. Dagger generates a class prefixed by Dagger. In this case, DaggerWebappComponent will be created to construct the UserResource from it. Additionally, it provides us a way to bind a module at runtime.

Dropwizard Application

In the Dropwizard, we will get the component class to get the UserResource and register it as a jersey resource.

public class Application extends io.dropwizard.Application<Configuration> {

  public static void main(String[] args) throws Exception {
    new Application().run(args);
  }

  @Override
  public void run(@NotNull Configuration configuration, Environment environment) {
    // Bind the module to inject the user configuration
    // All objects dependent on the UserConfig can change the behavior without rewriting them.
    WebappComponent component = DaggerWebappComponent.builder()
                        .webResourceModule(
                                new WebResourceModule(configuration)
                        .build();

    environment.jersey().register(component.getUserResource();
  }
}

DaggerWebappComponent has a builder interface to bind the module at runtime. By changing the module here, we can change the behavior. For the test purpose, we can write a component like this.

WebappComponent testComponent = DaggerWebappComponent.builder()
                    .webResourceModule(
                            new TestWebResourceModule(configuration)
                    .build();

UserResource testUserResource = testComponent.getUserResource();

It obviously helps us write more testable code.

Wrap Up

As we saw now, using a Dagger looks easy. Dagger enabled me to write more maintainable code without learning many things. Its simple APIs significantly reduce the trouble and burden to employ the DI framework in our software projects. Let’s try to use Dagger in your Dropwizard project as well!