Thursday, November 23, 2017

Builder design pattern simple example

The below is normal simple class with constructor.

public class Computer {

	private String modelname="";
	private int ram = 0;
	private String keyboardName= "";
	private String mouseName = "";
	
	public Computer(String modelname, int ram, String keyboardName, String mouseName) {
		super();
		this.modelname = modelname;
		this.ram = ram;
		this.keyboardName = keyboardName;
		this.mouseName = mouseName;
	}

	@Override
	public String toString() {
		return "Computer [modelname=" + modelname + ", ram=" + ram + ", keyboardName=" + keyboardName + ", mouseName="
				+ mouseName + "]";
	}
}

You have another one main class called JavaTest is below.

public class JavaTest{
public static void main(String args[]){
Computer comp = new Computer("Intel", 6, "Logitech", "dell");
System.out.println("Comp object is: " + comp );
}
}

Output:
Comp object is: Computer [modelname=Intel, ram=6, keyboardName=Logitech, mouseName=dell]


We can change the above code to Builder design pattern. To do this you need to create one additional class called ComputerBuilder.

public class ComputerBuilder {

	private String modelname="";
	private int ram = 0;
	private String keyboardName= "";
	private String mouseName = "";
	
	public ComputerBuilder setModelname(String modelname) {
		this.modelname = modelname;
		return this;
	}
	public ComputerBuilder setRam(int ram) {
		this.ram = ram;
		return this;
	}
	public ComputerBuilder setKeyboardName(String keyboardName) {
		this.keyboardName = keyboardName;
		return this;
	}
	public ComputerBuilder setMouseName(String mouseName) {
		this.mouseName = mouseName;
		return this;
	}
	
	public Computer getComputer () {
		return new Computer(modelname, ram, keyboardName, mouseName);
	}
}

From the above class,

1. It don't have any getter method. We have added only setter method.

2. The last method getComputer returning the object of Computer class.

Let see how we can execute this code from main class.

Computer c = new ComputerBuilder().setKeyboardName("DELL KEyboard").setMouseName("LOGI Mouse").getComputer();
System.out.println("Comp object from builder design pattern is : " + c );

You can notice from the main class,

1. You wont get complex for creating object for computer.

2. Its not mandatory to put all arguments. If you are not providing arguments it will take its initial initialized value.

3. It will be more clear than our normal code creating object through constructor.

Output:
Comp object from builder design pattern is : Computer [modelname=, ram=0, keyboardName=DELL KEyboard, mouseName=LOGI Mouse]

Thursday, August 3, 2017

How to remove first option from select drop down option value

We may get a task sometime to remove the first value from the drop down like Chosse Country, Empty option, --Select-- etc.,

We can have lot of option to remove this. But here we can use simple css style option. Let see the code.

<select name="test">
    <option value="" style="display: none"></option>
    <option value="">Option 2</option>
    <option value="">Option 3</option>
    <option value="">Option 4</option>
    <option value="">Option 5</option>
  </select>

The style:display:none do the job for you!

UML Diagrams - Notations

Below are the list of notations which we have used in UML diagarms. Let see one by one , so that we can understand while using UML diagrams. 

Actor

It may be a Human user , System or Subsystem etc., Mostly actor will be acted from OUTSIDE.

Object 
 An object - This is a student object and its type is not specified. Underline is must there.

Asynchronous Message
 Its describing an asynchronous action, sender no need to wait for an receiver response. Just assume our normal java async thread flow. The arrow is OPEN.

Boundary
Mostly developers will use this in MVC pattern to mention at screen level. Means, capturing user interactions with system.

Comment 

 Comment , which we can use to describe related to your actions in diagram.

Controller

Controller which is used to mention our MVC pattern controller related to an entity.

DataBase
Database , which is mentioning an back end side to store and retrieve data.

Destroy

Destroy or delete which is mentioning an deleting action. Cross symbol must need to be add to mention its an destroy.

