Welcome to my blog. Here I write about technology, software development practice/processes and other stuff.
Notice
╠ This is my personal blog and my posts here have nothing to do with my employers or any other association I may have. It is my personal blog for my personal experience, ideas and notes. ╣
Monday, April 27, 2020
Saturday, January 18, 2020
Exception flow control could be expensive.
As a developer sometimes we use exceptions as flow control. It could be expensive. I am going to show you how a simple change could help you to save a lot of time by simply not accepting exception as your code flow controller.
In this example, I will throw an exception if required data is not available during execution I will throw an IllegalArgumentException and in another case, I simply return a value using which call is going to take the decision based on the value then we will see how different it will be.
In this example, I will throw an exception if required data is not available during execution I will throw an IllegalArgumentException and in another case, I simply return a value using which call is going to take the decision based on the value then we will see how different it will be.
Code Output
In case of exception, it will take around a minute for execution and in another case it is insignificant. Both methods are invoked one million times to determine the impact.
I request you to think again if you are using exception as your flow controller in a code which will be invoked many times.
Code Output |
Then what if I have to address an exception scenario
If I need to address an exception scenario then for optimization I could pre-allocate the exception object so that I can use them multiple times.Code Output
Let me know your thoughts about it.
Monday, July 15, 2019
JDK 12 switch statement... No expression
In Java language, there are lots of improvement and new paradigm changes like lambda expression, streams, etc.
In JDK 12 you can use switch statement as an expression instead of a statement. Okay, what is the difference?
Let's write code a code to understand the difference.
In the above code, you can clearly see these switch statement with fall through structure and irritating 😠break statement. Expressing switch as a statement is error-prone, repetitive and roundabout.
In JDK 12 switch expression will come in non-fall through it means no break statement anymore.
So what does switch expression means?
Let's rewrite the above come in JDK 12 using the latest switch expression and see how many lines of code we could reduce it and how readable our code it will be.
In JDK 12 you can use switch statement as an expression instead of a statement. Okay, what is the difference?
Let's write code a code to understand the difference.
In the above code, you can clearly see these switch statement with fall through structure and irritating 😠break statement. Expressing switch as a statement is error-prone, repetitive and roundabout.
In JDK 12 switch expression will come in non-fall through it means no break statement anymore.
So what does switch expression means?
static void howMany(int k) {
System.out.println(
switch (k) {
case 1 -> "one"
case 2 -> "two"
default -> "many"
}
);
}
Let's rewrite the above come in JDK 12 using the latest switch expression and see how many lines of code we could reduce it and how readable our code it will be.
Keep it simple.
Oh ! please do remember that as this language enhancement not present in JDK 12 while compiling and running the JDK 12 code you need to add few arguments.
Please do share this with others and ask/discuss questions if you have.
Happy learning!
Oh ! please do remember that as this language enhancement not present in JDK 12 while compiling and running the JDK 12 code you need to add few arguments.
javac --enable-preview -source 12 -Xlint:preview Jdk12Switch.java
java --enable-preview -source 12 Jdk12Switch
Please do share this with others and ask/discuss questions if you have.
Happy learning!
Wednesday, January 16, 2019
How to support multiple types of multi-tenancy database?
In this proposed solution, we are going to support multiple tenants with different types of multi-tenancy database models in one application.
To achieve this we need to have tenant identifier columns in all tables, and all query should have the association of tenant identifier as criteria.
We will be adding another column to have database identifier along with tenant identifier.
In this example, we have five tenants but T1 & T2 tenants have their own database implementation named D1 & D2 respectively, and T3, T4 & T5 tenant has the common database named ‘CD’/Common Database.
We going to have three databases named D1, D2 and CD, three data sources for these three databases. In application, we going to have the map of tenant identifier and the database identifier. In the persistent layer of the application, we are going to retrieve the tenant identifier from the tenant context and get the data source with respect to it. We will be populating the tenant identifier in each persistence call and all the update, delete and retrieve call will have tenant identifier as criteria along with other criteria.
By this way, we can support multiple multiple types of multitenancy database implementation models.
Business Impact
We can efficiently able to manage different categories of clients like we can group up small clients into a common database. As a result, these small clients will be benefited from shared storage cost and low database maintenance cost. On the other side, big clients could have their own database and it will make sure they can scale well in the future.
Looking forward to your questions & suggestions.
Friday, January 26, 2018
Java Unit Testing of POJO class
I have created a tool to help the developer to do test coverage of their POJO Bean classes.
Java POJO classes are supposed to be tested while testing any business logic but in the real world, it does not happen. So I created this framework which will help developers while showing coverage to reviewers & auditors, and also help to discover silly mistakes which happen mostly during field name refactoring.
I personally recommend developers that try to get these POJO tested while testing business logic if you somehow could not do it then this tool comes second.
This is a very simple to use the framework with lots of features which developers required in the real world.
Here is Wiki to learn this framework.
I am open to your feedback, please try it and let me know your feedback.
Java POJO classes are supposed to be tested while testing any business logic but in the real world, it does not happen. So I created this framework which will help developers while showing coverage to reviewers & auditors, and also help to discover silly mistakes which happen mostly during field name refactoring.
I personally recommend developers that try to get these POJO tested while testing business logic if you somehow could not do it then this tool comes second.
This is a very simple to use the framework with lots of features which developers required in the real world.
Here is Wiki to learn this framework.
I am open to your feedback, please try it and let me know your feedback.
Monday, December 25, 2017
Spring Dependency Injection
Overview
As a developer, we trend to create modular and loosely coupled applications. To accomplish modularity developer divided the application into multiple classes and each class depends on one or more other classes to accomplish desired functionality in an application. Spring is the most popular dependency injection framework for Java.
Let take an example to understand the dependency. A person has a name. It also means 'Person' has a dependency on 'Name'.
public class Person {
private Name personName;
}
To accomplish independence from other dependent classes Spring framework provides Inversion of Control (IoC) which is basically inverting the dependency injection flow. In IoC, Spring container inject those dependencies when it creates the beans. We will now see how to define this bean and inject the dependent object in it.
Type of dependency injection
Primarily there are two types of dependency injection
1. Constructor-based dependency injection
2. Setter-based dependency injection
Constructor-based dependency injection
Constructor-based dependency injection is accomplished by constructor arguments where each argument represents the dependency.
package example;
public class Person {
private Name personName;
// Dependency injected via argument by Spring
public Person(Name personName){
this.personName = personName;
}
}
Spring Bean Definition
<bean id="personName" class="example.Name" />
<bean id="constructorExample" class="example.Person">
<constructor-arg type="example.Name" ref="personName" />
</bean>
Constructor based injection using static factory method
package example;
public class PersonFactory {
public static Person createPerson(Name personName){
return new Person(personName);
}
}
Spring Bean Definition
<bean id="personName" class="example.Name" />
<bean id="person" class="example.PersonFactory"
factory-method="createPerson">
<constructor-arg ref="personName" />
</bean>
Setter-Based Dependency injection
Setter-based dependency injection is accomplished by calling the Java bean write method (i.e. setter) on object which is created using no-argument constructor or no-argument static factory method.
public class Person {
private Name personName;
// Setter method so that Spring can inject the dependency
public void setPersonName(Name personName){
this.personName = personName;
}
}
Spring Bean Definition
<bean id="personName" class="example.Name" />
<bean id="setterExample" class="example.Person">
<property name="personName" ref="personName" />
</bean>
Setter based injection using static factory method
package example;
public class Person {
private Name personName;
private Person(){
}
// Factory method
public static Person createPerson(){
return new Person();
}
private void setPerson(Name personName){
this.personName = personName;
}
}
Spring Bean Definition
<bean id="personName" class="example.Name" />
<bean id="person" class="example.Person"
factory-method="createPerson">
<property name="personName" ref="personName" />
</bean>
So, where to use constructor-based and when to use setter-based ?
Constructor based injection is recommended when we want dependencies to be injected during creation of object. In other words if dependency is absolutely mandatory then we will use constructor, and if dependency is option then we could use setter based injection.
Now what if during first phase of development, dependency was optional so we used setter based injection but now due to change in requirement dependency is mandatory. To deal with this kind of scenario Spring provide an annotation @Required which actually enforce that setter based dependency must be populated during bean creation otherwise it will raise BeanInitializationException exception.
public class Person {
private Name personName;
// Setter method so that Spring can inject the dependency
@Required
public void setPersonName(Name personName){
this.personName = personName;
}
}
Spring Bean Definition
<bean id="personName" class="example.Name" />
<bean id="setterExample" class="example.Person">
<!-- Not injecting setter based dependency -->
<!--property name="personName" ref="personName" / -->
</bean>
Exception message will be printed as "Property 'personName' is required for bean 'setterExample'".
So technically developers need to take decision based on their business requirement which type need to use.
Sunday, February 5, 2017
Spying on JavaScript Method using Jasmine [Part - 2]
Basic Introduction of JavaScript Testing Framework Jasmine
The basic of Jasmine is already discussed in my earlier blog. To read it please click here.
Spying with Jasmine
One of the basic reason of spying is to do unit testing of method in isolation. So we mock the method to bypass other dependencies.
Let's see what Jasmine offer us.
Spy on a method
spyOn(object, methodName)
it can only exist inside the describe
or it
block. In another words it can only be define inside spec or suit, and it will be removed once spec get existed. spyOn(obj , 'setName');
When you want to invoke the actual method but call will be tracked.
spyOn(obj , 'setName').and.callThrough();
When you call
and.callThrough
, the spy acts as a proxy, calling the real function, but passing through a spy object allowing you to add tests like expectation.
When you want to remove the effect of spyOn(obj , 'setName').and.callThrough()
spyOn(obj , 'setName').and.stub()
removes the effect ofspyOn(obj , 'setName').and.callThrough()
on a spy.
When you want to return a specific value on all calls.
spyOn(obj, "getName").and.returnValue('Andy');
When you want to invoke a custom function.
spyOn(obj, "getName").and.callFake(function(arguments, here) {
return 'Andy';
});
When you want to throw specific error.
spyOn(obj, "setName").and.throwError("myError");
Every call to a spy is tracked and exposed on the calls
property.
Calls | Purpose |
---|---|
any() |
returns false if the spy has not been called at all, and then true once at least one call happens. expect(obj.setName.calls.any()).toEqual('Andy'); |
count() |
returns the number of times the spy was called. expect(obj.setName.calls.count()).toEqual(2); |
argsFor(index) |
returns the arguments passed to call number index .
obj.setName('Andy');
expect(obj.setName.calls.argsFor(0)).toEqual(["Andy"]);
|
allArgs() |
returns the arguments to all calls.
obj.setName('Andy'); obj.setName('Anindya','Banerjee'); expect(obj.setName.calls.allArgs()).toEqual([["Andy"],["Anindya","Banerjee"]]); |
all() |
returns the context (the this ) and arguments passed all calls.
obj.setName('Andy'); expect(obj.setName.calls.all()).toEqual({object: obj, args: ["Andy"]}); |
mostRecent() |
returns the context (the this ) and arguments for the most recent call.
obj.setName('Andy'); obj.setName('Anindya','Banerjee'); expect(obj.setName.calls.mostRecent()).toEqual({object: obj, args:"Anindya","Banerjee"}); |
first() |
returns the context (the this ) and arguments for the first call.
obj.setName('Andy'); obj.setName('Anindya','Banerjee'); expect(obj.setName.calls.first()).toEqual({object: obj, args:"Andy"}); |
reset()
clears all tracking for a spy.
obj.setName.calls.reset();
There is a property named
object
which actually return the this
object when the spy was call. This can be used with all
/mostReset
/first
.Please note here these methods are return an array of json object and one of key is
object
. Please refer to the above table.Here is an example.
obj.setName('Andy');
obj.setName('Anindya','Banerjee');
expect(obj.setName.calls.all().object).toEqual(obj);
expect(obj.setName.calls.mostRecent().object).toEqual(obj);
expect(obj.setName.calls.first().object).toEqual(obj);
There are three matchers
toHaveBeenCalled
, toHaveBeenCalledWith
and toHaveBeenCalledTimes.
toHaveBeenCalled
return true
if the spy was called.
expect(obj.setName).toHaveBeenCalled();
toHaveBeenCalledWith
return true
if the argument list matches any of the recorded calls to the spy.
expect(obj.setName).toHaveBeenCalledWith('Andy');
toHaveBeenCalledTimes
return true
if the spy was called the specified number of times.
expect(obj.setName).toHaveBeenCalledTimes(2);
What we will do if we didn't have a function to spy on ?
Jasmine provide functions to deal with this kind of situations.
Function | Purpose |
---|---|
jasmine.createSpy |
create a spy function which doesn't exist.var dummyFunction = jasmine.createSpy('dummy function');
$('#mybutton').click(dummyFunction);
|
jasmine.createSpyObj |
create multiple spy function which doesn't exist.
// Suppose you got a Json object from back-end
// Person is a spy object with getName and getAge methods and an id property
var person = jasmine.createSpyObj("person", ["getName", "getAge"]);
person.id = 1234;
|
jasmine.any |
returns true if the constructor matches the constructor of the actual value.expect({}).toEqual(jasmine.any(Object)); expect(12).toEqual(jasmine.any(Number)); |
jasmine.anything |
returns true if the actual value is not null or undefined .
expect({}).toEqual(jasmine.anything());
|
jasmine.objectContaining
|
when an expectation only cares about certain key/value pairs in the actual.
var person = {
firstName : "Anindya",
lastName : "Banerjee",
aliasName : "Andy"
};
expect(person).toEqual(jasmine.objectContaining({ aliasName: "Andy" }));
|
jasmine.arrayContaining
|
when an expectation only cares about some of the values in an array.
var num = [1, 2, 3, 4];
expect(num).toEqual(jasmine.arrayContaining([3, 1]));
expect(num).not.toEqual(jasmine.arrayContaining([6]));
|
jasmine.stringMatching
|
When match a portion of a string in a spy expectation.
expect({names: 'AndyAnindya'}).toEqual({names: jasmine.stringMatching('Andy')});
|
Labels:
any,
anything,
BDD,
Jasmine,
objectContaining,
spyOn,
TDD,
toHaveBeenCalledTimes
Subscribe to:
Posts (Atom)