<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>coder . cl &#187; java</title>
	<atom:link href="http://coder.cl/category/programming/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://coder.cl</link>
	<description>web developer &#38; system programmer</description>
	<lastBuildDate>Sat, 04 Feb 2012 12:07:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>what is thread-safe?</title>
		<link>http://coder.cl/2011/11/what-is-thread-safe/</link>
		<comments>http://coder.cl/2011/11/what-is-thread-safe/#comments</comments>
		<pubDate>Sat, 26 Nov 2011 20:51:11 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[c]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2044</guid>
		<description><![CDATA[What is thread-safe?. Thread-safe implies that for a given resource it will not be used at the same time by two or more threads or processes. By resource, we must understand a memory block or similar kind of resources. If you create a list that is shared between threads to store data, you will need [...]]]></description>
			<content:encoded><![CDATA[<p>What is thread-safe?. Thread-safe implies that for a given resource it will not be used at the same time by two or more threads or processes. By resource, we must understand a memory block or similar kind of resources. If you create a list that is shared between threads to store data, you will need a way to write that list &mdash; appending nodes or removing nodes &mdash; without writing it simultaneously. This implies the usage of thread-safety techniques that will bring you sequential access to the list allowing sequential writes, instead concurrent writes that will probably crash your application.</p>
<p><span id="more-2044"></span></p>
<p>There are various kinds of techniques that can be used to create thread-safe algorithms and data structures. The are two main classes called <i>blocking algorithms</i> and <i>non-blocking algorithms</i>. On a blocking algorithm, locks are used to encapsulate fragments of code where you must not do concurrent writes to avoid racing conditions, where that fragment is called <i>critical section</i>. On non-blocking algorithms, you do not use locks, instead you use atomic operations to switch between the used resources, for example using a technique called <i>compare and swap</i> or <i>CAS</i>.</p>
<p>A racing condition, is an event that occurs when two or more threads are accessing the same resource at the same time, leading to data corruption or system faults. The most classic lock techniques in Java and C, are the <tt>synchronized</tt> keyword on Java and <tt>pthread_mutex_lock()</tt> call in C. On Java we protect our critical section using <tt>synchronized</tt> as follows.</p>
<pre class="brush: java;">
class SingletonSampleImpl extends Object {  

    private static Object singletonMutex = new Object();
    private static SingletonSampleImpl instance = null;  

    public static SingletonSampleImpl getInstance() {
        synchronized (singletonMutex) {
            /* when we instantiate the singleton
               we have a critical section to protect
               from racing conditions */
            if (instance == null) {
                instance = new SingletonSampleImpl();
            }
        }
        return instance;
    }
}
</pre>
<p>The <tt>singletonMutex</tt> object acts as <i>mutex</i>, where a mutex &mdash; term that comes from <i>mutual exclusion</i> &mdash; has a flag that indicates to the other threads if it is blocked or not to jump into the critical section and execute the code. So, a mutex or semaphore is a mere <i>flag</i> that indicates to the program if the resource is busy or not. Using locks or blocking-algorithms is expensive on most systems, depending on how are they used. For example is very expensive to use a blocking algorithm to protect a socket, where it must <i>wait</i> its chance to be written by other threads, with inherent network time wait.</p>
<p>On the non-blocking side, we have three types of algorithms: <i>wait-free</i>, <i>lock-free</i> and <i>obstruction-free</i>. Where wait free is the strongest technique, but the hardest to handle, because once you implement it you have an algorithm that do not <i>waits</i> for writing or reading. Lock-free usually uses CAS, so it using a compare and swap operation to ensure that the critical section is protected, without locking. Obstruction-free uses locking, but a different one called live-locking.</p>
<p>The atomic operations used on the non-blocking techniques usually are operating on a very low level of the processor, because they must executed without the interference of any other threads. For example to work with atomic operations using the GCC compiler we have some <a href='http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Atomic-Builtins.html' title='Built-in functions for atomic memory access'>special extensions to work with them</a>.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2011 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2011. | <a href="http://coder.cl/2011/11/what-is-thread-safe/">Permalink</a> | <a href="http://coder.cl/2011/11/what-is-thread-safe/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/11/what-is-thread-safe/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>evolutionary unit tests</title>
		<link>http://coder.cl/2011/07/evolutionary-unit-tests/</link>
		<comments>http://coder.cl/2011/07/evolutionary-unit-tests/#comments</comments>
		<pubDate>Fri, 08 Jul 2011 15:45:37 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1653</guid>
		<description><![CDATA[Evolutionary development depends on continuous iterations with the customer, being a final customer or not, like an intern QA engineer. If you create unit tests in your evolutionary development process, you can also work with evolutionary unit tests. An evolutionary unit test can be used on code hardening tasks, because you must make your test [...]]]></description>
			<content:encoded><![CDATA[<p>Evolutionary development depends on continuous iterations with the customer, being a final customer or not, like an intern QA engineer. If you create unit tests in your evolutionary development process, you can also work with evolutionary unit tests. An evolutionary unit test can be used on code hardening tasks, because you must make your test fail using unexpected environment behaviour, for example passing <tt>null</tt> references to your unit tests, avoiding the well known <a href='http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare' title='Null References: The Billion Dollar Mistake'><i>&ldquo;Null References: The Billion Dollar Mistake&rdquo;</i></a>, once the code is refactored to support <tt>null</tt> references.</p>
<p><span id="more-1653"></span></p>
<p>You can start checking the <a href='http://cwe.mitre.org/top25/?2011' title='2011 CWE/SANS Top 25 Most Dangerous Software Errors'><i>&ldquo;2011 CWE/SANS Top 25 Most Dangerous Software Errors&rdquo;</i></a> using your unit tests. Regarding the best programming practices, and even using style checkers and static analysis tools, you will be generating better code. So, the cycle is simple while you are testing your application:</p>
<ol>
<li>Create a Test Case.</li>
<li>Check that the Test Case runs correctly.</li>
<li>Choose a well known error, for example <i>null references</i>.</li>
<li>Change the Test Case and add the wrong input to your code.</li>
<li>Refactor the application hardening its input.</li>
<li>Check that the Test Case runs correctly with wrong input.</li>
<li>Document your progress with source code comments or annotations.</li>
<li>Choose another error and make the Test Case fail again.</li>
</ol>
<div class="figure">
<a href='http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2011/07/test-cycle.jpg' title='Code Hardening Testing Cycle' target='_blank'><img src='http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2011/07/test-cycle.jpg' border='0' alt='Code Hardening Testing Cycle' /></a></p>
<div>Code Hardening Testing Cycle</div>
</div>
<p>There is also some interesting papers and documents with some techniques that you can integrate in your development process, so you can create more stable code, mostly applied to Object-Oriented software and strongly-typed languages, which are talking about using manually created evolutionary tests to using genetic programming for those tasks. I hope that we can see the results of that research using genetic programming to automate the test handling process. The advantage of strongly-typed languages is the fact that most of them require to be statically-typed, which means that your code must follow well implemented type declarations and variable declaration using the proper types. So, the type system on those languages can be used to ensure that implementations are correctly done.</p>
<blockquote><p>
Initially, the test cluster for the given class under test is defined using static analysis. The concerned classes are then instrumented; thereby, the test goals &mdash; in our case all branches of the methods of the class under test &mdash; are collected. We follow the goal oriented approach and carry out a search for a test program for each individual test goal.
</p></blockquote>
<p>Static analysis again plays an interesting role on this approach, where is easier to handle static analysis on strongly-typed languages, rather than using static analysis on dynamically-typed languages.</p>
<blockquote><p>
When comparing evolutionary-based approaches over random testing [21] several prominent advantages arise, which include: less need for human analysis, as the evolutionary algorithm pre-analyses the software in accordance to the fitness function; the ability to automatically test combinations of suspicious parameters; and the possibility of finding combinations of inputs that lead to a more severe fault behaviour. Drawbacks include the difficulty of detecting solitary errors (&ldquo;needles in a haystack&rdquo;) with greater efficiency than random testing, and the impossibility of guaranteeing code coverage in black-box testing.
</p></blockquote>
<p>But if we have a lack of that kind of tools in our environment, so we must do that kind of analysis manually, and manually make our test to be tested against suspicious environment conditions, so we can use manual evolutionary unit testing. I hope that you will enjoy hardening your code ;)</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2011 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2011. | <a href="http://coder.cl/2011/07/evolutionary-unit-tests/">Permalink</a> | <a href="http://coder.cl/2011/07/evolutionary-unit-tests/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/07/evolutionary-unit-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>considerations in code review</title>
		<link>http://coder.cl/2011/07/considerations-in-code-review/</link>
		<comments>http://coder.cl/2011/07/considerations-in-code-review/#comments</comments>
		<pubDate>Thu, 07 Jul 2011 00:04:37 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1644</guid>
		<description><![CDATA[Once we have created code, we can evaluate how it was done. We can use various tools to check our creation among other activities. To do standard checks, we can use style checkers, static checkers, unit testing suites and the most important one, the human code review. We can use Python as example language, or [...]]]></description>
			<content:encoded><![CDATA[<p>Once we have created code, we can evaluate how it was done. We can use various tools to check our creation among other activities. To do standard checks, we can use style checkers, static checkers, unit testing suites and the most important one, the human code review.</p>
<p><span id="more-1644"></span></p>
<p>We can use Python as example language, or even Java. To check the Python style, we can use the <a href='http://pypi.python.org/pypi/pep8/0.6.1' title='PEP8 Style Checker'>pep8</a> style checker, which is based on the <a href='http://www.python.org/dev/peps/pep-0008/' title='PEP8, Python Style Guide'>PEP8 Python Style Guide</a>. To make lightweight Python correctness checks, we can use <a href='http://pypi.python.org/pypi/pylint/0.23.0' title='PyLint Static Checker'>PyLint</a> and <a href='http://pypi.python.org/pypi/pyflakes/0.4.0' title='PyFlakes Static Checker'>PyFlakes</a>, which are <i>static checkers</i>. To build unit test suites, we can use <a href='http://pypi.python.org/pypi/PyUnit/1.4.1'>PyUnit</a>. All those tools will help us in our coding tasks, so we can create a better and clean code. Very close to the required standards cited by the PEP8 and The Zen of Python. I have modified a script that runs all those checkers in one command to be integrated under Emacs, and you can download it <a href='http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2011/07/pycheckers.py_.gz' title='pycheckers.py script'>here</a>. To integrate that script on your Emacs editor, you can use the following settings:</p>
<pre class="brush: lisp;">
(defun my-python-mode-hook ()
  (setq py-indent-offset 4
        py-smart-indentation nil
        py-continuation-offset 4
        indent-tabs-mode nil
        py-pychecker-command "pycheckers.py"
        py-pychecker-command-args (quote ("")))
  (setq interpreter-mode-alist(cons '("python" . python-mode)
                                    interpreter-mode-alist))
  (eldoc-mode 1)
  (define-key py-mode-map "\C-c\C-w" (lambda ()
     (interactive)
     (command-execute 'py-pychecker-run)))
  (message ">>> done my-python-mode-hook..."))

(add-hook 'python-mode-hook 'my-python-mode-hook)
</pre>
<p>On the Java side, we have CheckStyle as style checker. As static checker, we have PMD and FindBugs. To build unit testing suites, we can use the well known JUnit. All of those tools can be integrated in your favourite Java IDE, like Eclipse or NetBeans, since you can integrate them on those IDEs using plug-ins. Java is quite different from Python, because it has several coding styles, among a wide variety of FOSS projects and company standards, so you need to choose between those styles.</p>
<p>Among other tasks, the code review matters. Static analysis tools and style checkers are not enough to ensure that your code is clean. You can use code hardening techniques to make safer code. But that requires that you must stay a little bit paranoid with your code, checking every execution path on it. There are some good books on code hardening techniques like <i>&ldquo;GNU/Linux Application Programming&rdquo;</i>, which explains some techniques and <i>&ldquo;Secure Coding Principles &amp; Practice&rdquo;</i>.</p>
<p>You can integrate those techniques in your evolutionary testing process. Debugging tests is not a ridiculous task, I think that it is a good approach to make better code, assuming that you will modify the program variables enough to make your unit tests fail, and then refactor the code, repair possible failure and fix a harder execution path. But those activities requires the proper time assignment, so your project manager must include enough time to test and prove that your code will work well, even if the environment fails.</p>
<p>I hope that you will enjoy changing your mind about thinking that the code that just works is fine, switching a little and make sure that your code will work <i>always</i>.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2011 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2011. | <a href="http://coder.cl/2011/07/considerations-in-code-review/">Permalink</a> | <a href="http://coder.cl/2011/07/considerations-in-code-review/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/07/considerations-in-code-review/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>singleton are not dangerous</title>
		<link>http://coder.cl/2011/06/singleton-are-not-dangerous/</link>
		<comments>http://coder.cl/2011/06/singleton-are-not-dangerous/#comments</comments>
		<pubDate>Thu, 30 Jun 2011 16:39:34 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1631</guid>
		<description><![CDATA[Yes, singleton patterns are not dangerous. That pattern is dangerous only for those developers that cannot handle concurrent programming or parallel programming, where you need to manage resources with concurrent access, even if they are read or write. There are some myths related to the singleton pattern, but they are just created by that kind [...]]]></description>
			<content:encoded><![CDATA[<p>Yes, singleton patterns are not dangerous. That pattern is dangerous only for those developers that cannot handle concurrent programming or parallel programming, where you need to manage resources with concurrent access, even if they are read or write. There are some myths related to the singleton pattern, but they are just created by that kind of developers. If you don&#8217;t know about concurrent programming techniques, is obvious that your application is at risk if your are using singletons with the wrong implementation. Also it depends on how large is your application, how do you apply governance over you application design and which platform is using.</p>
<p><span id="more-1631"></span></p>
<p>Certainly an application that uses a worker model, using threads, probably requires concurrent programming techniques to use the singleton pattern. That kind of applications, for example those implemented under JavaEE containers, like IBM WebSphere and Oracle WebLogic, require a good governance over the code and a good knowledge on how will be used a singleton implementation. In other environments, where static objects are not shared on the stack, you don&#8217;t need to care about singleton implementations, like PHP environments, where only one thread or process is reaching the singleton object, it just requires to be instanced once, and do not requires mutexes.</p>
<p>If you are good enough, you can use the singleton pattern on worker enabled environments. The well known <tt>getInstance</tt> method, should be implemented as follows in Java under JavaEE environments:</p>
<pre class="brush: java;">
class SingletonSampleImpl extends Object {

    private static Object singletonMutex = new Object();
    private static SingletonSampleImpl instance = null;

    public static SingletonSampleImpl getInstance() {
        synchronized (singletonMutex) {
            if (instance == null) {
                instance = new SingletonSampleImpl();
            }
        }
        return instance;
    }
}
</pre>
<p>In other environments like PHP, you do not need to care about creating a mutex that protects the singleton instance to be overwritten or allocated twice, you just need to care about an object instance that is not accessed twice by various threads concurrently.</p>
<pre class="brush: php;">
class SingletonSample {

    private static $instance = null;

    public static function getInstance() {
        if ($instance == null) {
            $instance = SingletonSample();
        }
        return $instance;
    }
}
</pre>
<p>Also you must be very careful, and never externalise the control of mutexes to external routines. A mutex must be controlled locally. The reason is simple, you just need to avoid a deadlock by double locking the mutex. If you externalise the control of a mutex, you are in risk of reaching a situation like the following problem, where the second lock will wait for the first one, creating a deadlock and killing the thread.</p>
<pre class="brush: java;">
synchronized (singletonMutex) {
    synchronized (singletonMutex) {
        instance = new SingletonSampleImpl();
    }
}
</pre>
<p>This is just the situation that you can reach by externalising the control of a mutex, not the algorithm itself that you will implement, but the risk that you run by allowing mutexes to be locked outside of the controlling class. This is a similar situation that generates a race condition when you are programming singletons in worker environments without using the proper mutex. The wrong implementation of a singleton that is under the risk of a race condition is on the following example, where the algorithm just checks for a null value, and do not uses a lock for the concurrent threads that can instantiate the <tt>instance</tt> object.</p>
<pre class="brush: java;">
class SingletonSampleImpl extends Object {

    private static Object singletonMutex = new Object();
    private static SingletonSampleImpl instance = null;

    public static SingletonSampleImpl getInstance() {
        if (instance == null) {
            instance = new SingletonSampleImpl();
        }
        return instance;
    }
}
</pre>
<p>So, using singletons is not dangerous. Just requires to have developers with the proper knowledge.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2011 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2011. | <a href="http://coder.cl/2011/06/singleton-are-not-dangerous/">Permalink</a> | <a href="http://coder.cl/2011/06/singleton-are-not-dangerous/#comments">One comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/06/singleton-are-not-dangerous/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>code hardening techniques</title>
		<link>http://coder.cl/2011/02/code-hardening-techniques/</link>
		<comments>http://coder.cl/2011/02/code-hardening-techniques/#comments</comments>
		<pubDate>Wed, 23 Feb 2011 13:40:33 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1348</guid>
		<description><![CDATA[Do you know something about Test Driven Development?, It is OK, you can reach optimal development performance using TDD, and similar methodologies. You will find yourself developing applications very quickly, but &#8220;how hard is your code?&#8221;. You can reach very high quality code only using your debugger, making tests is just not enough. Using some [...]]]></description>
			<content:encoded><![CDATA[<p>Do you know something about Test Driven Development?, It is OK, you can reach optimal development performance using TDD, and similar methodologies. You will find yourself developing applications very quickly, but <i>&ldquo;how hard is your code?&rdquo;</i>. You can reach very high quality code only using your debugger, making tests is just not enough. Using some debugging techniques, you can find not evident bugs, and you will probably find succesfuly some bugs that can cause your application to core dump &mdash; core dump is one of the ugliest forms of application failures, I prefer to think that each application failures is not another thing than a core dump.</p>
<p><span id="more-1348"></span></p>
<p>You can use unit tests and TDD, and double check that your algorithms are working. Also you can check your code using some <i>static checker</i>. Both will help to find you a little bit optimal code. This will allow you create more stable and reliable code, but not enough to be hard. When you code an aplication, you must think that the application and your code is merged within an environment, and it has dependencies. So, you need enough time to double check your code using tests and also, you need to double check your code using static checkers when they are available for your language. All is about input and output&#8230;</p>
<p>Your code has an input, from a service, from the user using a browser, from some data retrieval cron task, whatever, your application is subject of <i>input errors</i>. The typicall error is to reach <i>null references</i>, where your application tries to use an unallocated address space, using a reference to an object or anything related to it. The main technique against null reference, is to check the reference before you begin using it. Just to show some examples I will use Java code, I can use C++ or C code, but I prefer to use Java codes in this post:</p>
<pre class="brush: java;">
  /***
   * Returns a list of File objects that match the given stream
   * name on the given directory.
   *
   * @param strm    Stream name.
   * @param bdir    Directory to List.
   * @return      An array of found File objects.
   */
  public static File[] getFileNamesForStream(String strm, String bdir) {
    ArrayList&lt;File&gt; res = new ArrayList&lt;File&gt;();
    if (strm == null || bdir == null) {
      return new File[0];
    }
    if (strm.trim().length() == 0 || bdir.trim().length() == 0) {
      return new File[0];
    }
    File fdir = new File(bdir);
    File[] rawdir = fdir.listFiles();
    if (rawdir == null || rawdir.length == 0) {
      return new File[0];
    }
    for (int i = 0; i &lt; rawdir.length; i++) {
      String name = rawdir[i].getName();
      if (name.indexOf(strm) >= 0) {
        res.add(new File(bdir + File.separator + name));
      }
    }
    Collections.sort(res, new FileDateComparator());
    return (File[]) res.toArray(new File[0]);
  }
</pre>
<p>The code above does various checks. Ther first one is to check the <tt>strm</tt> and the <tt>bdir</tt> parameters to be <tt>null</tt>. If those parameters are null, the method returns an empty array &mdash; instead of returning a new null reference increasing the error probability &mdash; so the user do not process any file from the returned array, the returned object can be used <i>transparently</i>. Then checks for string emptyness, we cannot use empty file names, because the operating system do not allows empty file names, and again we are using a zero filled array as return object. Then we list files on the input directory <tt>bdir</tt>, and we check if there is any available file on the directory, if the directory is empty, we return a zero filled array, but <i>never returns a null reference</i>. The method is <i>hardened</i> against input and output. The example above is easy to handle, but <i>&ldquo;what happens to service enabled methods?&rdquo;</i>.</p>
<pre class="brush: java;">
  /**
   * Initial method to handle playlist items on server startup.
   *
   * @param server      The server where to put the streams.
   */
  private void refreshPlayList(IServer server) {
    try {
      if (server == null) {
        return;
      }
      if (minutesToShift &lt; 0 &amp;&amp; ownServer != null) {
        synchronized (schedulerMutex) {
          minutesToShift = Long.valueOf(ownServer.
              getProperties().
              getPropertyStr("MinutesToShift", "41")).
            longValue();
        }
      }
      IVHost vhost = VHostSingleton.getInstance(server.
                         getProperties().
                         getPropertyStr("PublishToVHost", VHost.VHOST_DEFAULT));
      if (vhost == null) {
        return;
      }
      IApplication app = vhost.getApplication(server.
                         getProperties().
                         getPropertyStr("PublishToApplication", "live"));
      if (app == null) {
        return;
      }
      streamsToAdd = WowzaTools.getStreams(server.
                         getProperties().
                         getPropertyStr("StreamsToAdd", "_default_"));
      for (int si = 0; si &lt; streamsToAdd.length; si++) {
        String streamName = streamsToAdd[si] + STREAM_SUFFIX;
        Stream stream = getStream(vhost, app, streamName);
        if (stream == null) {
          continue;
        }
        streamMap.put(streamName, stream);
        app.getAppInstance("_definst_").
          getProperties().
          setProperty(streamName, stream);
        setupStream(stream);
        IStreamActionNotify actionNotify = new
          StreamListener(app.getAppInstance("_definst_"));
        stream.addListener(actionNotify);
      }
      ScheduledItem sched = new ScheduledItem(
        new Date(System.currentTimeMillis() + 30000)
      );
      sched.start();
    } catch (Exception ex) {
      log.error(ex.getMessage());
      log.error(ex);
    }
  }
</pre>
<p>The method above is <tt>void</tt>, it do not have a return value. The first check is over the <tt>server</tt> argument, if it is a <i>null reference</i>, we exit from the method. Then checks for the <tt>minutesToShift</tt> and the <tt>ownServer</tt> static members, and uses a mutex to write on one of them, doing a synchronous write and doing it once. Then we check for the <tt>vhost</tt> and <tt>app</tt> variable to be null references, we exit from the method if any of them are null references. Those checks are made <i>before</i> using those variables. Depending on how do you handle that kind of errors, you should use an exception instead of a plain return, but it depends on how do you need to handle the error. Then, another check is done on the cycle, we check if the obtained stream is a null reference, if it is a null reference, we continue processing the loop, instead of using that null reference. On this method we depend on third party methods that can return null reference, so we <i>must</i> check for them, instead of being sure of their availability. If you are a good observer, you will notice that the method <tt>getPropertyStr()</tt> has a default return value when the parameter is not found, but <i>&ldquo;what happens with those methods without a default return value?&rdquo;</i>.</p>
<pre class="brush: java;">

  public ActionForward execute(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
         throws IOException, ServletException {
    String target = "success";
    String request_arg = request.getParameter("request_arg") == null ?
                         "0" :
                         request.getParameter("request_arg");
    if (form != null) {
      NameForm nameForm = (NameForm)form;
      String name = nameForm.getName() == null ?
                    "" :
                    nameForm.getName();
    }
    if (name == null) {
      target = "failure";
    } else {
      request.setAttribute("name", name);
    }
    request.setAttribute("request_arg",
                         Integer.valueOf(request_arg));
    request.setAttribute("target", target);
    return (mapping.findForward(target));
  }
</pre>
<p>Above we have a typicall struts ActionForward method. It handles a request argument with a default value, using the ternary operator to do that. Checks for the possible null reference that can provide the <tt>request_arg</tt> parameter. The same applies to the form attribute <i>name</i> returned by the <tt>getName</tt> method. Using default values, can help you a lot. Null references are like a ninja waiting patiently to dismember you when are not expecting him. Again we have a method that is <i>a little bit hardened</i>. The same we can apply to our unit tests, we can ensure that they will not fail, for example if we have the following test:</p>
<pre class="brush: java;">
  /**
   * Test Video Info Handling.
   */
  public void testVideoInfo1() {
    System.out.println("testVideoInfo1() Entering ->");
    String streamNames1 = "CHANNEL_TV";
    String directoryName1 = "/home/dmw/tm";
    VideoInfo[] streamsToAdd1 = WowzaTools.getInfoList(streamNames1, directoryName1);
    for (int i = 0; i &lt; streamsToAdd1.length; i++) {
      VideoInfo current = streamsToAdd1[i];
      String msg = "Name: " + current.getVideo().getName()
        + "; Date: " + current.getTime()
        + "; Duration: " + WowzaTools.secondsToMinutes(current.getDuration());
      System.out.println(msg);
    }
    System.out.println("testVideoInfo1() Exiting &gt;-");
  }
</pre>
<p>On this method we are testing the <tt>getInfoList()</tt> method. Since it is a testing class, it is easy enough to change the arguments passed to the <tt>getInfoList()</tt> method. We can pass null references, incorrect arguments and anything we think that can generate an error. We must not <i>trust</i> in the user input. Is easy to change some lines to <i>streamNames1 = null;</i>, <i>streamNames1 = &#8220;xxx&#8221;;</i>, <i>directoryName1 = null;</i>, <i>directoryName1 = &#8220;/dev/null&#8221;;</i>, or whatever can help you to detect possible failures in your code. You will be hardening your code if you can handle more errors which the typicall user can generate. Also, you must request enough time to your project manager to complete code hardening tasks and debugging sessions, which are slow, since you need to trace the code various times. Is not enough to write unit tests, you need to run your tests and debug them, and change every dependent value to ensure that your code is free of flaws. I do not know if project managers are considering code hardening or testing time, usually I just see enough time only to <i>develop</i> software, not to ensure that it will not fail. If you do not have enough time to do those tasks, because your project manager is not measuring that time as part of the development process, your project manager sucks&#8230;</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2011 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2011. | <a href="http://coder.cl/2011/02/code-hardening-techniques/">Permalink</a> | <a href="http://coder.cl/2011/02/code-hardening-techniques/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/02/code-hardening-techniques/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  coder.cl/category/programming/java/feed/ ) in 0.39061 seconds, on Feb 7th, 2012 at 3:01 am UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 7th, 2012 at 4:01 am UTC -->
