<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
  <channel>
    <title>wujunrat</title>
    <description></description>
    <link>http://wujunrat.javaeye.com</link>
    <language>UTF-8</language>
    <copyright>Copyright 2003-2008, JavaEye.com</copyright>
    <docs>http://blogs.law.harvard.edu/tech/rss</docs>
    <generator>JavaEye - 做最棒的软件开发交流社区</generator>
      <item>
        <title>7 tips on writing clean code(ZZ)</title>
        <author>wujunrat</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://wujunrat.javaeye.com">wujunrat</a>&nbsp;
          链接：<a href="http://wujunrat.javaeye.com/blog/79083" style="color:red;">http://wujunrat.javaeye.com/blog/79083</a>&nbsp;
          发表时间: 2007年05月12日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          My job has required me to read quite a bit of code written by other people, and over the years I've found that there are some problems that tend to recur again and again. The idea with this blog entry is to write up some tips on this once and for all, in the hope that it can help people out there who struggle to write clean code. <br /><br />The main goal with these tips is readability. This is important because usually your code has to be changed or reviewed by other people, and writing readably makes these people's jobs a lot easier. That may be obvious. What's less obvious is that it also makes your own job easier, because working on simple code is a lot easier than working on complex code, even while you are writing it, and the more readable code is always simpler. <br /><br />An important part of making your code readable is to always work to communicate your intent. The basic idea is that it's usually not difficult to see what a single line of code does. The tricky thing is to see why it's doing what it does. So the more you can make your code communicate the thinking behind the code, the better it is. You'll see this point recurring repeatedly below. <br /><br />I should add that most people seem to be aware of most of these rules, in a general kind of way. The main point of this posting is really to convince people that these rules are important. So important, in fact, that you should try to always follow them, and that you should have a really bad conscience about any code that breaks them. So bad that you just never write any such code. Some of these rules require you to write a little extra code, but I think I can claim that none of them cause you to actually lose time, on any project. <br /><br />1. Always know why you are catching an exception<br />This has to be the most common mistake I see people make, and it seems to me that exceptions is a feature many people haven't really learned how to use yet. One of the reasons for this is probably that before the advent of Java the languages people used at university did not have exceptions, and so no rules were taught about this. It's not a trivial feature to use, so it's hardly surprising that people struggle. <br /><br />Anyway, the cardinal rule is: if you catch an exception you need to have a good reason. Reporting an expected error condition to the user in a more friendly way is a good reason. Handling an expected, but unusual, condition is another. But very often people just swallow the exceptions with an empty catch block (this is a real nono), or they do like this: <br /><br />  private static List readLines(String fileName) {<br />    String line;<br />    ArrayList file = new ArrayList();<br />    try {    <br />      BufferedReader in = new BufferedReader(new FileReader(fileName));<br />      while ((line = in.readLine()) != null)<br />        file.add(line);<br />      in.close();<br />    } catch (Exception e){<br />      System.out.println(e);<br />      return null;<br />    }<br />    return file;<br />  }<br /><br />The catch block here does nothing useful. In fact, it hides useful information if the program were to crash. If you don't catch the exception, you get a traceback. If you do catch it you get much less. Plus, it takes up 5 lines, and it makes the method almost twice as big as it needs to be. Doing without is just a lot better. <br /><br />That would give us this: <br /><br />  private static ArrayList readLines(String fileName) throws IOException {<br />    String line;<br />    ArrayList file = new ArrayList();<br /><br />    BufferedReader in = new BufferedReader(new FileReader(fileName));<br />    while ((line = in.readLine()) != null)<br />      file.add(line);<br />    in.close();<br /><br />    return file;<br />  }<br /><br />2. Never declare implementation types<br />This is another thing I see very often: parameters, variables, or even return types that are really implementation types. You can see this in the code above, where ArrayList is used where List would do. There are several problems with this: ArrayList is longer, and you have to do a lot of work if you want to change what list implementation you are using. <br /><br />The main thing, however, is that just using List communicates your intent that this be a list much more clearly. It says "I thought about this, and I really intend this collection to be a List, and not just any sort of collection". In other words: it tells the reader that you care about the order in this collection. <br /><br />Another round of simplification brings us this: <br /><br />  private static List readLines(String fileName) throws IOException {<br />    String line;<br />    List file = new ArrayList();<br /><br />    BufferedReader in = new BufferedReader(new FileReader(fileName));<br />    while ((line = in.readLine()) != null)<br />      file.add(line);<br />    in.close();<br /><br />    return file;<br />  }<br /><br />3. Use descriptive variable names<br />This is a rule that can be hard to follow, but in general variables should be named so that they make it clear what a variable contains. Sometimes this is blindingly obvious, and in these cases short names like i for loop indexes, in for files is perfectly OK. But if you use a longer name, try to make it meaningful. <br /><br />In the case of the method above, what does file really contain? Yes, it does contain the file, but what it really is is a list of all the lines in the file. So why not call it lines? That would give us: <br /><br />  private static List readLines(String fileName) throws IOException {<br />    String line;<br />    List lines = new ArrayList();<br /><br />    BufferedReader in = new BufferedReader(new FileReader(fileName));<br />    while ((line = in.readLine()) != null)<br />      lines.add(line);<br />    in.close();<br /><br />    return lines;<br />  }<br /><br />Still not perfect, but arguably a lot more readable than the original. <br /><br />4. Cut-and-paste code<br />One simple approach that's suggested quite often as a way to improve people's code is to disable the paste function on every developer machine. While the idea may be a little over the top, the basic thought is sound. If you have a snippet of, say, 7 lines of code that do one thing, and you want to do it again to a different set of variables, don't copy and paste the code. Instead, make a function (or a method, if you're stuck with Java). <br /><br />There are several reasons for this. One is simple brevity. Another is that it makes your code much easier to read, since you would effectively be replacing 14 lines of code with just 2. This would obviously be at the expense of an additional function/method, but since these stand alone and isolated from the rest of the code, their impact on readability is very low. The main reason, however, is that by doing this you make life much easier for yourself. Even if this is a one-time script, you are still going to change the code around. This is easier if it's broken up into parts, like functions/methods. <br /><br />5. Variables and communication<br />One of the hardest things to pick up when reading code is to understand the flow of values through the variables in the code. (This is one reason why functional programming is popular.) This has several implications for how the code should be written. <br /><br />For one thing, this means that you should try to declare variables as close to where they are used as possible. Let's say you write the following: <br /><br />String tmp = null;<br />// 50 lines that don't touch tmp<br />tmp = whatever;<br />// ...<br /><br />This means the reader has to scan 50 lines to see if tmp is used anywhere in there. Merging the assignment and the declaration would remove this problem completely, and would lose you nothing. <br /><br />Another thing this means is that if a variable is only used inside a block (if statement, while loop, or whatever), then it really should be declared in there. Imagine you write this: <br /><br />int tmp;<br />for (...) {<br />  // code that uses tmp<br />}<br />// no more mentions of tmp below this point<br /><br />In this case, you could have declared tmp inside the for loop. Not doing it sends the signal that "I'm going to keep using this variable" and forces the reader to try to figure out what happens with it later. Moving the declaration inside the loop means that you can't use the variable after the loop, which makes the code much easier to read. <br /><br />A third consequence is that you should really work hard to keep your functions/methods short. If you have a function/method that's, say, 400 lines long it becomes almost impossible to track the data flow through it. There will just be too many variables and too many assignments to keep track of. So this is a real no-no. Just don't do it. And as usual with these rules, this is a rule that will also help you get the code right the first time, so this is worth doing even if you will just write the code and then discard it. <br /><br />In fact, if you really do keep your methods short, a lot of the other rules here become less important, because the impact of breaking them will be lessened. The reason is of course that it's very hard for a short method to be really difficult to read. There's so little code in a short method that you can almost always digest it quite easily. So you could think of this as being the most important rule. <br /><br />6. Don't preserve return values you don't use<br />This is also related to making it easier to track data flow. et's say you write something like this: <br /><br />boolean present = myCollection.remove(object);<br /><br />You could have written it like this, however: <br /><br />myCollection.remove(object);<br /><br />You can safely assume that any reader of your code will know this, and therefore using the first form is a signal that "I care about this return value, and I'm going to use it for something". If you don't, you'll be confusing the reader, because they are assuming that they now need to figure out what you're going to do with this variable. <br /><br />Of course, leaving it out saves space, too, so there's really no reason not to drop these variables. <br /><br />7. Omit needless code!<br />It's quite common to find code that's commented out, but still hanging around. This is mainly bad because it bloats the code unnecessarily. People seem to do this because they want to have the possibility to bring the code back, either because they are writing an alternative they are not sure about, or (and this seems quite common) because they don't dare to delete it. However, in nearly all cases there is no real reason to keep such code around. You should be using version control, and that means you could always find any deleted code again. <br /><br />Also, since this code is no longer compiled or executed there is no real difference between commenting it out or deleting it. You've still made the change. The difference is that now it's quite likely that this code will slowly move out of sync with the code around it, so that by the time you find you want it again it will no longer work. That actually makes the code dangerous, because it tempts you to include code without understanding what it does. (If you really understood it you could retype it quite quickly even if it was deleted.) <br /><br />Of course, commenting out code while you are working on the code is fine. I do that a lot. However, I never check in code that is commented out, and whenever I find such code I delete it, without asking anyone or telling them. If they wanted the code they shouldn't have commented it out. And it will be in the version history, anyway.
          <br/>
          <span style="color:red;">
            <a href="http://wujunrat.javaeye.com/blog/79083#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Sat, 12 May 2007 13:13:39 +0800</pubDate>
        <link>http://wujunrat.javaeye.com/blog/79083</link>
        <guid>http://wujunrat.javaeye.com/blog/79083</guid>
      </item>
      <item>
        <title>12 Rules for Self-Management (ZZ)</title>
        <author>wujunrat</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://wujunrat.javaeye.com">wujunrat</a>&nbsp;
          链接：<a href="http://wujunrat.javaeye.com/blog/73052" style="color:red;">http://wujunrat.javaeye.com/blog/73052</a>&nbsp;
          发表时间: 2007年04月21日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          <p><strong>1.</strong> Live by your values, whatever they are. You confuse people when you don&rsquo;t, because they can&rsquo;t predict how you&rsquo;ll behave.<br />
