best practrices in java

Upload: chaitu215

Post on 06-Jul-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/16/2019 Best Practrices in Java

    1/22

    1. Prefer returning Empty Collections instead of Null

    If a program is returning a collection which does not have any value, make sure an Empty collection is returned

    rather than Null elements. This saves a lot of “if else” testing on Null Elements.

    1 public class getLocationName {2   return (null==cityName ? "": cityName);3 }

    2. Use Strings carefully

    If two Strings are concatenated using “” operator in a “for” loop, then it creates a new String !"#ect, every

    time. This causes wastage of memory and increases performance time. $lso, while instantiating a String !"#ect,

    constructors should "e avoided and instantiation should happen directly. %or e&ample'

    1 !loer #nstantiation

    2 !tring ba$ = ne !tring("%et anot&er string ob'ect");

    3   aster #nstantiation

    * !tring goo$ = "%et anot&er string ob'ect"

    3. Avoid unnecessary Objects

    !ne of the most e&pensive operations (in terms of )emory *tili+ation in -ava is !"#ect reation. Thus it is

    recommended that !"#ects should only "e created or initiali+ed if necessary. %ollowing code gives an e&ample'

    +1 import 'a,a-util-.rrayList;

    +2 import 'a,a-util-List;

    +3  

    + public class /mployees {

    +*  

    +0   pri,ate List /mployees;

    +  

    +   public List get/mployees() {

    +  1+ initiali4e only &en re5uire$

    11   i6(null == /mployees) {

    12   /mployees = ne .rrayList();

    13 }1   return /mployees;1* }

    10 }

    4. Dilemma between Array and ArrayList

    /evelopers often 0nd it di1cult to decide if they should go for $rray type data structure of $rray2ist type. They

    "oth have their strengths and weaknesses. The choice really depends on the re3uirements.

    +1 import 'a,a-util-.rrayList;

    +2  

    +3 public class array7s.rrayList {+  

  • 8/16/2019 Best Practrices in Java

    2/22

    +*   public static ,oi$ main(!tring89 args) {

    +0   int89 my.rray = ne int809;

    +   my.rray89= 1+;  .rraysut6oun$/emo,e o6 elements is easy-

    1+   .rrayList#nteger@ my.rrayList = ne .rrayList@();11 my.rrayList-a$$(1);

    12 my.rrayList-a$$(2);

    13 my.rrayList-a$$(3);

    1 my.rrayList-a$$();

    1* my.rrayList-a$$(*);

    10 my.rrayList-remo,e(+);

    1  

    1   6or(int i = +; i my.rrayList-si4e(); iAA) {

    1   !ystem-out-println("/lement: " A my.rrayList-get(i));

    2+ }21  

    22 BultiC$imensional .rray

    23   int898989 multi.rray = ne int 839839839;2 }

    2* }

    4. $rrays have 0&ed si+e "ut $rray2ists have varia"le si+es. Since the si+e of $rray is 0&ed, the memory

    gets allocated at the time of declaration of $rray type varia"le. 5ence, $rrays are very fast. !n the other

    hand, if we are not aware of the si+e of the data, then $rray2ist is )ore data will lead to

    $rray!ut!f6oundE&ception and less data will cause wastage of storage space.

    7. It is much easier to $dd or 8emove elements from $rray2ist than $rray

    9. $rray can "e multi:dimensional "ut $rray2ist can "e only one dimension.

    5. When Finally does not get executed with Try

    onsider following code snippet'

    +1 public class s&utonDooEsemo {

    +2   public static ,oi$ main(!tring89 args) {

    +3   6or(int i=+;i*;iAA)+ {

    +*   try {+0 i6(i==) {

    +   !ystem-out-println("#nsi$e Fry locE-/

  • 8/16/2019 Best Practrices in Java

    3/22

    and nally  never gets called the 0fth time. The reason is: System.e&it halts e&ecution of all the running threads

    including the current one. Even nally  "lock does not get e&ecuted after try  when exit  is e&ecuted.

    =hen System.exit  is called, ->) performs two cleanup tasks "efore shut down'

    %irst, it e&ecutes all the shutdown hooks which have "een registered with Runtime.addShutdownHook . This is

    very useful "ecause it releases the resources e&ternal to ->).

    Second is related to Finalizers. Either System.runFinalizersOnExit or Runtime.runFinalizersOnExit . The use

    of nalizers has "een deprecated from a long time. Finalizers can run on live o"#ects while they are "eing

    manipulated "y other threads.This results in undesira"le results or even in a deadlock.

    +1 public class s&utonDooEsemo {

    +2  

    +3   public static ,oi$ main(!tring89 args) {

    +   6or(int i=+;i*;iAA)+* {

    +0   6inal int 6inalGi = i;

    +   try {+ >untime-get>untime()-a$$!&ut$onDooE(

    +   ne F&rea$() {1+   public ,oi$ run() {11 i6(6inalGi==) {

    12  !ystem-out-println("#nsi$eFry locE-/

  • 8/16/2019 Best Practrices in Java

    4/22

    7. Difference between single quotes and double quotes

    1 public class Da&a {

    2   public static ,oi$ main(!tring args89) {

    3   !ystem-out-print("D" A "a");

      !ystem-out-print(KDK A KaK);* }

    0 }

    %rom the code, it would seem return “5a5a” is returned, "ut it actually returns 5a4AB. The reason is that if

    dou"le 3uotes are used, the characters are treated as a string "ut in case of single 3uotes, the char :valued

    operands ( C5D and CaD to int values through a process known as widening primitive conversion. $fter integer

    conversion, the num"ers are added and return 4AB.

    8. Avoiding Memory leaks by simple tricks

    )emory leaks often cause performance degradation of software. Since, -ava manages memory automatically,

    the developers do not have much control. 6ut there are still some standard practices which can "e used to

    protect from memory leakages.

    • $lways release data"ase connections when 3uerying is complete.

    •  Try to use %inally "lock as often possi"le.

    • 8elease instances stored in Static Ta"les.

    9. Avoiding Deadlocks in Java

    /eadlocks can occur for many dierent reasons. There is no single recipe to avoid deadlocks. Normally

    deadlocks occur when one synchroni+ed o"#ect is waiting for lock on resources locked "y another synchroni+ed

    o"#ect.

     Try running the "elow program. This program demonstrates a /eadlock. This deadlock arises "ecause "oth thethreads are waiting for the resources which are gra""ed "y other thread. They "oth keep waiting and no one

    releases.

    +1 public class ea$locEemo {

    +2   public static b'ect a$$LocE = ne b'ect();

    +3   public static b'ect subLocE = ne b'ect();

    +  

    +*   public static ,oi$ main(!tring args89) {

    +0  

    +   By.$$itionF&rea$ a$$ = ne By.$$itionF&rea$();

    +  By!ubtractionF&rea$ sub = ne By!ubtractionF&rea$();+ a$$-start();

    1+ sub-start();

    11 }

    12 pri,ate static class By.$$itionF&rea$  e

  • 8/16/2019 Best Practrices in Java

    5/22

    2+   catc& (#nterrupte$/

  • 8/16/2019 Best Practrices in Java

    6/22

    11 }

    12  

    13  

    1 pri,ate static class By.$$itionF&rea$  e

  • 8/16/2019 Best Practrices in Java

    7/22

    Dol$ing !econ$ LocE---

    !ubtraction F&rea$: Maiting 6or !ubLocE--- F&rea$s: Dol$ing .$$ an$ !ub LocEs---

    10. Reserve memory for JavaSome of the -ava applications can "e highly F* intensive as well as they need a lot of 8$). Such applications

    generally run slow "ecause of a high 8$) re3uirement. In order to improve performance of such applications,

    8$) is reserved for -ava. So, for e&ample, if we have a Tomcat we"server and it has 4G H6 of 8$). If we like, we

    can allocate 8$) for -ava on this machine using the following command'

    1 e

  • 8/16/2019 Best Practrices in Java

    8/22

  • 8/16/2019 Best Practrices in Java

    9/22

    1{"No,el Name":"So$aan""No,el etails":8"Language: Din$i""%ear o6Oublication: 130""Oublis&er: LoEmanya Oress"9".ut&or":"Buns&iOremc&an$"}

    16. Decode from JSON

    In order to decode -S!N, the developer must "e aware of the schema. The details can "e found in "elow

    e&ample'

    +1 import 'a,a-io-ileNotoun$/

  • 8/16/2019 Best Practrices in Java

    10/22

    3 get an array 6rom t&e !N ob'ect

    + !ystem-out-println("atters:");

    1  !N.rray batter.rray= (!N.rray)'sonb'ect-get("batters");

    2 #terator i = batter.rray-iterator();

    3 taEe eac& ,alue 6rom t&e 'son array separately

      &ile (i-&asNe

  • 8/16/2019 Best Practrices in Java

    11/22

    12 9

    13 "topping":

    1 8

    1*   { "i$": *++1 "type": "None" }

    10   { "i$": *++2 "type": "Sla4e$" }

    1   { "i$": *++* "type": "!ugar" }1   { "i$": *++ "type": "Oo$ere$ !ugar" }

    1   { "i$": *++0 "type": "U&ocolate it& !prinEles" }

    2+   { "i$": *++3 "type": "U&ocolate" }

    21   { "i$": *++ "type": "Baple" }22 9

    23 }

    +1 F&e i$ is: 1

    +2 F&e type is: $onut+3 F&e name is: UaEe

    + F&e OOT is: +-**+* atters:

    +0 # 1++1 type >egular

    + # 1++2 type U&ocolate

    + # 1++3 type lueberry

    + # 1++ type e,ilKs oo$1+ Fopping:

    11 # *++1 type None

    12 # *++2 type Sla4e$

    13 # *++* type !ugar

    1 # *++ type Oo$ere$ !ugar1* # *++0 type U&ocolate it& !prinEles

    10 # *++3 type U&ocolate

    1 # *++ type Baple

    17. Simple String Search

     -ava oers a 2i"rary method called inde&!f(. This method is used with String !"#ect and it returns the position

    of inde& of desired string. If the string is not found then :4 is returned.

    +1 public class !tring!earc& {

    +2  +3   public static ,oi$ main(!tring89 args) {

    +   !tring my!tring = "# am a !tringJ";

    +*  

    +0 i6(my!tring-in$e

  • 8/16/2019 Best Practrices in Java

    12/22

    18. Listing content of a directory

    In order to list the contents of a directory, "elow program can "e used. This program simply receives the names

    of the all su":directory and 0les in a folder in an $rray and then that array is se3uentially traversed to list all the

    contents.

    +1 import 'a,a-io-R;+2  

    +3 public class ListUontents {

    +   public static ,oi$ main(!tring89 args) {

    +*   ile 6ile = ne ile("&omeuserocuments");+0 !tring89 6iles = 6ile-list();

    +  

    +   !ystem-out-println("Listing contents o6 " A 6ile-getOat&());

    +   6or(int i=+ ; i 6iles-lengt& ; iAA)1+ {

    11 !ystem-out-println(6iles8i9);12 }

    13 }

    1 }

    19. A Simple IO

    In order to read from a 0le and write to a 0le, -ava oers %ileInputStream and %ile!utputStream lasses.

    %ileInputStreamDs constructor accepts 0lepath of Input %ile as argument and creates %ile Input Stream. Similarly,

    %ile!utputStreamDs constructor accepts 0lepath of !utput %ile as argument and creates %ile !utput Stream.$fter

    the 0le handling is done, itDs important to “close” the streams.

    +1 import 'a,a-io-R;

    +2  

    +3 public class my#emo {

    +   public static ,oi$ main(!tring args89) t&ros #/

  • 8/16/2019 Best Practrices in Java

    13/22

    22 }

    23 }

    2 }

    2* }

    20. Executing a shell command from Java -ava oers 8untime class to e&ecute Shell ommands. Since these are e&ternal commands, e&ception handling

    is really important. In "elow e&ample, we illustrate this with a simple e&ample. =e are trying to open a F/% 0le

    from Shell command.

    +1 import 'a,a-io-u66ere$>ea$er;

    +2 import 'a,a-io-#nput!tream;

    +3 import 'a,a-io-#nput!tream>ea$er;

    +  

    +* public class !&ellUomman$/untime rt = >untime-get>untime();

    12 Orocess processb' = rt-e

  • 8/16/2019 Best Practrices in Java

    14/22

    \0n The character with octal value 0n (0

  • 8/16/2019 Best Practrices in Java

    15/22

    +1 import 'a,a-util-rege

  • 8/16/2019 Best Practrices in Java

    16/22

    + Uontainer contentOane = getUontentOane();

    1+   contentOane-setLayout(ne loLayout());

    11  

    12 o< myDori4ontalo< = o

  • 8/16/2019 Best Practrices in Java

    17/22

    10  

    1   try {

    1   T>L url = t&is-getUlass()-get>esource("By.u$io-a,");

    1  .u$io#nput!tream au$io#n =.u$io!ystem-get.u$io#nput!tream(url);

    2+ Ulip clip = .u$io!ystem-getUlip();21 clip-open(au$io#n);

    22 clip-start();

    23   } catc& (Tnsupporte$.u$ioile/

  • 8/16/2019 Best Practrices in Java

    18/22

    22 table-a$$Uell(cell);

    23 table-a$$Uell("Last Name");

    2 table-a$$Uell("Sen$er");

    2* table-a$$Uell(">am");

    20 table-a$$Uell("Zumar");

    2 table-a$$Uell("Bale");

    2 table-a$$Uell("LaEs&mi");

    2 table-a$$Uell("e,i");

    3+ table-a$$Uell("emale");

    31  32 $ocument-a$$(table);

    33  

    3 $ocument-close();

    3* }

    30 }

    25. Sending Email from Java CodeSending email from -ava is simple. =e need to install -ava )ail -ar and set its path in our programDs classpath.

     The "asic properties are set in the code and we are good to send email as mentioned in the code "elow'

    +1 import 'a,a-util-R;

    +2 import 'a,a

  • 8/16/2019 Best Practrices in Java

    19/22

    3+ }

    31 }

    32 }

    26. Measuring time

    )any applications re3uire a very precise time measurement. %or this purpose, -ava provides static methods in

    System class'

    4.   currentTimeMillis(): 8eturns current time in )illiSeconds since Epoch Time, in 2ong.

    1 long startFime = !ystem-currentFimeBillis();

    2 long estimate$Fime = !ystem-currentFimeBillis() C startFime;

    7.   nanoTime(): 8eturns the current value of the most precise availa"le system timer, in nanoseconds, in

    long. nanoTime( is meant for measuring relative time interval instead of providing a"solute timing.

    1 long startFime = !ystem-nanoFime();

    2 long estimate$Fime = !ystem-nanoFime() C startFime;

    27. Rescale Image$n image can rescaled using$1neTransform. %irst of all, Image 6uer of input image is created and then scaled

    image is rendered.

    +1 import 'a,a-at-Srap&ics2;

    +2 import 'a,a-at-geom-.66ineFrans6orm;

    +3 import 'a,a-at-image-u66ere$#mage;

    + import 'a,a-io-ile;

    +* import 'a,aescale#mage {

    +   public static ,oi$ main(!tring89 args) t&ros /S);

    11 Srap&ics2 g = imgestination-createSrap&ics();

    12  .66ineFrans6orm a66inetrans6ormation =

    .66ineFrans6orm-get!cale#nstance(2 2);13 g-$ra>en$ere$#mage(img!ource a66inetrans6ormation);

    1   #mage#-rite(imgestination "OS" ne ile("out#mage-'pg"));1* }

    10 }

    28. Capturing Mouse Hover Coordinates

    6y implementing )ouse)otion2istner Interface, mouse events can "e captured. =hen the mouse is entered in

    a speci0c region )ouse)oved Event is triggered and motion coordinates can "e captured. The following

    e&ample e&plains it'

    +1 import 'a,a-at-e,ent-R;

    +2 import 'a,a

  • 8/16/2019 Best Practrices in Java

    20/22

    +0   public Label mouseDo,er!tatus;

    +  

    +   public static ,oi$ main(!tring args89)+ {

    1+   ne BouseUaptureemo();11 }

    12  13 BouseUaptureemo()

    1 {

    1*   set!i4e(*++ *++);10 setFitle("rame $isplaying Uoor$inates o6 Bouse Botion");

    1  

    1   mouseDo,er!tatus = ne Label("No Bouse Do,er etecte$-"Label-U/NF/>);

    1 a$$(mouseDo,er!tatus);

    2+ a$$BouseBotionListener(t&is);

    21 set7isible(true);

    22 }

    23  

    2   public ,oi$ mouseBo,e$(Bouse/,ent e)2* {

    20  mouseDo,er!tatus-setFe

  • 8/16/2019 Best Practrices in Java

    21/22

     This makes it pretty clear that for image type of /ata %ile!utputStream should "e used and for Te&t type of data

    %ile=riter should "e used.

    Additional Suggestions

    1. Use Collections

     -ava is shipped with a few collection classes P for e&ample, >ector, Stack, 5ashta"le, $rray. The developers

    are encouraged to use collections as e&tensively as possi"le for the following reasons'

    o *se of collections makes the code reusa"le and interopera"le.

    o ollections make the code more structured, easier to understand and maintaina"le.

    o !ut of the "o& collection classes are well tested so the 3uality of code is good.

    2. 10-50-500 Rule

    In "ig software packages, maintaining code "ecomes very challenging. /evelopers who #oin fresh ongoing

    support pro#ects, often complain a"out' #onolithi $ode, Spaghetti $ode. There is a very simple rule to avoid

    that or keep the code clean and maintaina"le' 4G:;G:;GG.o 4G' No package can have more than 4G classes.

    o ;G' No method can have more than ;G lines of code.

    o ;GG' No class can have more than ;GG lines of code.

    2. SOLID Class Design Principles

    S!2I/ (http'KKen.wikipedia.orgKwikiKS!2I/QR7o"#ect:orientedQdesignR7B is an acronym for design

    principles coined "y 8o"ert )artin. $ccording to this rule'

    Rule Description

    inle res9onsibil it> 9rinci9le class shoul$ have one an$ onl> one taskHres9onsibili t>) + 6 class is 9er6or!in !ore than onetask# it lea$s to con6usion)

    .9enHclose$ 9r inci9 le The $evelo9ers shoul$ 6ocus !ore on exten$in the so6tware entities rather than !o$i6>in

    the!)Iiskov substitut ion 9rinci9 le +t shoul$ be 9ossible to substit ute the $erive$ class with base class)

    +nter6ace sereation 9rinci9le +ts l ike inle Jes9onsibil it> rinci9le but a99licable to inter6aces) /ach inter6ace shoul$ beres9onsible 6or a s9eci6ic task) The $evelo9ers shoul$ nee$ to i!9le!ent !etho$s which heHshe$oesnt nee$)

    De9en$enc> inversion 9rinci9le De9en$ u9on bstractions but not on concretions) This !eans that each !o$ule shoul$ bese9arate$ 6ro! other usin an abstract la>er which bin$s the! toether)

    3. Usage of Design Patterns

    /esign patterns help developers to incorporate "est Software /esign Frinciples in their software. They also

    provide common platform for developers across the glo"e. They provide standard terminology which makes

    developers to colla"orate and easier to communicate to each other.

    4. Document ideas

    Never #ust start writing code. Strategi+e, Frepare, /ocument, 8eview and Implementation. %irst of all, #ot

    down your re3uirements. Frepare a design document. )ention assumptions properly. Het the documents

    peer reviewed and take a sign o on them.

    5. Use Equals over ==

    JJ compares o"#ect references, it checks to see if the two operands point to the same o"#ect (not e3uivalent

    o"#ects, the same o"#ect.!n the other hand, “e3uals” perform actual comparison of two strings.

    6. Avoid Floating Point Numbers

  • 8/16/2019 Best Practrices in Java

    22/22

    %loating point num"ers should "e used only if they are a"solutely necessary. %or e&ample, representing

    8upees and Faise using %loating Foint num"ers can "e Fro"lematic P 6ig/ecimal should instead "e preferred.

    %loating point num"ers are more useful in measurements.

    4 E&ample 4' Talks a"out empty collections, "ut the e&ample is a"out returning (supposedly a String

    7 E&ample 4' /oes not compile. )ethod returns String. “class” is not a valid return type and the method has no "races.9 E&ample 4' Testing null JJ some!"#ect is confusing. ItDs more useful in a String conte&t' “No”.e3uals(anwser