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.

Saturday, April 1, 2017

Executor Service Example, for invoking multiple calls Parallelly

You may need to run a particular task (that can run independently) in parallel fashion in order to improve performance, or lets say, simulate a method call in multi-threaded environment:

Here is a example code snippet to do so:


Opinion on documentation

When to do documentation:

  • Nuggets of information, need to be referred by more people or more frequently - for example, Test Data, Deep links in different environment etc. 
  • It can speed up a new joiner's on-boarding. For example, some basic knowledge using which a developer can jump-start into building new feature and deploy stuff.
  • Something you feel you are likely to forget for example, an assumptions you were forced to made for whatever reason. 

When it comes to an API is used by different sets of users/clients, it needs to be documented properly. Otherwise, your consumers will either assume things, or, they will keep coming back to you with trivial questions, and that can result in low productivity on both provider's and consumer's end.

Look out for overdoing of documentations - its not good - rather, sometime its a waste of time and energy.


Monday, March 27, 2017

What you need to do to thrive in an Agile Software Development Team :)

1. The art of getting things done:
Building Software is a lot about how to get things done. Small wins are very important in initial days. Try to have targets in mind, small problems to solve, small features that can go into production.
2. Situational Awareness:
People (who is who), technology stack, way of working and cultural aspects of the team.
3. To do list:
You can follow this for time as ritual, or "deliberate practice".
Make a to do list twice, one for the present day and one for the next. Let your to do's become the engine of your initial days of growth.  
4.  Adaptability and self leadership:
You should always look for aligning your day to day tasks or activities to customer's goal or agenda.
Self leadership efforts to know your environment, to understand the way operation runs etc., comes handy when you are actually asked to deal with situations ranging from solving a technical problem to negating with customers or stakeholders.
5. Learning and early failures - Don't let silly mistake ruin your days after 6 months or an year. The early you make mistakes, the early you will have an opportunity to learn from your mistakes. Be courageous (doesn't mean act foolish, without knowing the context),
keep an open mind and learn little something everyday, until you are not comfortable enough.

Sunday, November 27, 2016

Resolving Collision issues while working with wsimport maven plugin


Such situation may arise when you are dealing with multiple version of same wsdl and want to separate two stubs into different package.

Example snippet.




http://www.mojohaus.org/jaxws-maven-plugin/wsimport-mojo.html#xjcArgs

Saturday, August 6, 2016

Getting the MIME Type based on filename

If you have worked with documents over internet (http), you must be aware of what MIME Type is.
(In case this has suddenly made you interested to read more about mime type, you can check this wiki link.)

But while doing coding in java, the traditional approach or at least how I had been working with so far is, to have a hash/map of mime types and then get it based on the file extension.

Now, here is what Java provides an interesting feature to remove your worries. :-)
There is this interesting feature since I guess, java 1.7,  in java.nio.Files -> probeContentType which gives you content type. here is small test to demo the same.



Tuesday, July 26, 2016

Formatting Strings in Java, a better way of logging!


As developers we should always choose the elegant way to do things.
One of them, is writing the log messages. Logging is important as it's the only way to see what your users/application has done or doing. Hence, it should be done elegantly. :-)

For example, if you need to write a log like this:

logger.info("records updated for user:"+ userId + "of org id:" + orgId) ;

Instead, you can use String.format(), and pass formatted string like this: 

logger.info(String.format( "records updated for user:%s of org id: %s",  userId, orgId) ) ;


Friday, July 22, 2016

What Agile Scrum is not? And, breaking some myths about scrum....

In the madness of selling Agile and adopting the buzz, many wrong interpretation and implementation is rampant. We need to understand and remind ourselves that,

Scrum is not:

  1. Marketing gimmick!!! Please stop fooling customers by setting wrong expectations.
  2. about doing no documentation at all.
  3. about saving cost ( in longer terms may be, but not ROI take some time )
  4. a magic wand, that will produce software in a day/week.
  5. asking customer that we would do everything for you and you sit back, relax and enjoy. Rather, scrum is about sharing journey with customer.
  6. Making developers commit to some stupid timeline, and leaving developers no choice!
  7. Is not very helpful, if don't align/improve your engineering practices to be able to ship quickly.


Will continue updating this, based on my experience. Any comments or personal experiences are welcome. :)

There is no ideal world, but, we as professionals, must be aware of what is right and what is wrong and stop saying Yes, when you want to say No.

Scrum Values

People often talk about Agile principles and Scrum but they leave the Scrum values aside, probably deliberately since they are pretty tough to achieve and practice.

But, when we are practicing Agile its only important that we keep reminding ourselves about these values and drive to achieve them.
Recently, I attended a session on Scrum. I think the most important takeaway for me was Scrum Values. It's not an official version not even the exact version that I got. But, as I remember correctly, here they go:

  • Self Organization
  • Trust
  • Respect 
  • Sense of urgency
  • Avoid Shortcuts
  • Share Journey with customer
  • Courage
Its not often that you sit in a session and talk about the values. But, recently, I was attending one of internal session and one of top leader was speaking. He said couple of interesting point about company's values, one that these are the guiding principles and secondly whenever you are in a situation where you are not sure whether I am wrong or right, please refer to these values. If your actions are aligned with them, you are good.

The same goes with practicing Agile!
For example, if you are showing some courage to say NO to something you are uncomfortable with or your gut feeling is not allowing to accept it, you are good. 