<strong>2.</strong> Speak up! No one can &ldquo;hear&rdquo; what you&rsquo;re thinking without you be willing to stand up for it. Mind-reading is something most people can&rsquo;t do.<br />
<strong>3.</strong> Honor your own good word, and keep the promises you make. If not, people eventually stop believing most of what you say, and your words will no longer work for you.<br />
<strong>4.</strong> When you ask for more responsibility, expect to be held fully accountable. This is what seizing ownership of something is all about; it&rsquo;s usually an all or nothing kind of thing, and so you&rsquo;ve got to treat it that way.<br />
<strong>5.</strong> Don&rsquo;t expect people to trust you if you aren&rsquo;t willing to be trustworthy for them first and foremost. Trust is an outcome of fulfilled expectations.<br />
<strong>6.</strong> Be more productive by creating good habits and rejecting bad ones. Good habits corral your energies into a momentum-building rhythm for you; bad habits sap your energies and drain you.<br />
<strong>7.</strong> Have a good work ethic, for it seems to be getting rare today. Curious, for those &ldquo;old-fashioned&rdquo; values like dependability, timeliness, professionalism and diligence are prized more than ever before. Be action-oriented. Seek to make things work. Be willing to do what it takes.<br />
<strong>8.</strong> Be interesting. Read voraciously, and listen to learn, then teach and share everything you know. No one owes you their attention; you have to earn it and keep attracting it.<br />
<strong>9.</strong> Be nice. Be courteous, polite and respectful. Be considerate. Manners still count for an awful lot in life, and thank goodness they do.<br />
<strong>10.</strong> Be self-disciplined. That&rsquo;s what adults are supposed to &ldquo;grow up&rdquo; to be.<br />
<strong>11.</strong> Don&rsquo;t be a victim or a martyr. You always have a choice, so don&rsquo;t shy from it: Choose and choose without regret. Look forward and be enthusiastic.<br />
<strong>12.</strong> Keep healthy and take care of yourself. Exercise your mind, body and spirit so you can be someone people count on, and so you can live expansively and with abundance. </p>
          <br/>
          <span style="color:red;">
            <a href="http://wujunrat.javaeye.com/blog/73052#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Sat, 21 Apr 2007 15:21:07 +0800</pubDate>
        <link>http://wujunrat.javaeye.com/blog/73052</link>
        <guid>http://wujunrat.javaeye.com/blog/73052</guid>
      </item>
      <item>
        <title>12 Rules for Self-Management (ZZ)</title>
        <author>wujunrat</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://wujunrat.javaeye.com">wujunrat</a>&nbsp;
          链接：<a href="http://wujunrat.javaeye.com/blog/73050" style="color:red;">http://wujunrat.javaeye.com/blog/73050</a>&nbsp;
          发表时间: 2007年04月21日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          <p><strong>1.</strong> Set goals for your life; not just for your job. What we think of as &ldquo;meaning of life&rdquo; goals affect your lifestyle outside of work too, and you get whole-life context, not just work-life, each feeding off the other.<br />
