Thursday, August 8, 2019

Prototype

Prototype is another creation pattern.

Intent:

 - Intent is to create objects by cloning existing instance
 - Specify the kinds of objects to create using a prototypical instance


Why cloning?

Sometimes, we run into situation where object creation is expensive, specially when it involves network I/O or interacting with database etc. How do we allow object creation, without doing lots of rigorous gymnastics, for objects similar in nature? Prototype design pattern comes handy here. Objects are cloned with some initial setup that requires little or no further changes.

In college, we have all done this, one friend downloads the assignment from college online portal  and its gets distributed using pen-drive. Probably a close example!?  ;)

But, can you give some real world examples?


  •  cloning set of agreements from a archive store, and adding contact details later. (That's the exactly what real state agents do, misspelling you names or id details, and ask you to verify. :P )
  • cloning a job with other instance members - only difference is ID and executionTime.
  • creating test dummies!?
  • Creating a new case/user story, by cloning ServiceNow case, or JIRA or Trello!! :)
I hope you got the point.

A little side story

I came across the term prototype while learning about Spring Bean scopes, one of them is prototype.
It does not however exactly the prototype pattern, since it does not returns a cloned object, but sounds pretty close. :)

Ok, How does it look like? 


Source:Wikipedia


Can I have a look at a Pseudo-code?

You can find it on this wiki page.

Anything else I should know?

  • Yes, you need to aware of your clone implementation. In java, default behavior is shallow copy, field by field copy, where primitives are copied as new values, and members of class types are copied as reference, hence both the cloned object and actual object points to the same objects. So, be aware of this fact, while choosing/writing clone method implantation.   
  • And, also classes needs to implement Cloneable interface and override clone method. Note that Cloneable is a marker interface, so it does not explicitly contains clone method. Read more on official java document here.
  • It may appear to overlap with AbstractFactory pattern, but its a bit different in the sense, it does not require subclassing, rather it relies on an initialization method (eventually relies on clone). 

Please share your story of implementing Prototype in comments. Will be helpful to people learning it for the first time. :)



Wednesday, August 7, 2019

Singleton Pattern

Intent:


Make it impossible to create another instance of class (so, only one instance).  
And, provide a global point of access to it.

How to make a class Singleton?

1) Make the constructor private. Wait, a sec! Private constructor!!?? can we even have a constructor privates? Yes, we can.

2) Then, how do we create a object?

Allowing global access point ...
- We have a static method getInstance() that returns an instance of Singleton class.
 And, use Signleton.getInstance() not Singleton singleton = new Singleton(); singleton.getInstance();
to create an object.


3) How does getInstance finds the object?

- declare a private static member of the same type as of Singleton, private to avoid access from outside the class.
- getIntsance checks of there is already an instance and return that instance, else creates a new instance and stores it in the instance variable so that the same can be returned every-time a new instance is requested for.

That's it!! (There are some other issues in Java, details in other blog.)

Wait, But how does it look like?

Pseudo-code:




Examples:

  • constants
  • configuration
  • cache 
  • datasource


Thursday, July 4, 2019

Java8: What it meant?

According to a recent survey done by Jetbrains, a whopping 83% developers are using Java8 regularly. This shows the impact Java 8 had and is still carrying on to have in Java developers' world. This is particularly due to the way Java8 brought-in a lot of new ways to improve developers experience and eventually cutting-off a lot of criticism like code verbosity, lack of functional programming etc.

Although it can't be said that Java8 has become a functional programming language. However, it brings in those nice things from functional world, and is still not moving away completely the "Java" way of doing things. This has been the trademark of Java - language developers have always been considerate and kind. Enough attention has been given to ensure that the new features are backward compatible. And, the more we go into details, we find that some of them have been very clever and neat indeed.

This is perhaps one reason Java has been so popular. A new release almost never means, you need to throw everything you have been doing and start new.

Some of the important Java 8 features:
  • Lamda Expressions
  • Method Reference
  • Default Methods in Interface
  • Streams
  • Functional Interface (Consumer, Supplier, Function, Predicate )
  • Optional
  • New changes in Reflection API - parameter types and repeatable annotations
  • Date and Time API
If you want to know more you can take a look at Oracle's official website here: Whats new in Java8?

Will try to explore each of these features and more in upcoming blog posts.

Till then, happy coding! :)

Monday, July 1, 2019

What is loose coupling?


When two layers or components or classes (in context of OOP paradigm) interact with each other or uses some other component, they are coupled in certain ways. Also, known as "dependencies".  


The lesser a component know about its dependencies the looser coupled they are.

The information they need to know in order to use them, such as creating a new instance.
One of the biggest advantage is maintenance. The looser coupled code is, a lot easier to maintain.

Some of the ways we can promote loose coupling in Java:

  1. Passing Interfaces instead of concrete classes.
  2. Look for the use of new keyword for creating a new object, and using factory method or Dependency injection.
  3. Creating Rest/Messaging/Event interfaces to interact instead of using direct (like maven) dependencies of Jar files. 



Friday, July 21, 2017

Getting XML including the xml TAG

Sometime we need to extract some inner xml from the bigger xml, while parsing it.
One simple approach is to use the some String util (such as Apache commons etc.) and call stringBetween finction, but then it does not give you the parent tag and then you add the prefix and suffix the start and end tag respectively.

Alternatively you can use a mix of XQuery(to search the exact xml node) and then apply LS Serializer to get the inner xml or the sub xml as String.

In the below example of note xml, lets say we have to extract <attachments> xml. So, we will first try to get the node and then use LS Serailzer to get attachments.

The first piece of code, is the input, the second is the output we are looking for. And, the third one is the actual code.

So, that's it. Happy chopping the xmls! :) ;)




Saturday, June 24, 2017

Getting Http Header Param in Jersey (JAX-RS) Rest


How to read header parameter in Jersey REST - directly into a variable.



//contentType is the String variable which can be used later inside the method.
@GET
public Response getFirstUser(@HeaderParam("Content-Type") String contentType){

 ..
 ...
 System.out.println("content type:" + contentType)
  
 ..
  
}


There is one more way, by reading using @Context  HttpHeader (you can also use this in case you need to get multiple/all header parameters):

//All headers can be read by iterating over headers object.
@GET
public Response getFirstUser(@Context HttpHeaders headers){

  String contentType = headers.getRequestHeader("Content-Type");
  String userAgent= headers.getRequestHeader("user-agent").get(0);
  
  ...
  ... 
  
}





Thursday, June 8, 2017

View Unpushed Git Commits


Working from git command line, you want to check the commited but unpsuhed files. You can use below command:


git log origin/<branch_name>..HEAD

Replace <branch_name> with you feature branch name or the current branch name you are working with.

To create a alias inside you unix shell, you can put this alias inside your .profile or .bashrc file:

alias git-unpushed = !GIT_CURRENT_BRANCH=$(git name-rev --name-only HEAD); git log origin/$GIT_CURRENT_BRANCH..$GIT_CURRENT_BRANCH --oneline

And, use git-unpushed from your git client command prompt.

Even better, if you want git client (on your machine) to remember an alias of your liking (that can be used as command later)

$ git config --global alias.unpushed'!GIT_CURRENT_BRANCH=$(git name-rev --name-only HEAD); git log origin/$GIT_CURRENT_BRANCH..$GIT_CURRENT_BRANCH --oneline'

Then use git unpsuhed from your git client command prompt.

Prototype

Prototype is another creation pattern. Intent:  - Intent is to create objects by cloning existing instance  - Specify the kinds of obj...