Entity
Entity which is mentioning a Model of  MVC model pattern. Model will capture an information.

Object with Type
Object which is mentioning an instance of type student and its name is s. 


Loop
Loop - Which is mentioning an normal loop with condition.

 Object Without Type
An object named as student and its type is not specified here.

Condition Met
If the condition is met then only it will proceed further.

Return
Return message or response which should be mentioned as dotted lines.

Message Itself

Its used to describe an recursion function. 

Synchronous

A normal synchronous action.

Non Instantaneous
Its describing an amount of time will take to reach other side. Example is network calls.

Friday, July 21, 2017

Editable and searchable Drop down with Javascript

Below is the select drop down, here you able to Edit, Search and Select the value. But forgot to implement arrow icon for the drop down.

However I will do another post which will show you how to hide and show drop down arrow image with the help of css.

Comment below if you need any query.

<html>
<head>
<title>Own Drop Down Component</title>

</head>
<body>
<form name="myfrm">
<input id="filter">
<select id="countries" multiple onchange="onChangeValue()" style="width:11%">
  <option value="india">India</option>
  <option value="america">America</option>
  <option value="germany">Germany</option>
  <option value="russia">Russia</option>
</select>
</form>
<script type="text/javascript">
(function () {
    // the IIFE  for local variable store information
    var optionsCache = [];

    // add option values to the cache with reduce
    function optionsArray(select) {
        var reduce = Array.prototype.reduce;
  //addToCache for cache
        return reduce.call(select.options, function addToCache(options, option) {
            options.push(option);
            return options;
        }, []);
    }
    // give a list of options matching the filter value with match function
    function filterOptions(filterValue, optionsCache) {
        return optionsCache.reduce(function filterCache(options, option) {
            var optionText = option.textContent;
            if (option.text.toLowerCase().match(filterValue.toLowerCase())) {
                options.push(option);
            }
            return options;
        }, []);
    }
    // replace current with new options
    function replaceOptions(select, options) {
 //document.getElementById("countries").size = select.options.length;
        while (select.options.length > 0) {
            select.remove(0);
        }
        options.forEach(function addOption(option) {
            select.add(option);
        });
    }
    
    function filterOptionsHandler(evt) {
        var filterField = evt.target;
        var targetSelect = document.getElementById("countries");
        if (optionsCache.length < 1) {
            optionsCache = optionsArray(targetSelect);
        }
        var options = filterOptions(filterField.value, optionsCache);
        replaceOptions(targetSelect, options);
  var x = document.getElementById("countries").length;
  //alert("bbb"+x)
  if (x > 0) {
  document.getElementById("countries").size = x;
  } else {
   document.getElementById("countries").size = 1;
   var select = document.getElementById("countries");
   select.options[select.options.length] = new Option('No Results','empty');}
    }
    // attach whatever event
    var filter = document.getElementById("filter");
 
    filter.addEventListener( 'click', function(){
  document.getElementById("countries").style.display = "block";
 } );
 filter.addEventListener("keyup", filterOptionsHandler, false);
 document.getElementById("countries").style.display = "none";
}());

function onChangeValue () {
var e = document.getElementById("countries");
var strUser = e.options[e.selectedIndex].text;
//alert(strUser);
  
  if (strUser != null) {
    //alert("Test" + strUser);
 document.getElementById('filter').value = strUser;
 document.getElementById("countries").style.display = "none";
  }
 }
  
</script>
</body>
</html>

Wednesday, July 5, 2017

How to add a particular word starting and end position of notepad++?

1. Press CTRL + H to open Find/Replace Dialog box.

2. Click "Regular expressions" checkbox near to the bottom of the dialog box.

3. Then To add your particular word, "test" (example) to the beginning of each line,
     type `^` in the "Find what" field,
     and "test" in the "Replace with" field. Just click hit "Replace All". (Alt+A Shortcut)