<strong>2.</strong> Practice discretion constantly, and lead with the example of how your own good behavior does get great results. Otherwise, why should anyone follow you when you lead?<br />
<strong>3.</strong> Take initiative. Volunteer to be first. Be daring, bold, brave and fearless, willing to fall down, fail, and get up again for another round. Starting with vulnerability has this amazing way of making us stronger when all is done.<br />
<strong>4.</strong> Be humble and give away the credit. Going before others is only part of leading; you have to go with them too. Therefore, they&rsquo;ve got to want you around!<br />
<strong>5.</strong> Learn to love ideas and experiments. Turn them into pilot programs that preface impulsive decisions. Everything was impossible until the first person did it.<br />
<strong>6.</strong> Live in wonder. Wonder why, and prize &ldquo;Why not?&rdquo; as your favorite question. Be insatiably curious, and question everything.<br />
<strong>7.</strong> There are some things you don&rsquo;t take liberty with no matter how innovative you are when you lead. For instance, to have integrity means to tell the truth. To be ethical is to do the right thing. These are not fuzzy concepts.<br />
<strong>8.</strong> Believe that beauty exists in everything and in everyone, and then go about finding it. You&rsquo;ll be amazed how little you have to invent and much is waiting to be displayed.<br />
<strong>9.</strong> Actively reject pessimism and be an optimist. Say you have zero tolerance for negativity and self-fulfilling prophecies of doubt, and mean it.<br />
<strong>10.</strong> Champion change. As the saying goes, those who do what they&rsquo;ve always done, will get what they&rsquo;ve always gotten. The only things they do get more of are apathy, complacency, and boredom.<br />
<strong>11.</strong> Be a lifelong learner, and be a fanatic about it. Surround yourself with mentors and people smarter than you. Seek to be continually inspired by something, learning what your triggers are.<br />
<strong>12.</strong> Care for and about people. Compassion and empathy become you, and keep you ever-connected to your humanity. People will choose you to lead them. </p>
<p>&nbsp;</p>
          <br/>
          <span style="color:red;">
            <a href="http://wujunrat.javaeye.com/blog/73050#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Sat, 21 Apr 2007 15:19:39 +0800</pubDate>
        <link>http://wujunrat.javaeye.com/blog/73050</link>
        <guid>http://wujunrat.javaeye.com/blog/73050</guid>
      </item>
      <item>
        <title>新年了，blog搬家</title>
        <author>wujunrat</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://wujunrat.javaeye.com">wujunrat</a>&nbsp;
          链接：<a href="http://wujunrat.javaeye.com/blog/42786" style="color:red;">http://wujunrat.javaeye.com/blog/42786</a>&nbsp;
          发表时间: 2007年01月02日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          新的一年，应该给自己一些新的东西，一些新的目标。<br />
今天就给自己一件新东西，把blog搬到javaEye，因为越来越讨厌CSDN了，尽是些八卦和炒做。
          <br/>
          <span style="color:red;">
            <a href="http://wujunrat.javaeye.com/blog/42786#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Tue, 02 Jan 2007 18:29:15 +0800</pubDate>
        <link>http://wujunrat.javaeye.com/blog/42786</link>
        <guid>http://wujunrat.javaeye.com/blog/42786</guid>
      </item>
  </channel>
</rss>