<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss'><id>tag:blogger.com,1999:blog-5298847321027408119</id><updated>2009-12-18T06:43:49.006-08:00</updated><title type='text'>Java for Beginners</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://javagurug.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default?orderby=updated'/><link rel='alternate' type='text/html' href='http://javagurug.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>kaustubh verma</name><uri>http://www.blogger.com/profile/05716121951681396830</uri><email>noreply@blogger.com</email></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>6</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-5298847321027408119.post-7698487119880063722</id><published>2008-04-27T11:44:00.000-07:00</published><updated>2008-04-27T11:46:12.292-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='java'/><category scheme='http://www.blogger.com/atom/ns#' term='java best practices'/><category scheme='http://www.blogger.com/atom/ns#' term='kaustubh'/><category scheme='http://www.blogger.com/atom/ns#' term='code'/><title type='text'>Tips for maintainable Java code</title><content type='html'>&lt;p class="MsoNormal" style=""&gt;&lt;i&gt;There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.&lt;/i&gt; -- C.A.R. Hoare&lt;/p&gt;  &lt;p class="MsoNormal" style=""&gt;Here's a random collection of personal observations (some well established to the point of cliché, some deliberately controversial and tongue in cheek) on things to watch out for while designing and implementing large scale object oriented applications. While much is applicable to other languages such as C++, these days I'm only interested in Java, so that's what the examples refer to. &lt;/p&gt;  &lt;p class="MsoNormal" style=""&gt;&lt;b&gt;&lt;span style=""&gt;General&lt;/span&gt;&lt;/b&gt;&lt;/p&gt;  &lt;ul type="disc"&gt;&lt;li class="MsoNormal" style=""&gt;Programmers need to be precise. If you're sloppy      and inconsistent with spaces, indentation, names, or access modifiers,      what confidence will people have that your logic is any more accurate? &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;A good framework can sometimes help developers by      avoiding you having to reinvent the wheel each time, but a bad framework      is infinitely worse than no framework at all. Designing good frameworks is      very, very hard. Consider this point carefully and draw your own      conclusions... &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Test your code, and keep testing it. Automated      unit tests can be very useful, particularly for modules that can be driven      programmatically or from a command line. Trying to automate GUI tests, on      the other hand, is a noble goal but usually doomed to failure. It takes a      vast amount of effort with very little payback. The tests produced are      very 'brittle' (they permanently fail, but nearly always because of new      development or changes in the test data, rather than bugs in the code      actually under test). &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Keep your code simple and comprehensible. Source      code that nobody understands is about as useful as a bug-ridden third      party library with no documentation, no source code, and no support, i.e.      not very! &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Think about your reward structures. If the system      rewards analysts for the length of their documents, programmers for the      number of lines of code they write, consultants for the number of days      they can invoice, and managers for the size of the teams they hire, then      collectively this will do little to reduce the size or cost of your      development! &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Don't optimise too soon. Unless you're doing I/O      or performing the same operation a million times or more, forget about      optimising it until you've run the program under a profiler. (On the other      hand, if you develop an exponential-time algorithm with test cases of half      a dozen elements, don't be too surprised if performance is less than      satisfactory on a real world data set of 10,000 rows!) &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Using common design patterns can be useful, but      only when appropriate: "It must be good design, look, I'm using the      Visitor pattern!" "Why, exactly?" "Err, well, I've      just got to page 79 in the book and haven't tried that one yet..." &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Never test for an error condition you don't know      how to handle! If you don't know how to handle exceptions properly then      let them propagate up to someone who does, as undeclared runtime exceptions      if necessary. (Don't make the mistake of catching an exception that      contains precise details of an error, simply because it's declared and you      "have to" catch it, and then silently return, neither reporting      an error nor completing the operation the method was called to perform!) &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Here's one for managers: learn to identify those      developers with &lt;i&gt;negative&lt;/i&gt; productivity (and, boy, do they exist!)      and don't be afraid to sack them, or at least move them to a role such as      testing or documentation where they won't cause as much damage. (That      isn't meant to imply that testing isn't a valuable role - which it is - so      much as the worst most people are likely to achieve at it is zero      productivity.) &lt;/li&gt;&lt;/ul&gt;  &lt;p class="MsoNormal" style=""&gt;&lt;b&gt;&lt;span style=""&gt;Documentation&lt;/span&gt;&lt;/b&gt;&lt;/p&gt;  &lt;ul type="disc"&gt;&lt;li class="MsoNormal" style=""&gt;Document your design &lt;i&gt;after&lt;/i&gt; you code it (or      while you code it), not &lt;i&gt;before&lt;/i&gt;. That way your documents stand at      least some chance of corresponding with reality and still being useful      when someone has to come along later and maintain your code. (Ok, &lt;i&gt;some&lt;/i&gt;      up front design is clearly a good idea, but you should still leave a large      chunk of your documentation effort until after you've started coding). &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;It should go without saying that you &lt;i&gt;must&lt;/i&gt;      comment your code, and keep those comments up to date! Code that isn't      worth commenting probably isn't worth executing either. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Any maintenance programmer who has had to work on      code hacked about over the years by a myriad of other people will tell you      that the &lt;i&gt;only&lt;/i&gt; documentation they trust (or in all likelihood even &lt;i&gt;look&lt;/i&gt;      at) is the code itself. If a crucial piece of information is documented      elsewhere, or if two or more files need to be maintained in sync, then say      so in the code (in both places...). &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Remember that it's much more important to      document &lt;i&gt;why&lt;/i&gt; a method exists than what it does. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;If you find you need to use a debugger to      understand the programming logic in your own code, something, somewhere,      has gone badly wrong! &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;It sounds like a paradox but too much      documentation is actually &lt;i&gt;worse&lt;/i&gt; than too little documentation.      Nobody will read it, it will be permanently out of date, and it lulls you      into a false sense of security. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Avoid vacuous statements, e.g. commenting a      method setList(List list) to say "This methods sets the list.".      They're insulting and a waste of everybody's time. I might have guessed      that it sets a list, but what list? Why? When? What does the object do      with the list? Can it be null? etc. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Make sure you use a version control system that      maintains an edit history, and try to enter a meaningful description of      each change. (Again, it's more important to record &lt;i&gt;why&lt;/i&gt; you made a      change than what the change is.) &lt;/li&gt;&lt;/ul&gt;  &lt;p class="MsoNormal" style=""&gt;&lt;b&gt;&lt;span style=""&gt;Java language&lt;/span&gt;&lt;/b&gt;&lt;/p&gt;  &lt;ul type="disc"&gt;&lt;li class="MsoNormal" style=""&gt;When you implement equals() or hashCode() &lt;i&gt;always&lt;/i&gt;      override both or neither (you're liable to encounter some very nasty and      subtle bugs otherwise, once your objects start finding their way into      hashtables, which they often do). &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Consider overriding toString() to produce a      useful description of the object (eg. the type of the object and the value      of any unique id it contains). To avoid confusion, toString() on two      objects should normally be equal if and only if equals() is true. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;The result of calling equals() on an object of      the wrong type is 'false', not a ClassCastException. (Knowing that the      "instanceof" operator doesn't throw a NullPointerException on a      null argument but returns 'false' often helps, by the way.) &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;If your class is cloneable always call      super.clone() rather than using "new" to create the new object.      This is implemented natively and will create an object of the correct type      even if your class is later extended. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Keys and other basic types should be &lt;i&gt;immutable&lt;/i&gt;,      ie. have no setters, only take on values at time of construction,      implement equals() and hashCode(). For good measure, they could also have      a string constructor that works if you pass in the value returned by      toString(). &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Immutable objects are the "first class      citizens" of the object world. Semantically they behave exactly the      same way as basic types. You can share instances without having to worry      about anyone else modifying the value (or having the overhead of creating      copies). Declare them to be final too and you have a self-contained,      bullet-proof class, which should be every developer's highest aspiration. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Avoid duplicate representations of the same data      that need to be maintained in sync. Instead, have a single master copy and      use an adapter. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Think symmetrically. Every object that's created,      every link that's made, every listener that's added, all need to be      removed again, unless you consciously intend them to last the entire life      of the VM or can be &lt;i&gt;certain&lt;/i&gt; they will be garbage collected.      Consider adding a dispose() method to your objects to forcibly break any      references they hold and make the garbage collector's job easier. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Don't overuse threads. Unless you're sure you      know what you're doing and sure you need some extra threads then you      probably don't. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Java is not C++. It's generally good practice &lt;i&gt;not&lt;/i&gt;      to check for error conditions all over the place unless you expect the      condition to occur and plan to do something specific with that knowledge.      Let the VM take care of array bounds and null pointer checking while you      concentrate on your design (programming logic that is correct and code      that's clean and understandable). &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;This is an important point so to reiterate: &lt;i&gt;too      much&lt;/i&gt; error checking is a bad thing, especially if it's applied      haphazardly. If I come across an existing class and see that in some      methods a particular member variable is compared against null before it's      used and in others it's dereferenced without a check, what am I to assume      regarding the status of that variable?&lt;/li&gt;&lt;/ul&gt;  &lt;p class="MsoNormal" style=""&gt;&lt;b&gt;&lt;span style=""&gt;Modularity&lt;/span&gt;&lt;/b&gt;&lt;/p&gt;  &lt;ul type="disc"&gt;&lt;li class="MsoNormal" style=""&gt;A good modular, componentized design means      minimizing the knowledge and dependency one part of the system has to have      about another. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Dogma has no place in practical programming,      especially when it's driven by the latest trends in fashion, as often      seems to be the case. Who remembers the introduction of macro assemblers,      high level languages, procedural languages, structured programming, object      oriented programming, 4GLs, CASE tools, UML, client-server, COM,      JavaBeans, components, CORBA, frameworks, XML, J2EE, etc.? Each in their      way promised to be the panacea of programming, delivering standard      reusable components, and reducing the time to deliver applications to      almost nothing. But looking back, who can truthfully claim that it's &lt;i&gt;cheaper&lt;/i&gt;      to develop software now than it was 10 or 15 years ago?! &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;The common theme of most of these methodologies      is &lt;i&gt;modularity&lt;/i&gt;. To make sense of a large complex system it is      necessary to break it down into smaller parts somehow, with the minimum of      interdependencies between those parts. The difficulty of course is knowing      &lt;i&gt;which&lt;/i&gt; parts. A good methodology may help you come up with a good      design (in other words: a good breakdown into independent components), but      by no means guarantees it. Nor does a good design necessarily depend on      using any particular methodology. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;If you view each component (method, class, file,      package, application, or whatever) as a box, the important thing is having      a clear mental picture that tells you which box a particular piece of      functionality ought to go in (and even more importantly, which boxes it      shouldn't). &lt;i&gt;Achieving that clear mental picture requires both skill and      experience; there aren't any shortcuts! &lt;/i&gt;&lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;If you encounter an ugly or difficult to use API,      wrap it up in your own abstraction layer so that all the ugly code is in      one place. You can then convert it easily to use a different back end      while keeping the interface the same. Even if the API is clean and well established,      for example JDBC, there may still be valid reasons to abstract from it.      Does this mean you're likely to write your own database drivers? No.      However, you &lt;i&gt;might&lt;/i&gt; want to log all database accesses, or perhaps      start persisting your objects via XML and HTTP rather than to a relational      database, and it's obviously easier to do this if all the related code is      in one place. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Avoid designs with complex interdependencies,      such as having to write three new classes and change six others each time      you add a new field to an existing table. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Having all your code in one big file may not be      the epitome of good OO design but it makes it a darn sight easier to find      something if you don't know where to look for it, and easier to modify too      if the alternative is a morass of interdependent files. Perhaps that's      extreme, but never underestimate the power of grep as a software      development tool - the best identifiers are the ones you can easily search      for! &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Make sure you fully understand the concept of a &lt;i&gt;dependency&lt;/i&gt;.      Decide which packages are allowed to refer to which other ones and which      aren't and strictly adhere to those rules (for example, you might have GUI      code that can refer to and invoke methods on your business objects, but      not vice versa). &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Complexity in the implementation is fine, but &lt;i&gt;keep      the API simple!&lt;/i&gt;&lt;/li&gt;&lt;/ul&gt;  &lt;p class="MsoNormal" style=""&gt;&lt;b&gt;&lt;span style=""&gt;Just in time development and over-complexity&lt;/span&gt;&lt;/b&gt;&lt;/p&gt;  &lt;ul type="disc"&gt;&lt;li class="MsoNormal" style=""&gt;All code has a cost. Justify every class you      write. Developers should be rewarded for functionality rather than code;      if anything they should be &lt;i&gt;penalised&lt;/i&gt; rather than rewarded for every      new class or line of code they require to deliver that functionality. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Programmers love to be creative and demonstrate      how clever they are at coming up with elegant and generalised designs.      Don't let them - the objective is to write maintainable code, not an      elaborate monument to one's own ego. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Virtually everybody loves to generalise, yet      virtually nobody is any good at it. Until you've done something the hard      way more than once it's very difficult to spot the general pattern. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Although the exact opposite has traditionally      been ingrained in us, often it's actually better if we &lt;i&gt;do not&lt;/i&gt; worry      about the big picture or future requirements until we have to. When the      future arrives you're going to have to change it anyway, and it's a &lt;i&gt;lot&lt;/i&gt;      easier to change a simple design, that admits it didn't try to anticipate      all possible future requirements, than a complex one that tried but got it      wrong, as they invariably do. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Take your pick as to which methodology name you      pick to make the process sound respectable: "Just in time"      development, iterative development cycles, RAD, timeboxed development,      re-factoring, etc. The message is the same. Design and build &lt;i&gt;only&lt;/i&gt;      what you and your users understand &lt;i&gt;now,&lt;/i&gt; and be prepared to review      and change it once you have more complete knowledge. Throwing away and      rewriting code is a &lt;i&gt;good&lt;/i&gt; thing. Get it right &lt;i&gt;next&lt;/i&gt; time. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Be very suspicious of generalised designs that      are supposed to make things easier in future, unless you have a pretty      good understanding of those requirements and what the payback will be &lt;i&gt;now&lt;/i&gt;.      &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;If you're determined to ignore this advice (as      I'm sure you will), at least make &lt;i&gt;some&lt;/i&gt; effort to quantify what      long-term benefits you think your design will bring. All too often a      developer will spend a week developing, then two weeks debugging a general      solution where the specific solution will take a day to develop, a day to      debug, and then a further 10 minutes two months later to adapt it to a new      scenario. The developer will quite happily justify his two weeks of      debugging effort, to himself and his manager, because it avoids the need      for that one 10 minute change - and don't think I made those numbers up! &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;If a design is too complex and difficult to code      correctly, the correct solution is a simpler design, not automatic code      generators. If code is worth writing more than once, it's worth writing by      hand each time! &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Don't expose more methods in a class than you      need (eg. gratuitous 'convenience' methods). Once published, they form      part of the contract of your class, and make it much more difficult to      change in future. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Building software is the &lt;i&gt;opposite&lt;/i&gt; of      building bridges. Ten developers deliver twice as much code, four times as      many bugs, and half as much functionality as five developers. I didn't      make those numbers up either. (Of course, if managers are rewarded for the      number of people they hire and size of budget they control then it's only      natural that they'll build up as big a team is possible, regardless of      whether that's good for the project or not.) &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;If it were possible to know all the requirements      of a program in advance why are we still writing software today - wouldn't      it all already have been written 20 years or more ago? (Arguably of      course, nearly all the software that anybody really needs &lt;i&gt;was&lt;/i&gt; written      20 years ago, and everything developed since is fluff in the name of      buzzword compliance, either just 'eye candy' or driven by marketing      imperatives. Progress has its own inevitable inertia, and you need to be      seen to be using the latest technology, regardless of whether it actually      adds much tangible benefit to users!) &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Let's face it, you and I and everyone else are      going to write crap code anyway, so it may as well be cheap and simple      crap code that you understand and can afford to throw away rather than      complicated and expensive crap code. (The fact that 90% of the code      written by 90% of developers is crap is a corollary of Sturgeon's law that      90% of &lt;i&gt;everything&lt;/i&gt; is crap.) &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Don't get me wrong, I'm not saying generalised      designs or frameworks are wrong in principle, far from it. The important      thing is a good design, though, framework or no, and a good design almost      invariably means a simple design.&lt;/li&gt;&lt;/ul&gt;  &lt;p class="MsoNormal" style=""&gt;&lt;b&gt;&lt;span style=""&gt;Objects and classes&lt;/span&gt;&lt;/b&gt;&lt;/p&gt;  &lt;ul type="disc"&gt;&lt;li class="MsoNormal" style=""&gt;Think about what an object &lt;i&gt;is&lt;/i&gt;, not what      the class &lt;i&gt;does&lt;/i&gt;. With relatively few exceptions (eg. some factories,      or if you specifically need to encapsulate an algorithm or process)      classes whose name is a verb (eg. something-"Manager") are &lt;i&gt;not&lt;/i&gt;      good OO design! &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;An object or instance, as opposed to a class, is      defined by its &lt;i&gt;state&lt;/i&gt;. Think about what its state is, and what the      lifecycle of that object is. Who creates it and when, who owns it, when or      how does it get saved, when or how does it get refreshed, when is it      destroyed? etc. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Remember, what we do is called &lt;i&gt;object&lt;/i&gt;-oriented      programming, not &lt;i&gt;class&lt;/i&gt;-oriented programming! (One reason,      incidentally, why I'm not a huge fan of Rose models. I'm more interested      in how many of something there are and how they're used than what they      extend.) &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Think instances: if two related objects always      exist in a one-to-one relationship with each other, it's quite likely      they're actually the same thing and should be a single class. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Complex switch statements, especially if they      occur more than once in a class, are usually a sign of poor OO design and      call for use of inheritance. Conversely, sometimes it &lt;i&gt;is&lt;/i&gt; ok just to      parametrize a class and write a simple 'if' statement. As with everything,      apply common sense and "value your intelligence above the      standard". &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Don't use random classes or interfaces you      stumble upon for other than their intended purpose, just because they      happen to resemble the structure of what you want. (An AWT Dimension      measures pixels on a screen, so don't use it to store the size of a      football pitch in feet. A Swing ListModel defines the specific requirements      of a JList component, not a general purpose collection interface.) &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;If a utility method doesn't access any instance      variables in a class then you should probably declare the method static. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Don't use inheritance when aggregation is called      for (think about whether the relationship is an "is-a" or      "has-a" relationship).&lt;/li&gt;&lt;/ul&gt;  &lt;p class="MsoNormal" style=""&gt;&lt;b&gt;&lt;span style=""&gt;Style&lt;/span&gt;&lt;/b&gt;&lt;/p&gt;  &lt;ul type="disc"&gt;&lt;li class="MsoNormal" style=""&gt;Be consistent with indendation style. Personally,      I loathe and detest K&amp;amp;R style indentation. The only logic behind it      seems to be to avoid unecessary white space, which may have been useful      once but when is the last time &lt;i&gt;you&lt;/i&gt; edited code on a line printer or      dumb VT100 terminal? Far more useful, surely, to clearly show how blocks      line up - and far easier to spot when a rogue brace is missing. On the      other hand, this is just my &lt;i&gt;personal&lt;/i&gt; preference, and it's always      more important to be consistent. If you need to add code to someone else's      class make sure you respect the indentation style that's already in force      (or use a pretty print utility afterwards, such as &lt;a href="https://imailhyd.satyam.com/exchweb/bin/redir.asp?URL=http://www.squarebox.co.uk/download/jpp.pl" target="_blank"&gt;jpp&lt;/a&gt;). &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;There are some pretty strong conventions in Java      that class names start with UpperCase, that packages are all lower case,      that method and variable names start with lower case, that identifiers      other than constants are in mixedCase and that constants are ALL_CAPS.      It's also pretty much mandatory not just that the name of a source file      matches the class name it contains but also that the directory structure      matches the package name. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Avoid Hungarian notation (prefixing identifiers      with things like 'm' and 'lpsz'), it's ugly and unnecessary. Trying to      cram all the type and scope information into the variable name is a      hangover from the days of C, when everything was stored in global      variables. It suggests you either don't understand or don't trust the      language and compiler. (Programmers need to keep track of the meaning of      identifiers, so if you had a naming scheme that told you who owns an      object, or whether it's the master or a temporary copy of some      information, then that might actually be useful, not one that tells you      what's already known.) &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Many people put the private instance variables of      a class at the bottom of the file, reasoning that users of the class      shouldn't be concerned with the implementation. That's true, but missing      the point slightly. Having a picture of what &lt;i&gt;state&lt;/i&gt; a class embodies      is essential to understanding the class as a whole and therefore one of      the first things you look at, irrespective of whether you plan to access      that state directly. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Be consistent with your names. If variables in      two different scopes have the same meaning, or if methods in two classes      do the same thing, give them the same name. If you abbreviate a name, do      so consistently.&lt;/li&gt;&lt;/ul&gt;  &lt;p class="MsoNormal" style=""&gt;&lt;b&gt;&lt;span style=""&gt;Pulling it all together&lt;/span&gt;&lt;/b&gt;&lt;/p&gt;  &lt;p class="MsoNormal" style=""&gt;Or not: &lt;/p&gt;  &lt;ul type="disc"&gt;&lt;li class="MsoNormal" style=""&gt;For a particularly bad example of how not to      generalise a class, take a look at the abomination that is      GregorianCalendar. Vastly overcomplicated and difficult to use, and full      of concepts in the wrong place, inappropriate abstractions and      inconsistent names. Why does a Calendar contain an instance in time rather      than just embodying the rules for doing date arithmetic? Why does a Date      have set methods (a more classic example of an object that ought to be      immutable than a date or timestamp is difficult to imagine)? Why deprecate      methods that create or display a Date as UTC/GMT (by definition a &lt;i&gt;universal&lt;/i&gt;      representation that &lt;i&gt;can&lt;/i&gt; be depended on without any further locale      information) and yet leave in a toString() method that defaults to Pacific      Daylight Time?! Why expose a complicated API that reveals internal      implementation details and yet hide a safe and useful method like      getTimeInMillis(), another unambiguous and universal representation? The      designers thought they were so clever and forward-looking in not assuming      a year starts on January 1, yet still have constants like MONDAY or PM.      Above all, why is it so big and slow? (The 1.1 date classes are wrong at      so many levels you're left wondering if the whole thing was just a sick      joke, which might even have been quite funny if they weren't part of the      core language and we were now stuck with the thing!) &lt;/li&gt;&lt;/ul&gt;  &lt;p class="MsoNormal" style=""&gt;By far the biggest cost in any project is fixing and maintaining the code, &lt;i&gt;not&lt;/i&gt; developing it in the first place. So: &lt;/p&gt;  &lt;ul type="disc"&gt;&lt;li class="MsoNormal" style=""&gt;Think about users of your class. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Design for understandability and maintainability.      &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Remember that &lt;i&gt;complexity&lt;/i&gt; is the number one      enemy of &lt;i&gt;maintainability&lt;/i&gt;. &lt;/li&gt;&lt;li class="MsoNormal" style=""&gt;Less is more! &lt;/li&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5298847321027408119-7698487119880063722?l=javagurug.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javagurug.blogspot.com/feeds/7698487119880063722/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=5298847321027408119&amp;postID=7698487119880063722' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/7698487119880063722'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/7698487119880063722'/><link rel='alternate' type='text/html' href='http://javagurug.blogspot.com/2008/04/tips-for-maintainable-java-code.html' title='Tips for maintainable Java code'/><author><name>kaustubh verma</name><uri>http://www.blogger.com/profile/05716121951681396830</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='16127096785144693830'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5298847321027408119.post-175770105190177360</id><published>2008-04-27T10:58:00.000-07:00</published><updated>2008-04-27T11:04:29.430-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='java'/><category scheme='http://www.blogger.com/atom/ns#' term='w3c'/><category scheme='http://www.blogger.com/atom/ns#' term='DOM'/><category scheme='http://www.blogger.com/atom/ns#' term='sax'/><category scheme='http://www.blogger.com/atom/ns#' term='xml'/><category scheme='http://www.blogger.com/atom/ns#' term='jaxp'/><title type='text'>Reading and Writing XML file using JAVA</title><content type='html'>the purpose of program :&lt;br /&gt;&lt;br /&gt;* Read the contents of file Books.xml&lt;br /&gt;* Copy the contents to New_Books.xml&lt;br /&gt;&lt;br /&gt;Desired output&lt;br /&gt;&lt;br /&gt;New_Books.xml with same contents as Books.xml&lt;br /&gt;&lt;br /&gt;here is Books.xml&lt;br /&gt;-----------------------------------------------------------------&lt;br /&gt;&lt;books&gt;&lt;book_ordered&gt;&lt;book&gt;&lt;author&gt;&lt;/author&gt;&lt;/book&gt;&lt;book&gt;&lt;price&gt;&lt;/price&gt;&lt;/book&gt;&lt;/book_ordered&gt;&lt;/books&gt;&lt;books&gt;&lt;book_ordered&gt;&lt;book&gt;&lt;author&gt;Jeffery Archer&lt;/author&gt;&lt;title&gt;Prodigal Daughter&lt;/title&gt;&lt;price&gt;$39&lt;/price&gt;&lt;/book&gt;&lt;book&gt;&lt;author&gt;Richard Branson&lt;/author&gt;&lt;title&gt;Loosing My Virginity&lt;/title&gt;&lt;price&gt;$19&lt;/price&gt;&lt;/book&gt;&lt;book&gt;&lt;author&gt;Paulo Cohelo&lt;/author&gt;&lt;title&gt;Veronica Decides to Die&lt;/title&gt;&lt;price&gt;$23&lt;/price&gt;&lt;/book&gt;&lt;/book_ordered&gt;&lt;/books&gt;&lt;br /&gt;-----------------------------------------------------------------&lt;br /&gt;&lt;br /&gt;/*&lt;br /&gt;ParsingXML_DOM.java&lt;br /&gt;&lt;br /&gt;This program demostrates&lt;br /&gt;•	Parsing an XML file Books.xml&lt;br /&gt;•	Copying the contents of Books.xml to New_Book.xml&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Compiled By:&lt;br /&gt;Kaustubh Verma&lt;br /&gt;www.campusfever.wordpress.com&lt;br /&gt;www.javagurug.blogspot.com&lt;br /&gt;&lt;br /&gt;*/&lt;br /&gt;package Parsing_DOM;&lt;br /&gt;&lt;br /&gt;import javax.xml.parsers.ParserConfigurationException;&lt;br /&gt;import org.w3c.dom.Document;&lt;br /&gt;&lt;br /&gt;public class ParsingXML_DOM {&lt;br /&gt;&lt;br /&gt; public ParsingXML_DOM() {&lt;br /&gt;   &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;public static void main(String []args)throws Exception{&lt;br /&gt;&lt;br /&gt;    Document document = null;&lt;br /&gt;        &lt;br /&gt;  document = DOMUtil.parse("Books.xml");&lt;br /&gt;&lt;br /&gt;  if (document != null){&lt;br /&gt;    // Print XML content&lt;br /&gt;&lt;br /&gt;    DOMUtil.printDOM(document);&lt;br /&gt;     &lt;br /&gt;    // Write to a new file&lt;br /&gt;    DOMUtil.writeXmlToFile("New_Books.xml",document);&lt;br /&gt;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;  &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;get the code of DOMUtil &lt;a href="http://javagurug.blogspot.com/2008/04/creating-root-element-books-and-write.html"&gt;here&lt;/a&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5298847321027408119-175770105190177360?l=javagurug.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javagurug.blogspot.com/feeds/175770105190177360/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=5298847321027408119&amp;postID=175770105190177360' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/175770105190177360'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/175770105190177360'/><link rel='alternate' type='text/html' href='http://javagurug.blogspot.com/2008/04/reading-and-writing-xml-file-using-java.html' title='Reading and Writing XML file using JAVA'/><author><name>kaustubh verma</name><uri>http://www.blogger.com/profile/05716121951681396830</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='16127096785144693830'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5298847321027408119.post-5660739329528003247</id><published>2008-04-27T10:53:00.000-07:00</published><updated>2008-04-27T10:57:35.710-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='java'/><category scheme='http://www.blogger.com/atom/ns#' term='w3c'/><category scheme='http://www.blogger.com/atom/ns#' term='DOM'/><category scheme='http://www.blogger.com/atom/ns#' term='sax'/><category scheme='http://www.blogger.com/atom/ns#' term='xml'/><category scheme='http://www.blogger.com/atom/ns#' term='jaxp'/><title type='text'>Creating XML file using DOM in java</title><content type='html'>To find the code of DOMUtil &lt;a href="http://javagurug.blogspot.com/2008/04/creating-root-element-books-and-write.html"&gt;check here&lt;/a&gt;&lt;br /&gt;/*&lt;br /&gt;* Create_DOM.java&lt;br /&gt;*&lt;br /&gt;* Created on March 24, 2008, 4:28 PM&lt;br /&gt;*&lt;br /&gt;* Created by :  Kaustubh Verma&lt;br /&gt;                www.campusfever.wordpress.com&lt;br /&gt;                www.javagurug.blogspot.com&lt;br /&gt;&lt;br /&gt;* Created on March 24, 2008, 3:54 PM&lt;br /&gt;*&lt;br /&gt;* Purpose : To demostrate the insertion of root node BOOKS&lt;br /&gt;            to insert text node: this is an XML file&lt;br /&gt;            and save it in "book.xml"&lt;br /&gt;&lt;br /&gt;*/&lt;br /&gt;&lt;br /&gt;import javax.xml.parsers.DocumentBuilder;&lt;br /&gt;import javax.xml.parsers.DocumentBuilderFactory;&lt;br /&gt;import javax.xml.parsers.ParserConfigurationException;&lt;br /&gt;import org.w3c.dom.Document;&lt;br /&gt;// import dom.Element for root node&lt;br /&gt;import org.w3c.dom.Element;&lt;br /&gt;import org.w3c.dom.Node;&lt;br /&gt;&lt;br /&gt;public class Create_DOM {&lt;br /&gt;  &lt;br /&gt;   private Document document = null;&lt;br /&gt; &lt;br /&gt;   /** Creates a new instance of Create_DOM */&lt;br /&gt;   public Create_DOM() {&lt;br /&gt;       // &lt;editor-fold defaultstate="collapsed" desc=" main() "&gt;&lt;br /&gt;  &lt;br /&gt;   DocumentBuilder builder = null;&lt;br /&gt;   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();&lt;br /&gt;    &lt;br /&gt;    try{&lt;br /&gt;           builder = factory.newDocumentBuilder();&lt;br /&gt;           document = builder.newDocument();&lt;br /&gt;              &lt;br /&gt;       }&lt;br /&gt;    catch (ParserConfigurationException e)&lt;br /&gt;       {&lt;br /&gt;           e.printStackTrace();&lt;br /&gt;       }&lt;br /&gt;  &lt;br /&gt;    // Insert Root Order&lt;br /&gt;   Element root = (Element) document.createElement("BOOKS");&lt;br /&gt;   document.appendChild(root);&lt;br /&gt;  &lt;br /&gt;   // Insert a text node&lt;br /&gt;   Node bookChild = document.createTextNode("this is an xml file ");&lt;br /&gt;   root.appendChild(bookChild);&lt;br /&gt;      &lt;br /&gt;   // Normalizing the DOM&lt;br /&gt;   document.getDocumentElement().normalize();&lt;br /&gt;  &lt;br /&gt;   }&lt;br /&gt;  //&lt;/editor-fold&gt;&lt;br /&gt;  &lt;br /&gt;   public Document getDocument(){&lt;br /&gt;         return document;&lt;br /&gt; }&lt;br /&gt;  &lt;br /&gt;   public static void main(String ...args){&lt;br /&gt;      &lt;br /&gt;   Document document = null;&lt;br /&gt; &lt;br /&gt;   // Build new DOM Document&lt;br /&gt;   Create_DOM cDOM = new Create_DOM();&lt;br /&gt;   document = cDOM.getDocument();&lt;br /&gt;  &lt;br /&gt;   // Print XML content&lt;br /&gt;   DOMUtil.printDOM(document);&lt;br /&gt;&lt;br /&gt;   // Write to a file, give the name of OUTPUT XML FILE&lt;br /&gt;   DOMUtil.writeXmlToFile("book.xml",document);&lt;br /&gt;      &lt;br /&gt;   }&lt;br /&gt;  &lt;br /&gt;}&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5298847321027408119-5660739329528003247?l=javagurug.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javagurug.blogspot.com/feeds/5660739329528003247/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=5298847321027408119&amp;postID=5660739329528003247' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/5660739329528003247'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/5660739329528003247'/><link rel='alternate' type='text/html' href='http://javagurug.blogspot.com/2008/04/creating-xml-file-using-dom-in-java.html' title='Creating XML file using DOM in java'/><author><name>kaustubh verma</name><uri>http://www.blogger.com/profile/05716121951681396830</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='16127096785144693830'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5298847321027408119.post-884699511817663047</id><published>2008-04-27T10:35:00.000-07:00</published><updated>2008-04-27T10:47:34.532-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='java'/><category scheme='http://www.blogger.com/atom/ns#' term='w3c'/><category scheme='http://www.blogger.com/atom/ns#' term='DOM'/><category scheme='http://www.blogger.com/atom/ns#' term='sax'/><category scheme='http://www.blogger.com/atom/ns#' term='xml'/><category scheme='http://www.blogger.com/atom/ns#' term='jaxp'/><title type='text'>Creating a root element BOOKS and write it to a file "first.xml" using DOM</title><content type='html'>&lt;span style="font-weight:bold;"&gt;first create a DOMUtil class &lt;/span&gt;&lt;br /&gt;&lt;br /&gt;/*&lt;br /&gt;DOMUtil.java &lt;br /&gt; &lt;br /&gt;This utility class contains static methods to: &lt;br /&gt;• Write a DOM document to a file &lt;br /&gt;• Recursively print a specified node, and then print all of its children &lt;br /&gt;• Parse the XML file and create a DOM object in memory &lt;br /&gt;• Count elements in a document by tag name &lt;br /&gt;&lt;br /&gt;&lt;br /&gt; Compiled By: &lt;br /&gt; Kaustubh Verma&lt;br /&gt; www.campusfever.wordpress.com&lt;br /&gt;&lt;br /&gt; */&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;/*&lt;br /&gt; * &lt;br /&gt; */&lt;br /&gt;&lt;br /&gt;import java.io.IOException;&lt;br /&gt;import java.io.File;&lt;br /&gt;&lt;br /&gt;import javax.xml.parsers.DocumentBuilderFactory;&lt;br /&gt;import javax.xml.parsers.ParserConfigurationException;&lt;br /&gt;import javax.xml.parsers.DocumentBuilder;&lt;br /&gt;&lt;br /&gt;import javax.xml.transform.TransformerConfigurationException;&lt;br /&gt;import javax.xml.transform.TransformerException;&lt;br /&gt;import javax.xml.transform.Source;&lt;br /&gt;import javax.xml.transform.dom.DOMSource;&lt;br /&gt;import javax.xml.transform.Result;&lt;br /&gt;import javax.xml.transform.stream.StreamResult;&lt;br /&gt;import javax.xml.transform.Transformer;&lt;br /&gt;import javax.xml.transform.TransformerFactory;&lt;br /&gt;&lt;br /&gt;import org.xml.sax.SAXParseException;&lt;br /&gt;import org.xml.sax.SAXException;&lt;br /&gt;&lt;br /&gt;import org.w3c.dom.Document;&lt;br /&gt;import org.w3c.dom.NamedNodeMap;&lt;br /&gt;import org.w3c.dom.Node;&lt;br /&gt;import org.w3c.dom.NodeList;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * Sample Utility class to work with DOM document&lt;br /&gt; */&lt;br /&gt;public class DOMUtil {&lt;br /&gt;&lt;br /&gt;  /** Prints the specified node, then prints all of its children. */&lt;br /&gt;  public static void printDOM(Node node) {&lt;br /&gt;    int type = node.getNodeType();&lt;br /&gt;    switch (type) {&lt;br /&gt;      // print the document element&lt;br /&gt;      case Node.DOCUMENT_NODE: {&lt;br /&gt;        System.out.println("&lt;?xml version=\"1.0\" ?&gt;");&lt;br /&gt;        printDOM(((Document)node).getDocumentElement());&lt;br /&gt;        break;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      // print element with attributes&lt;br /&gt;    case Node.ELEMENT_NODE: {&lt;br /&gt;      System.out.print("&lt;");&lt;br /&gt;      System.out.print(node.getNodeName());&lt;br /&gt;      NamedNodeMap attrs = node.getAttributes();&lt;br /&gt;      for (int i = 0; i &lt; attrs.getLength(); i++) {&lt;br /&gt;        Node attr = attrs.item(i);&lt;br /&gt;        System.out.print(" " + attr.getNodeName().trim() +&lt;br /&gt;                         "=\"" + attr.getNodeValue().trim() +&lt;br /&gt;                         "\"");&lt;br /&gt;      }&lt;br /&gt;      System.out.println("&gt;");&lt;br /&gt;&lt;br /&gt;      NodeList children = node.getChildNodes();&lt;br /&gt;      if (children != null) {&lt;br /&gt;        int len = children.getLength();&lt;br /&gt;        for (int i = 0; i &lt; len; i++)&lt;br /&gt;          printDOM(children.item(i));&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      break;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // handle entity reference nodes&lt;br /&gt;  case Node.ENTITY_REFERENCE_NODE: {&lt;br /&gt;    System.out.print("&amp;");&lt;br /&gt;    System.out.print(node.getNodeName().trim());&lt;br /&gt;    System.out.print(";");&lt;br /&gt;    break;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  // print cdata sections&lt;br /&gt;case Node.CDATA_SECTION_NODE: {&lt;br /&gt;  System.out.print("&lt;![CDATA[");&lt;br /&gt;  System.out.print(node.getNodeValue().trim());&lt;br /&gt;  System.out.print("]]&gt;");&lt;br /&gt;  break;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// print text&lt;br /&gt;case Node.TEXT_NODE: {&lt;br /&gt;  System.out.print(node.getNodeValue().trim());&lt;br /&gt;  break;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// print processing instruction&lt;br /&gt;case Node.PROCESSING_INSTRUCTION_NODE: {&lt;br /&gt;  System.out.print("&lt;?");&lt;br /&gt;  System.out.print(node.getNodeName().trim());&lt;br /&gt;  String data = node.getNodeValue().trim(); {&lt;br /&gt;    System.out.print(" ");&lt;br /&gt;    System.out.print(data);&lt;br /&gt;  }&lt;br /&gt;  System.out.print("?&gt;");&lt;br /&gt;  break;&lt;br /&gt;}&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    if (type == Node.ELEMENT_NODE) {&lt;br /&gt;      System.out.println();&lt;br /&gt;      System.out.print("&lt;/");&lt;br /&gt;      System.out.print(node.getNodeName().trim());&lt;br /&gt;      System.out.print('&gt;');&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  /**&lt;br /&gt;   * Parse the XML file and create Document&lt;br /&gt;   * @param fileName&lt;br /&gt;   * @return Document&lt;br /&gt;   */&lt;br /&gt;  public static Document parse(String fileName) {&lt;br /&gt;    Document document = null;&lt;br /&gt;    // Initiate DocumentBuilderFactory&lt;br /&gt;    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();&lt;br /&gt;&lt;br /&gt;    // To get a validating parser&lt;br /&gt;    factory.setValidating(false);&lt;br /&gt;    // To get one that understands namespaces&lt;br /&gt;    factory.setNamespaceAware(true);&lt;br /&gt;&lt;br /&gt;    try {&lt;br /&gt;      // Get DocumentBuilder&lt;br /&gt;      DocumentBuilder builder = factory.newDocumentBuilder();&lt;br /&gt;      // Parse and load into memory the Document&lt;br /&gt;      document = builder.parse( new File(fileName));&lt;br /&gt;      return document;&lt;br /&gt;&lt;br /&gt;    } catch (SAXParseException spe) {&lt;br /&gt;      // Error generated by the parser&lt;br /&gt;      System.out.println("\n** Parsing error , line " + spe.getLineNumber()&lt;br /&gt;                         + ", uri " + spe.getSystemId());&lt;br /&gt;      System.out.println(" " + spe.getMessage() );&lt;br /&gt;      // Use the contained exception, if any&lt;br /&gt;      Exception x = spe;&lt;br /&gt;      if (spe.getException() != null)&lt;br /&gt;        x = spe.getException();&lt;br /&gt;      x.printStackTrace();&lt;br /&gt;    } catch (SAXException sxe) {&lt;br /&gt;      // Error generated during parsing&lt;br /&gt;      Exception x = sxe;&lt;br /&gt;      if (sxe.getException() != null)&lt;br /&gt;        x = sxe.getException();&lt;br /&gt;      x.printStackTrace();&lt;br /&gt;    } catch (ParserConfigurationException pce) {&lt;br /&gt;      // Parser with specified options can't be built&lt;br /&gt;      pce.printStackTrace();&lt;br /&gt;    } catch (IOException ioe) {&lt;br /&gt;      // I/O error&lt;br /&gt;      ioe.printStackTrace();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return null;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  /**&lt;br /&gt;   * This method writes a DOM document to a file&lt;br /&gt;   * @param filename&lt;br /&gt;   * @param document&lt;br /&gt;   */&lt;br /&gt;  public static void writeXmlToFile(String filename, Document document) {&lt;br /&gt;    try {&lt;br /&gt;      // Prepare the DOM document for writing&lt;br /&gt;      Source source = new DOMSource(document);&lt;br /&gt;&lt;br /&gt;      // Prepare the output file&lt;br /&gt;      File file = new File(filename);&lt;br /&gt;      Result result = new StreamResult(file);&lt;br /&gt;&lt;br /&gt;      // Write the DOM document to the file&lt;br /&gt;      // Get Transformer&lt;br /&gt;      Transformer xformer = TransformerFactory.newInstance().newTransformer();&lt;br /&gt;      // Write to a file&lt;br /&gt;      xformer.transform(source, result);&lt;br /&gt;    } catch (TransformerConfigurationException e) {&lt;br /&gt;      System.out.println("TransformerConfigurationException: " + e);&lt;br /&gt;    } catch (TransformerException e) {&lt;br /&gt;      System.out.println("TransformerException: " + e);&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  /**&lt;br /&gt;   * Count Elements in Document by Tag Name&lt;br /&gt;   * @param tag&lt;br /&gt;   * @param document&lt;br /&gt;   * @return number elements by Tag Name&lt;br /&gt;   */&lt;br /&gt;  public static int countByTagName(String tag, Document document){&lt;br /&gt;    NodeList list = document.getElementsByTagName(tag);&lt;br /&gt;    return list.getLength();&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;now create the main class&lt;/span&gt; &lt;br /&gt;&lt;br /&gt;/*&lt;br /&gt; * Create_DOM.java&lt;br /&gt; *&lt;br /&gt; * Created on March 24, 2008, 4:28 PM&lt;br /&gt; *&lt;br /&gt; * Created by :  Kaustubh Verma&lt;br /&gt;                 www.campusfever.wordpress.com&lt;br /&gt;                 www.javagurug.blogspot.com&lt;br /&gt;  &lt;br /&gt; * Created on March 24, 2008, 3:54 PM&lt;br /&gt; *&lt;br /&gt; * Purpose : To demostrate the insertion of root node and save it in "fisrt.xml"&lt;br /&gt; &lt;br /&gt; * the output is &lt;br /&gt;&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;br /&gt;&lt;BOOKS/&gt;&lt;br /&gt;&lt;br /&gt;the reason for &lt;BOOKS/&gt; is due to no clild of root&lt;br /&gt; &lt;br /&gt; */&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import javax.xml.parsers.DocumentBuilder;&lt;br /&gt;import javax.xml.parsers.DocumentBuilderFactory;&lt;br /&gt;import javax.xml.parsers.ParserConfigurationException;&lt;br /&gt;import org.w3c.dom.Document;&lt;br /&gt;// import dom.Element for root node&lt;br /&gt;import org.w3c.dom.Element;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;public class Create_DOM {&lt;br /&gt;    &lt;br /&gt;    private Document document = null;&lt;br /&gt;   &lt;br /&gt;    /** Creates a new instance of Create_DOM */&lt;br /&gt;    public Create_DOM() {&lt;br /&gt;        // &lt;editor-fold defaultstate="collapsed" desc=" main() "&gt;&lt;br /&gt;    &lt;br /&gt;    DocumentBuilder builder = null;&lt;br /&gt;    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();&lt;br /&gt;      &lt;br /&gt;     try{&lt;br /&gt;            builder = factory.newDocumentBuilder();&lt;br /&gt;            document = builder.newDocument();&lt;br /&gt;                &lt;br /&gt;        } &lt;br /&gt;     catch (ParserConfigurationException e) &lt;br /&gt;        {&lt;br /&gt;            e.printStackTrace();&lt;br /&gt;        }&lt;br /&gt;    &lt;br /&gt;     // Insert Root Order&lt;br /&gt;    Element root = (Element) document.createElement("BOOKS");&lt;br /&gt;    &lt;br /&gt;    document.appendChild(root);&lt;br /&gt;       &lt;br /&gt;    // Normalizing the DOM&lt;br /&gt;    document.getDocumentElement().normalize();&lt;br /&gt;    &lt;br /&gt;    }&lt;br /&gt;   //&lt;/editor-fold&gt;&lt;br /&gt;    &lt;br /&gt;    public Document getDocument(){&lt;br /&gt;          return document;&lt;br /&gt;  }&lt;br /&gt;    &lt;br /&gt;    public static void main(String ...args){&lt;br /&gt;        &lt;br /&gt;    Document document = null;&lt;br /&gt;   &lt;br /&gt;    // Build new DOM Document&lt;br /&gt;    Create_DOM cDOM = new Create_DOM();&lt;br /&gt;    document = cDOM.getDocument();&lt;br /&gt;    &lt;br /&gt;    // Print XML content&lt;br /&gt;    DOMUtil.printDOM(document);&lt;br /&gt;&lt;br /&gt;    // Write to a file, give the name of OUTPUT XML FILE&lt;br /&gt;    DOMUtil.writeXmlToFile("first.xml",document);&lt;br /&gt;        &lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;}&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5298847321027408119-884699511817663047?l=javagurug.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javagurug.blogspot.com/feeds/884699511817663047/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=5298847321027408119&amp;postID=884699511817663047' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/884699511817663047'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/884699511817663047'/><link rel='alternate' type='text/html' href='http://javagurug.blogspot.com/2008/04/creating-root-element-books-and-write.html' title='Creating a root element BOOKS and write it to a file &quot;first.xml&quot; using DOM'/><author><name>kaustubh verma</name><uri>http://www.blogger.com/profile/05716121951681396830</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='16127096785144693830'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5298847321027408119.post-4422139933970307461</id><published>2008-04-27T10:23:00.000-07:00</published><updated>2008-04-27T10:31:13.209-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='java'/><category scheme='http://www.blogger.com/atom/ns#' term='w3c'/><category scheme='http://www.blogger.com/atom/ns#' term='DOM'/><category scheme='http://www.blogger.com/atom/ns#' term='sax'/><category scheme='http://www.blogger.com/atom/ns#' term='xml'/><category scheme='http://www.blogger.com/atom/ns#' term='jaxp'/><title type='text'>Creating a new object of DOM document and DOM builder factory</title><content type='html'>/*&lt;br /&gt; * DOM_Builder_Ex.java&lt;br /&gt; *&lt;br /&gt; *Created by :  Kaustubh Verma&lt;br /&gt;                www.campusfever.wordpress.com&lt;br /&gt;  &lt;br /&gt; * Created on March 24, 2008, 3:54 PM&lt;br /&gt; *&lt;br /&gt; * Purpose : To demostrate the instantiation of a DOM builder factory and DOM document&lt;br /&gt; &lt;br /&gt; */&lt;br /&gt;&lt;br /&gt;// javax.xml.parsers    :  Provides classes allowing the processing of XML documents.&lt;br /&gt;// org.w3c.dom          :      &lt;br /&gt;import javax.xml.parsers.DocumentBuilder;&lt;br /&gt;import javax.xml.parsers.DocumentBuilderFactory;&lt;br /&gt;import javax.xml.parsers.ParserConfigurationException;&lt;br /&gt;import org.w3c.dom.Document;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; *&lt;br /&gt; *The Class Definition starts here &lt;br /&gt; */&lt;br /&gt;public class DOM_Builder_Ex {&lt;br /&gt;    &lt;br /&gt;    /** Creates a new instance of DOM_Builder_Ex */&lt;br /&gt;        public DOM_Builder_Ex() {&lt;br /&gt;        // &lt;editor-fold defaultstate="collapsed" desc=" main() "&gt;&lt;br /&gt;        Document document;&lt;br /&gt;    DocumentBuilder builder = null;&lt;br /&gt;    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();&lt;br /&gt;      &lt;br /&gt;     try{&lt;br /&gt;            builder = factory.newDocumentBuilder();&lt;br /&gt;            document = builder.newDocument();&lt;br /&gt;            System.out.println("DOM builder and DOM factory objects instantiated successfully");&lt;br /&gt;     &lt;br /&gt;        } &lt;br /&gt;     catch (ParserConfigurationException e) &lt;br /&gt;        {&lt;br /&gt;            e.printStackTrace();&lt;br /&gt;        }&lt;br /&gt;    &lt;br /&gt;    }&lt;br /&gt;   //&lt;/editor-fold&gt;&lt;br /&gt;    public static void main(String ...args){&lt;br /&gt;        &lt;br /&gt;        DOM_Builder_Ex dom = new DOM_Builder_Ex();&lt;br /&gt;        &lt;br /&gt;    }&lt;br /&gt;}&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5298847321027408119-4422139933970307461?l=javagurug.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javagurug.blogspot.com/feeds/4422139933970307461/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=5298847321027408119&amp;postID=4422139933970307461' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/4422139933970307461'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/4422139933970307461'/><link rel='alternate' type='text/html' href='http://javagurug.blogspot.com/2008/04/creating-new-object-of-dom-document-and.html' title='Creating a new object of DOM document and DOM builder factory'/><author><name>kaustubh verma</name><uri>http://www.blogger.com/profile/05716121951681396830</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='16127096785144693830'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5298847321027408119.post-5047094653766172600</id><published>2008-04-27T02:16:00.000-07:00</published><updated>2008-04-27T02:24:05.164-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='satyam'/><category scheme='http://www.blogger.com/atom/ns#' term='java'/><category scheme='http://www.blogger.com/atom/ns#' term='hibenate'/><category scheme='http://www.blogger.com/atom/ns#' term='kaustubh'/><category scheme='http://www.blogger.com/atom/ns#' term='struts'/><category scheme='http://www.blogger.com/atom/ns#' term='springs'/><category scheme='http://www.blogger.com/atom/ns#' term='jdbc'/><title type='text'>Who is Java GuruG?</title><content type='html'>class Introduction&lt;br /&gt;{&lt;br /&gt;        System.out.println("hi all I am a software developer at Satyam"+&lt;br /&gt;                           "recently completed my training on Java, with stuff"+&lt;br /&gt;                           "like Hibernate, Springs, Struts, ... I am into the "+&lt;br /&gt;                           "collateral development team that develops content for"+&lt;br /&gt;                           "trainees..... so what ever I feel like sharing on the "+&lt;br /&gt;                           "old and new technologies, I'll do it here....."+&lt;br /&gt;                           "bye and take care.... ");&lt;br /&gt;        &lt;br /&gt;}&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5298847321027408119-5047094653766172600?l=javagurug.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javagurug.blogspot.com/feeds/5047094653766172600/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=5298847321027408119&amp;postID=5047094653766172600' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/5047094653766172600'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5298847321027408119/posts/default/5047094653766172600'/><link rel='alternate' type='text/html' href='http://javagurug.blogspot.com/2008/04/who-is-java-gurug.html' title='Who is Java GuruG?'/><author><name>kaustubh verma</name><uri>http://www.blogger.com/profile/05716121951681396830</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='16127096785144693830'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry></feed>