Sense of urgency, I also somewhat interpret this as ownership of a task/issue. It is very important that when you own the task you drive till it is "Done", to whatever is the definition is.

Similarly there can be various scenarios where these values can act as guiding force. 

Keep looking for the anti-pattern and allow these values and (of course principles) to do a course correction.


Tuesday, July 19, 2016

How to use Custom Perl Modules

Perl modules are easy to create and are used a library which you can reuse in another program or modules. However, for use it you need to do a bit of tweak in the environment, so that the interpreter can find the perl module.

@INC is the array, which works like CLASSPATH, in case you are familiar with Java. so, in the beginning of your code you need add the path where to find the perl modules you are using,


BEGIN {
        unshift(@INC, '/lib');


 # considering my perl module is located in /lib folder, relative to the current perl file

Now, @INC is an array which contains the paths of libraries, in case perl it is .pm files. And, unshift is used to append the path in the begining.

So, this code tweak make Perl interpreter aware of the path and you Perl code runs perfectly fine.  



Wednesday, June 29, 2016

Git Cheatsheet


To create a branch and switch to it at the same time, run the git checkout command with the -b switch:
git checkout -b <branch_name>
Same as:
git branch <branch_name>

git checkout <branch_name>

To check the current status of the branch.
git status
To add the changes - from the root directory - will make all red into green, if you are using git-shell

git add .
To commit your changes - use "-m" - to add message
git add -m "committing for the first time"
To do a git push into your branch

git push origin HEAD:branch_name 
To rename a branch
If you want to rename a branch while pointed to any branch, then use:
git branch -m <oldbranch> <newbranch>
If you want to rename the current branch, you can do:
git branch -m <newbranch>

To delete  a branch 

deletes the branch locally, use -D to force delete.

git branch -d <brnach_name>
 To delete it form remote:

 git push origin --delete <branchName>


Saturday, April 30, 2016

Larry Wall: 5 Programming Languages Everyone Should Know



You should see this video if you are starting your career in programming or you are interested in programming. :)


Tuesday, December 29, 2015

Resolving Unsupported major.minor version 51.0 error

Have came across this error on number of occasions.

Unsupported major.minor version 51.0 error

The reported major numbers are:
J2SE 8 = 52,
J2SE 7 = 51,
J2SE 6.0 = 50,
J2SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45
(Source: http://en.wikipedia.org/wiki/Java_class_file)



This java error comes, if you are compiling your code in java 1.7 and running it in JRE of lower version. To fix this, either you run the java class in a higher version (1.7 in this case) or instruct the compiler to create a 1.6 complaint byte code.

So, major number's represent the compiler version of the compiled bytecode here. And, may be, minor means, the JRE version you are trying to execute it in. (That's my analogy, I may not precise here, but it works for me, to recall.)
 
Fixing it in Ecplise project:
This can be done in eclipse , by right click the on the Project folder => Properties. Then choose compiler option => choose 1.6.

Fixing it in ItelliJIdea project:
File => Settings->Compiler => Java Compiler => Choose 1.6 under the Project byte code version drop down

There is a interesting story behind the convention of these numbers. If you are interested to read about it, you can find it here : James Gosling private communication to Bill Bumgarner (Source Wikipedia)





Thursday, December 24, 2015

Considering migration to cloud? Here are some tips and lesson learnt.

Recently, I was involved in migration to Openshift based cloud environment (enterprise version). We were migrating some of the apps based on the tech stack Java/JEE and back-end as oracle.

Though my organization has facilitated a dedicate infra support team, such migrations are still never easy to deal with.

Here are some of the lessons learned and point to consider if you are planning to place your apps into the cloud or, for that matter a new infra.

Do not show off and become the first one ever to do it in your company. You can be applauded, but might as well have to spend quite a few sleepless night depending upon number of switches you are turning on in the production environment.

Get a free ride or just walk in park. Get your feet wet by writing a simple app or a few servlets in a trial or evaluation server. Or, just watch someone help video/help manuals.

Talk to people who are doing the same thing in your company and as and when situation arise help them to get thru some technical issue or problem. The reward comes when you get stuck. :)

Housekeeping time. Remember, this is best time to get rid of your technical debts or any refactoring or code cleanup plans you had been keeping in the back burner  due to schedule crunch.


Analyze the impacts properly while committing yourself for the migration. You might not be knowing all the small little dependency. Following are some of the important stuff to lookout for:
  • DB Connection pooling code
  • Legacy code
  • Utilities like sending mails
  • Codes that reads a file like image or properties, from the codebase or the file system
  • Logging mechanism
  • LDAP Connections
  • Any 3rd party https calls that needs to be white-listed or needs to be added into 
  • Any other code that are based on the environment (for example, server provided API/tool etc.)
  • And last but not the least, static URLs which refers to your application 

Keep moving. When you are stuck on one particular issue, don't keep working on the same for long. Move ahead, solve the other small hanging ones. At the same time, keep following up with the support or any kind of help you can seek from a larger community. Usually, these are some small screws, which we some times just don't realize ourselves until may be, the very next morning. So, don't worry. Stay calm.

I think, these are some basic yet very relevant points I can tell from my experience. In case, you have some story or comment related with this, please do leave a comment.

Good luck in case you are into a migration phase and stumbled on this blog post. :)

Prototype

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