4. To add particular word ,"test" end of each line, type `$` in the "Find what" field,  and "test" in the       "Replace with" field. Then hit "Replace All".

That's All!

Friday, June 16, 2017

Load css based on browser identification

Loading a CSS file based on browser is not a good idea, However I will share the below code to identify browser.

Let it to do by javascript by onload method.

<script type="text/javascript">
 //Short code with ternary
 window.onload = function() {

  var link = document.createElement('link');
  link.rel = "stylesheet";
  link.type = "text/css";

  //Browser Detection
  link.href = (navigator.userAgent.indexOf("Chrome") != -1) ?link.href = "./css/grid.css";
    : (!(window.ActiveXObject) && "ActiveXObject" in window) ? link.href = "./css/iegrid.css";
      : "";
  document.querySelector("head").appendChild(link);
 }
</script>

Some people may document.write method, but It will not work in all case. Since document.write will swipes out the screen. So based on your task situation you should use this.

Friday, May 5, 2017

How to use eclipse effectively ?

Almost , most of the developers are using eclipse. But very rare developers only know all the tricky parts of eclipse IDE, means some shortcuts and way of using eclipse effectively. 

Here I am providing lot of wonderful tips and tricks of using eclipse. Remember this handling techniques you must do it again and again. I assure your productivity will increase compared to your earlier.

1. What is Open Type in eclipse ?

    Shortcut is Ctrl + Shift + T, Which will open any class , interface etc., Remember Ctrl + Shift +       R, which will open a files.

2. What is quick outline and How to use that ?

    Shortcut is Ctrl + O,  which will show you all the methods available in the current class. Press once again Ctrl + O,  which will show you inherited members for current class.

You can search method or inherited members also possible at the top search box.

3. What is open Type Hierarchy ?

    Shortcut is Ctrl + T or F4 , which will show you the hierarchy of your files. Means, inheritance class or implements interface. If you will press again Ctrl + T, it will only show you the super type hierarchy.

4. Search with eclipse Java Search File Search Method search etc.,

   You can click Search icon from the toolbar or Shortcut is Ctrl + H or by menu Search -- > Search, which will show you the effective way for search method , package , constructor etc.,

If you dont know the exact name of method or any other searchable word, just use * . eg. *action

5. What is open Declaration ?

    Right click on variable or object whatever it is, click open declaration or Shortcut F3,  which will show you where it was declared.

6. What is open call hierarchy ?

    Really a wonderful feature by eclipse to check where the caller, callees etc., Shortcut is Ctrl +Alt + H,  After call hierarchy window open check the right corner menu to get more like caller Hierarchy, callee hierarchy , history etc.,

7. References in eclipse ?

    Shortcut is Ctrl + Shift + G, it will show you related references from work space , Project , Hierarchy etc.,
    
8. Generate constructors using fields ?

     Like generate setters and getters there is an option to generate constructor also based on your class field. You can travel by Alt + Shift + S or go by Right Click.


9. Templates , how to use ?

   Eclipse templates will give you the best shortcut option for your code, for eg , sysout and putting Ctrl + Space will show you Syste.out.println . Like this you can create your own template.

I will post a separate topic , how to add new template in eclipse. Until then If you want to check about templates, Window - > Preferences - > Java -> Editor -> Templates.

12. Formatting source code by eclipse ?

   Shortcut is Ctrl + Shift + F,  which will format your source code. Suppose if you need your own style format code you can add it by code Style option. 

13. Refactor code in eclipse for local variable constants and method?

   Code refactor is the big topic , and I will post you the separate post for this. Its nothing but, will you an option to rename the method or variable or whatever , it will reflect all place. Moving the code , extract the code also possible.

14. Enable line numbers 

   Line number of the code is useful when you get error which will show nth line number missing ; So if you enable line number , you can go directly to code line.

To enable Right click side bar of the code and select Show Line numbers option.