<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rafael Chinelato Del Nero on Medium]]></title>
        <description><![CDATA[Stories by Rafael Chinelato Del Nero on Medium]]></description>
        <link>https://medium.com/@rafacdelnero?source=rss-ec833929e293------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KxJXDSnYfjb8JzJ-.</url>
            <title>Stories by Rafael Chinelato Del Nero on Medium</title>
            <link>https://medium.com/@rafacdelnero?source=rss-ec833929e293------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 12:45:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafacdelnero/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Design Patterns Saga #19: Real World Situations with Proxy]]></title>
            <link>https://medium.com/@rafacdelnero/design-patterns-saga-19-real-world-situations-with-proxy-c14c5c98fe7f?source=rss-ec833929e293------2</link>
            <guid isPermaLink="false">https://medium.com/p/c14c5c98fe7f</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Rafael Chinelato Del Nero]]></dc:creator>
            <pubDate>Sun, 05 Nov 2017 19:17:06 GMT</pubDate>
            <atom:updated>2017-11-05T19:17:06.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8qGN7HelPDJlQ1ptt0KDg.png" /></figure><p>To make code flexible and easy to maintain we must find a way to encapsulate and not repeat the code. What if we need to do a specific treatment every time we get an <strong>Exception</strong>? Would we repeat this code in the entire application? We could, but imagine how bad the maintenance would be. It would be much easier to use the power of the <strong>Proxy </strong>pattern. We can use <strong>Reflections </strong>in just one place and make our code<strong> </strong>extremely flexible.</p><p>A very simple example of <strong>Proxy</strong> is, for example, when the company you work for wants to block certain websites. They use <strong>Proxy</strong> to intercept non-work related sites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*8XKunB4LUsh311MU.png" /></figure><p><strong>1 — Interface</strong>: Nothing special here, it’s just the interface to invoke the <strong>Service</strong>.</p><pre>public class InvalidProductException extends RuntimeException {</pre><pre>	private static final long serialVersionUID = -5415448783266469523L;</pre><pre>	@Override<br>	public String getMessage() {<br>		return &quot;Invalid product.&quot;;<br>	}<br>}</pre><p><strong>2 — Specific Exception</strong>: <strong>Exception</strong> to be treated in the <strong>Proxy</strong> class.</p><pre>public class InvalidProductException extends RuntimeException {</pre><pre>	private static final long serialVersionUID = -5415448783266469523L;</pre><pre>	@Override<br>	public String getMessage() {<br>		return &quot;Invalid product.&quot;;<br>	}<br>}</pre><p><strong>3 — Service implementation</strong>: It’s a simulation of a product contract and a very simple verification to see how we can use the <strong>Proxy</strong> pattern.</p><pre>public class ContractProductServiceImpl implements ContractProductService {</pre><pre>	public String contractProduct(Long idProduct) {<br>		if (idProduct &lt; 0) {<br>			throw new InvalidProductException();<br>		}</pre><pre>		return &quot;Product contracted!&quot;;<br>	}</pre><pre>}</pre><p><strong>4 — Proxy</strong>: This is the main class where we intercept the method calls. The first important thing we are doing is the <strong>InvocationHandler</strong> interface implementation.</p><p>There are two crucial methods we use to intercept the methods invocations.</p><p><strong>Object newInstance(Object obj)</strong>: We are using the <strong>Proxy</strong> class from the <strong>Reflection API</strong>. When we instantiate any class by this method, it enables us to always intercept the method invocation.</p><p><strong>Object invoke(Object proxy, Method m, Object[] args)</strong>: It’s the method that will intercept the methods invocations when we use the method above. We are manipulating the actions if we get any <strong>Exception</strong> by any method invocation. We are simply using a <strong>JOptionPane</strong> to show the message that is thrown by any method invocation.</p><pre>public class SecurityProxy implements InvocationHandler {</pre><pre>	private Object obj;</pre><pre>	private SecurityProxy(Object obj) {<br>		this.obj = obj;<br>	}</pre><pre>	public static Object newInstance(Object obj) {<br>		return java.lang.reflect.Proxy.newProxyInstance(obj.getClass()<br>                   .getClassLoader(), obj.getClass().getInterfaces(),<br>				new SecurityProxy(obj));<br>	}</pre><pre>	@Override<br>	public Object invoke(Object proxy, Method m, Object[] args)<br>             throws Throwable {<br>		Object result;<br>		try {<br>			result = m.invoke(obj, args);<br>		} catch (InvocationTargetException e) {<br>			JOptionPane.showMessageDialog(null,<br>                             e.getTargetException()<br>			     .getMessage());</pre><pre>			throw e.getTargetException();<br>		} catch (Exception exception) {<br>			throw new RuntimeException(exception);<br>		}<br>		return result;<br>	}</pre><pre>}</pre><p><strong>5 — Unit Tests</strong>: Let’s check out the use of the <strong>Proxy</strong> pattern now.</p><p><strong>void proxyInvalidProductTest()</strong>: In this test we go through the <strong>InvalidProductException</strong>path. The first thing to understand is that we are creating the instance from the object by the <strong>newInstance</strong> method from the <strong>SecurityProxy</strong> class.</p><p>This is crucial because we need to get the instance from the <strong>SecurityProxy</strong> class to make the <strong>Proxy</strong> invocation work. Once we get the instance from the <strong>newInstance</strong> method then every method invocation will be intercepted.</p><p><strong>void proxyValidProductTest()</strong>: It’s pretty similar to the method above. The method will also be intercepted but the difference is that we are passing a valid id to contract the product.</p><pre>public class ProxyTest {</pre><pre>	public static final long INVALID_PRODUCT_ID = -1;<br>	public static final long VALID_PRODUCT_ID = 1;</pre><pre>	@Test(expected=InvalidProductException.class)<br>	public void proxyInvalidProductTest() {<br>		ContractProductService service =<br>                    (ContractProductService)SecurityProxy<br>		     .newInstance(new ContractProductServiceImpl());</pre><pre>		service.contractProduct(INVALID_PRODUCT_ID);<br>	}</pre><pre>	@Test<br>	public void proxyValidProductTest() {<br>		ContractProductService service =<br>                      (ContractProductService)SecurityProxy<br>		       .newInstance(new ContractProductServiceImpl());</pre><pre>		String result = service.contractProduct(VALID_PRODUCT_ID);</pre><pre>		Assert.assertEquals(&quot;Product contracted!&quot;, result);<br>	}<br>}</pre><p><strong>Summary of actions</strong>:</p><ol><li>Created a simple <strong>Service</strong> to intercept the method.</li><li>Created the <strong>Proxy</strong> class.</li><li>Created the <strong>newInstance</strong> method in the <strong>Proxy</strong> class.</li><li>Created the <strong>invoke</strong> method that does the action in the intercepted methods.</li><li>Created the instance from the <strong>Service</strong> thought the <strong>newInstance</strong> method.</li><li>Intercepted and implemented the actions in the invoke method from the <strong>Proxy</strong>.</li></ol><p>To practice the <strong>Proxy </strong>pattern you can create another rule in the invoke method<strong> </strong>or you can create another Service implementation. It’s crucial to practice. Use <strong>TDD</strong> for this example!</p><p>Get daily tips about the best programming practices <a href="https://twitter.com/RafaDelNero">here</a>!</p><p>Get the FREE ebook:</p><p><a href="http://eepurl.com/cCGHQD">No Bugs, No Stress — Your Step by Step Guide to Creating Life-Changing Software</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c14c5c98fe7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns Saga #19: Real World Situations with Proxy]]></title>
            <link>https://medium.com/@rafacdelnero/design-patterns-saga-19-real-world-situations-with-proxy-f330596c9155?source=rss-ec833929e293------2</link>
            <guid isPermaLink="false">https://medium.com/p/f330596c9155</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Rafael Chinelato Del Nero]]></dc:creator>
            <pubDate>Wed, 18 Oct 2017 17:38:48 GMT</pubDate>
            <atom:updated>2017-10-18T17:38:48.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VvaJ_LqMijqu6R2A6J58w.png" /></figure><p>To make code flexible and easy to maintain we must find a way to encapsulate and not repeat the code. What if we need to do a specific treatment every time we get an <strong>Exception</strong>? Would we repeat this code in the entire application? We could, but imagine how bad the maintenance would be. It would be much easier to use the power of the <strong>Proxy </strong>pattern. We can use <strong>Reflections </strong>in just one place and make our code<strong> </strong>extremely flexible.</p><p>A very simple example of <strong>Proxy</strong> is, for example, when the company you work for wants to block certain websites. They use <strong>Proxy</strong> to intercept non-work related sites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*ToJHRbCx0rTJ5RiB.png" /></figure><p><strong>1 — Interface</strong>: Nothing special here, it’s just the interface to invoke the <strong>Service</strong>.</p><pre>public class InvalidProductException extends RuntimeException {</pre><pre>	private static final long serialVersionUID = -5415448783266469523L;</pre><pre>	@Override<br>	public String getMessage() {<br>		return &quot;Invalid product.&quot;;<br>	}<br>}</pre><p><strong>2 — Specific Exception</strong>: <strong>Exception</strong> to be treated in the <strong>Proxy</strong> class.</p><pre>public class InvalidProductException extends RuntimeException {</pre><pre>	private static final long serialVersionUID = -5415448783266469523L;</pre><pre>	@Override<br>	public String getMessage() {<br>		return &quot;Invalid product.&quot;;<br>	}<br>}</pre><p><strong>3 — Service implementation</strong>: It’s a simulation of a product contract and a very simple verification to see how we can use the <strong>Proxy</strong> pattern.</p><pre>public class ContractProductServiceImpl implements ContractProductService {</pre><pre>	public String contractProduct(Long idProduct) {<br>		if (idProduct &lt; 0) {<br>			throw new InvalidProductException();<br>		}</pre><pre>		return &quot;Product contracted!&quot;;<br>	}</pre><pre>}</pre><p><strong>4 — Proxy</strong>: This is the main class where we intercept the method calls. The first important thing we are doing is the <strong>InvocationHandler</strong> interface implementation.</p><p>There are two crucial methods we use to intercept the methods invocations.</p><p><strong>Object newInstance(Object obj)</strong>: We are using the <strong>Proxy</strong> class from the <strong>Reflection API</strong>. When we instantiate any class by this method, it enables us to always intercept the method invocation.</p><p><strong>Object invoke(Object proxy, Method m, Object[] args)</strong>: It’s the method that will intercept the methods invocations when we use the method above. We are manipulating the actions if we get any <strong>Exception</strong> by any method invocation. We are simply using a <strong>JOptionPane</strong> to show the message that is thrown by any method invocation.</p><pre>public class SecurityProxy implements InvocationHandler {</pre><pre>	private Object obj;</pre><pre>	private SecurityProxy(Object obj) {<br>		this.obj = obj;<br>	}</pre><pre>	public static Object newInstance(Object obj) {<br>		return java.lang.reflect.Proxy.newProxyInstance(obj.getClass()<br>                   .getClassLoader(), obj.getClass().getInterfaces(),<br>				new SecurityProxy(obj));<br>	}</pre><pre>	@Override<br>	public Object invoke(Object proxy, Method m, Object[] args)<br>             throws Throwable {<br>		Object result;<br>		try {<br>			result = m.invoke(obj, args);<br>		} catch (InvocationTargetException e) {<br>			JOptionPane.showMessageDialog(null,<br>                             e.getTargetException()<br>			     .getMessage());</pre><pre>			throw e.getTargetException();<br>		} catch (Exception exception) {<br>			throw new RuntimeException(exception);<br>		}<br>		return result;<br>	}</pre><pre>}</pre><p><strong>5 — Unit Tests</strong>: Let’s check out the use of the <strong>Proxy</strong> pattern now.</p><p><strong>void proxyInvalidProductTest()</strong>: In this test we go through the <strong>InvalidProductException</strong>path. The first thing to understand is that we are creating the instance from the object by the <strong>newInstance</strong> method from the <strong>SecurityProxy</strong> class.</p><p>This is crucial because we need to get the instance from the <strong>SecurityProxy</strong> class to make the <strong>Proxy</strong> invocation work. Once we get the instance from the <strong>newInstance</strong> method then every method invocation will be intercepted.</p><p><strong>void proxyValidProductTest()</strong>: It’s pretty similar to the method above. The method will also be intercepted but the difference is that we are passing a valid id to contract the product.</p><pre>public class ProxyTest {</pre><pre>	public static final long INVALID_PRODUCT_ID = -1;<br>	public static final long VALID_PRODUCT_ID = 1;</pre><pre>	@Test(expected=InvalidProductException.class)<br>	public void proxyInvalidProductTest() {<br>		ContractProductService service =<br>                    (ContractProductService)SecurityProxy<br>		     .newInstance(new ContractProductServiceImpl());</pre><pre>		service.contractProduct(INVALID_PRODUCT_ID);<br>	}</pre><pre>	@Test<br>	public void proxyValidProductTest() {<br>		ContractProductService service =<br>                      (ContractProductService)SecurityProxy<br>		       .newInstance(new ContractProductServiceImpl());</pre><pre>		String result = service.contractProduct(VALID_PRODUCT_ID);</pre><pre>		Assert.assertEquals(&quot;Product contracted!&quot;, result);<br>	}<br>}</pre><p><strong>Summary of actions</strong>:</p><ol><li>Created a simple <strong>Service</strong> to intercept the method.</li><li>Created the <strong>Proxy</strong> class.</li><li>Created the <strong>newInstance</strong> method in the <strong>Proxy</strong> class.</li><li>Created the <strong>invoke</strong> method that does the action in the intercepted methods.</li><li>Created the instance from the <strong>Service</strong> thought the <strong>newInstance</strong> method.</li><li>Intercepted and implemented the actions in the invoke method from the <strong>Proxy</strong>.</li></ol><p>To practice the <strong>Proxy </strong>pattern you can create another rule in the invoke method<strong> </strong>or you can create another Service implementation. It’s crucial to practice. Use <strong>TDD</strong> for this example!</p><p>Get daily tips about the best programming practices <a href="https://twitter.com/RafaDelNero">here</a>!</p><p>Get the FREE ebook:</p><p><a href="http://eepurl.com/cCGHQD">No Bugs, No Stress — Your Step by Step Guide to Creating Life-Changing Software</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f330596c9155" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns Saga #18: Real World Situations with Flyweight]]></title>
            <link>https://medium.com/@rafacdelnero/design-patterns-saga-18-real-world-situations-with-flyweight-8a6a2d94e32f?source=rss-ec833929e293------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a6a2d94e32f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Rafael Chinelato Del Nero]]></dc:creator>
            <pubDate>Wed, 18 Oct 2017 17:01:39 GMT</pubDate>
            <atom:updated>2017-10-18T17:01:39.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plR1qp0S-BKNGmXcX82-Aw.png" /></figure><p>There are some situations in software development in which we need to improve performance. This is possible with the use of <strong>Cache</strong>. Imagine a lot of the same objects being created and wasting memory. The <strong>Flyweight</strong> pattern was created to avoid this problem and optimize performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*c5DciLzPSTaM20Ep.png" /></figure><p>Get the <a href="https://github.com/rafadelnero/design-patterns-saga.git"><strong>Design_Patterns_Saga_GitHub_Source_Code</strong></a></p><p>1 — <strong>POJO</strong>: This is the object we will keep in the <strong>Cache</strong>.</p><pre>class Product {<br>	private final String name;</pre><pre>	public Product(String name) {<br>		this.name = name;<br>	}</pre><pre>	public String toString() {<br>		return name;<br>	}<br>}</pre><p>2 — <strong>Factory (Cache)</strong>: Basically this class is responsible to create the caches.</p><p><strong>lookup(String productName)</strong>: It checks if the product is contained in the map. If it is, we will return the product. If not, we will put the product on the map and return the product.</p><pre>public class Portfolio {<br>	private Map&lt;String, Product&gt; products = new HashMap&lt;String, Product&gt;();</pre><pre>	<em>/**<br>	 * Factory method Pattern<br>	 */</em><br>	public Product lookup(String productName) {<br>		if (!products.containsKey(productName))<br>			products.put(productName, new Product(productName));<br>		return products.get(productName);<br>	}</pre><pre>	public int totalProductsMade() {<br>		return products.size();<br>	}<br>}</pre><p>3 — <strong>Object composer</strong>: It just composes the information from the product to execute the order.</p><pre>public class Order {<br>	private final int orderNumber;<br>	private final Product product;</pre><pre>	Order(int orderNumber, Product product) {<br>		this.orderNumber = orderNumber;<br>		this.product = product;<br>	}</pre><pre>	void processOrder() {<br>		System.out.println(&quot;Ordering &quot; + product +<br>				&quot; for order number &quot; + orderNumber);<br>	}<br>}</pre><p>4 — <strong>Executor</strong>: Here is where the action happens.</p><p><strong>void executeOrder(String productName, int orderNumber)</strong>: It orchestrates the input in the map. If the product is in the map already, it will return the same object. If not, it will put the new information in the map and return it.</p><p><strong>void process()</strong>: It will process all the orders and remove every product.</p><p><strong>int getTotalProducts()</strong>: It will get the total of the registered products.</p><pre>public class InventorySystem {</pre><pre>	private final Portfolio portfolio = new Portfolio();<br>	private final List&lt;Order&gt; orders = new CopyOnWriteArrayList&lt;Order&gt;();</pre><pre>	void executeOrder(String productName, int orderNumber) {<br>		Product product = portfolio.lookup(productName);<br>		Order order = new Order(orderNumber, product);<br>		orders.add(order);<br>	}</pre><pre>	void process() {<br>		for (Order order : orders) {<br>			order.processOrder();<br>			orders.remove(order);<br>		}<br>	}</pre><pre>	int getTotalProducts() {<br>		return portfolio.totalProductsMade();<br>	}<br>}</pre><p><strong>5 — Unit Tests</strong>: Let’s see if the cache is working!</p><p><strong>public void flyweightTest()</strong>: At first we will invoke the <strong>executeOrder</strong> method from the <strong>InventorySystem</strong> and process it. When the products are added it automatically removes the duplication. In the end, we check if there are 3 products and the test passes.</p><p><strong>public void flyweightJavaApiExampleTest()</strong>: There is something curious about Wrappers of Numbers in <strong>Java</strong>. When we use an <strong>Integer</strong> between -127 and 128 there is a <strong>Cache</strong> that maintains those numbers in order to avoid wasted memory.</p><pre>public class FlyweightTest {</pre><pre>	@Test<br>	public void flyweightTest() {<br>		InventorySystem inventory = new InventorySystem();</pre><pre>		inventory.executeOrder(&quot;AlienWare laptop&quot;, 2500);<br>		inventory.executeOrder(&quot;SkullCandy HeadPhones&quot;, 150);<br>		inventory.executeOrder(&quot;Playstation 5&quot;, 500);<br>		inventory.executeOrder(&quot;SkullCandy HeadPhones&quot;, 130);<br>		inventory.executeOrder(&quot;AlienWare laptop&quot;, 3000);<br>		inventory.executeOrder(&quot;Playstation 5&quot;, 600);</pre><pre>		inventory.process();</pre><pre>		Assert.assertEquals(3, inventory.getTotalProducts());<br>	}</pre><pre>	@Test<br>	public void flyweightJavaApiExampleTest() {<br>		Integer firstInt = Integer.valueOf(5);</pre><pre>		Integer secondInt = Integer.valueOf(5);</pre><pre>		Integer thirdInt = Integer.valueOf(10);</pre><pre>		Assert.assertTrue(firstInt == secondInt);<br>		Assert.assertFalse(secondInt == thirdInt);<br>	}</pre><pre>}</pre><p><strong>Summary of actions:</strong></p><ol><li>Created the POJO to keep in the <strong>Cache</strong>.</li><li>Created the auxiliary classes to make the <strong>Flyweight </strong>pattern work.</li><li>Created the map from the <strong>POJO </strong>to get rid of duplication<strong>.</strong></li><li>Map created from the <strong>POJO</strong> without duplications.</li></ol><p>To practice the <strong>Flyweight </strong>pattern you can create another <strong>POJO </strong>and your own implementation to avoid duplication. Practice <strong>TDD</strong> with this example!</p><p>Get daily tips about the best programming practices <a href="https://twitter.com/RafaDelNero">here</a>!</p><p>Get the FREE ebook:</p><p><a href="http://eepurl.com/cCGHQD">No Bugs, No Stress — Your Step by Step Guide to Creating Life-Changing Software</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a6a2d94e32f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns Saga #17: Real World Situations with Decorator]]></title>
            <link>https://medium.com/@rafacdelnero/design-patterns-saga-17-real-world-situations-with-decorator-1ec11ed03aa?source=rss-ec833929e293------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ec11ed03aa</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Rafael Chinelato Del Nero]]></dc:creator>
            <pubDate>Wed, 18 Oct 2017 16:15:36 GMT</pubDate>
            <atom:updated>2017-10-18T16:15:36.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtdKOEwokURMNI2UaSQ9Nw.png" /></figure><p>There are some situations in which we need high flexibility. Let’s consider that we want to create a flexible code for mixing a lot of different pizzas. We would not want to write all the possibilities without a pattern, right? For this reason, we want to use the <strong>Decorator</strong> pattern to gain flexibility, high cohesion, and low coupling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/0*qjAgb0_IjC2Q5P07.png" /></figure><p>Get the <a href="https://github.com/rafadelnero/design-patterns-saga.git"><strong>Design_Patterns_Saga_GitHub_Source_Code</strong></a></p><p><strong>1 — Generic interface (Component)</strong>: It’s the interface with the method that will create all of the objects’ decorations.</p><pre>public interface Pizza {<br>	public String make();<br>}</pre><p><strong>2 — Decorator</strong>: This is the class that makes things happen. It is on the top of all decorator classes and is responsible for decorating the objects.</p><pre>public abstract class PizzaDecorator implements Pizza {</pre><pre>	protected Pizza customPizza;</pre><pre>	public PizzaDecorator(Pizza customPizza) {<br>		this.customPizza = customPizza;<br>	}</pre><pre>	public String make() {<br>		return customPizza.make();<br>	}</pre><pre>}</pre><p><strong>3 — Decorator classes</strong>: These are the classes that will decorate the final pizza. Basically, we will decorate the pizza with the toppings we want in a flexible way.</p><pre>public class TuscanyDecorator extends PizzaDecorator {</pre><pre>	public DressingDecorator(Pizza customPizza) {<br>		super(customPizza);<br>	}</pre><pre>	public String make() {<br>		return customPizza.make() + addTuscany();<br>	}</pre><pre>	private String addTuscany() {<br>		return &quot; + Tuscany&quot;;<br>	}</pre><pre>}</pre><pre>public class MozzarellaDecorator extends PizzaDecorator {</pre><pre>	public MozzarellaDecorator(Pizza customPizza) {<br>		super(customPizza);<br>	}</pre><pre>	public String make() {<br>		return customPizza.make() + addMozzarella();<br>	}</pre><pre>	private String addMozzarella() {<br>		return &quot; + Mozzarella&quot;;<br>	}<br>}</pre><p><strong>4 — Concrete component</strong>: This is the base of the pizza (the dough), the component that will generate different kinds of pizzas.</p><pre>public class SimplePizza implements Pizza {</pre><pre>	@Override<br>	public String make() {<br>		return &quot;Base&quot;;<br>	}<br>}</pre><p><strong>5 — Unit Tests</strong>: It’s test time! Now we will top the pizza in the way we want. We will instantiate the toppings first and then we use the base of the pizza — always passing the object in the constructor of each decorator class. In the end, we invoke the generic make method and the pizza is done!</p><p>Also, there is the <strong>Java API</strong> example with File creation.</p><pre>public class DecoratorTest {</pre><pre>	@Test<br>	public void decoratorTest() {<br>		Pizza pizza = new TuscanyDecorator(<br>				new MozzarellaDecorator(new SimplePizza()));</pre><pre>		Assert.assertEquals(&quot;Base + Mozzarella + Tuscany&quot;<br>                    , pizza.make());<br>	}</pre><pre>	@Test<br>	public void decoratorJavaAPITest() throws IOException {<br>		File file = new File(&quot;./output.txt&quot;);<br>		file.createNewFile();</pre><pre>		OutputStream stream = new FileOutputStream(file);</pre><pre>		DataOutputStream dataStream = new DataOutputStream(stream);<br>		dataStream.writeChars(&quot;text&quot;);<br>		dataStream.close();<br>		stream.close();</pre><pre>		file.delete();<br>	}</pre><pre>}</pre><p><strong>Summary of actions:</strong></p><ol><li>Created the generic interface of the <strong>Component</strong> with the make method.</li><li>Created the <strong>Component</strong> class implementing the generic interface.</li><li>Created the <strong>Decorator</strong> abstract class controlling the decoration.</li><li>Created the <strong>Decorator</strong> concrete classes extending the Decorator.</li><li>Decorated the <strong>Component</strong> joining the classes in the constructor.</li></ol><p>To practice the <strong>Decorator</strong> pattern you can create another <strong>Component</strong> class, for example, a <strong>Sandwich</strong> and decorate your <strong>Sandwich</strong> as you wish. Be sure to use <strong>TDD</strong>(Test Driven Development).</p><p>Get daily tips about the best programming practices <a href="https://twitter.com/RafaDelNero">here</a>!</p><p>Get the FREE ebook:</p><p><a href="http://eepurl.com/cCGHQD">No Bugs, No Stress — Your Step by Step Guide to Creating Life-Changing Software</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ec11ed03aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns Saga #16: Real World Situations with Composite]]></title>
            <link>https://medium.com/@rafacdelnero/design-patterns-saga-16-real-world-situations-with-composite-626d3a73fa9f?source=rss-ec833929e293------2</link>
            <guid isPermaLink="false">https://medium.com/p/626d3a73fa9f</guid>
            <category><![CDATA[sofware-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Rafael Chinelato Del Nero]]></dc:creator>
            <pubDate>Wed, 18 Oct 2017 15:57:06 GMT</pubDate>
            <atom:updated>2017-10-18T15:57:06.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9eNQvNF049z9G0_r9cNALg.png" /></figure><p>Composing objects without a pattern can make code really messy — code repetition happens a lot and maintenance is terrible. Fortunately, there is the <strong>Composite</strong> pattern that solves this problem completely. Using the <strong>Composite</strong> pattern we can encapsulate the code in just one place and compose the object more easily.</p><p>There are some frameworks that use the <strong>Composite </strong>pattern, such as <strong>JSF</strong>. It’s possible to reference all <strong>HTML</strong> components through the component’s classes from <strong>JSF</strong>.</p><p>This is a simple example of <strong>Web</strong> components being composed by the <strong>Composite</strong> pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*yV2kbQcrVqGG-eXt.png" /></figure><p>Get the <a href="https://github.com/rafadelnero/design-patterns-saga.git"><strong>Design_Patterns_Saga_GitHub_Source_Code</strong></a></p><p>1 — <strong>UIComponent</strong> generic class: Every web component will inherit <strong>UIComponent</strong>, so we will be using polymorphism with this abstract class.</p><p>There are some necessary methods to enable the composition of objects.</p><p><strong>add(UIComponent uiComponent)</strong>: Adds any component.</p><p><strong>remove(UIComponent uiComponent)</strong>: Removes any component.</p><p><strong>toString()</strong>: Prints the components code when they are composed.</p><pre>public abstract class UIComponent {</pre><pre>	List&lt;UIComponent&gt; uiComponents = new ArrayList&lt;&gt;();</pre><pre>	public UIComponent add(UIComponent uiComponent) {<br>		throw new UnsupportedOperationException<br>			(&quot;Feature not implemented at this level&quot;);<br>	}</pre><pre>	public UIComponent remove(UIComponent uiComponent) {<br>		throw new UnsupportedOperationException<br>			(&quot;Feature not implemented at this level&quot;);<br>	}</pre><pre>	public abstract String toString();</pre><pre>}</pre><p><strong>2 — Components classes</strong>: These are the classes that will extend <strong>UIComponent</strong>. Basically, they are the actual components.</p><p><strong>Form</strong>: It is a component that will be composed by others. As we developers know, the form tag is vastly used in every web application, so we are going to add components inside the <strong>Form</strong> component.</p><p><strong>InputText</strong>: We are going add <strong>InputText</strong> instances in the <strong>Form</strong> component.</p><p><strong>LabelText</strong>: We are going to add <strong>LabelText</strong> instances in the <strong>Form</strong> component.</p><pre>public class Form extends UIComponent {</pre><pre>	String name;</pre><pre>	public Form(String name) {<br>		this.name = name;<br>	}</pre><pre>	@Override<br>	public UIComponent add(UIComponent uiComponent) {<br>		uiComponents.add(uiComponent);</pre><pre>		return uiComponent;<br>	}</pre><pre>	@Override<br>	public UIComponent remove(UIComponent uiComponent) {<br>		uiComponents.remove(uiComponent);</pre><pre>		return uiComponent;<br>	}</pre><pre>	@Override<br>	public String toString() {<br>		StringBuilder builder = new StringBuilder<br>               (&quot;&lt;form name=&#39;&quot;).append(name).append(&quot;&#39;&gt;&quot;);<br>		uiComponents.forEach(<br>                   e -&gt; builder.append(&quot;\n&quot;).append(e));<br>		builder.append(&quot;\n&lt;/form&gt;&quot;);<br>		return builder.toString();<br>	}<br>}</pre><pre>public class InputText extends UIComponent {</pre><pre>	String name;<br>	String value;</pre><pre>	public InputText(String name, String value) {<br>		this.name = name;<br>		this.value = value;<br>	}</pre><pre>	@Override<br>	public String toString() {<br>		return new StringBuilder(&quot;&lt;inputText name=&#39;&quot;)<br>                .append(name).append(&quot;&#39; value=&#39;&quot;).append(value)<br>                .append(&quot;&#39;/&gt;&quot;).toString();<br>	}<br>}</pre><pre>public class LabelText extends UIComponent {</pre><pre>	String value;</pre><pre>	public LabelText(String value) {<br>		this.value = value;<br>	}</pre><pre>	@Override<br>	public String toString() {<br>		return new StringBuilder(&quot;&lt;label value=&#39;&quot;)                                                                           .append(value).append(&quot;&#39;/&gt;&quot;).toString();<br>	}<br>}</pre><p><strong>3 — Unit Tests</strong>: Let’s use the <strong>Composite</strong> pattern now. We will instantiate and add the other components in the <strong>Form</strong> class. Then we will confirm if the <strong>Components</strong> code is correct with the assertion. There is another test with a composition of <strong>Maps</strong> showing this pattern with <strong>Java API</strong>.</p><pre>public class CompositeTest {</pre><pre>	public static final int EXPECTED_MAP_SIZE = 3;</pre><pre>	@Test<br>	public void compositeTest() {<br>		Form mainForm = new Form(&quot;frmCustomer&quot;);</pre><pre>		LabelText lblCustomerName = new LabelText(&quot;Customer name:&quot;);<br>		InputText txtCustomerName = new InputText(&quot;txtCustomerName&quot;,<br>				&quot;Juggy&quot;);</pre><pre>		LabelText lblCustomerProduct = new LabelText(&quot;Product:&quot;);<br>		InputText txtCustomerProduct = new<br>                InputText(&quot;txtCustomerProduct&quot;, &quot;Alienware laptop&quot;);</pre><pre>		mainForm.add(lblCustomerName);<br>		mainForm.add(txtCustomerName);<br>		mainForm.add(lblCustomerProduct);<br>		mainForm.add(txtCustomerProduct);</pre><pre>		Assert.assertEquals(&quot;&lt;label value=&#39;Customer name:&#39;/&gt;&quot;,<br>				lblCustomerName.toString());<br>		Assert.assertEquals(&quot;&lt;inputText name=&#39;txtCustomerName&#39;&quot; 				<br>                + &quot; value=&#39;Juggy&#39;/&gt;&quot;,<br>				txtCustomerName.toString());<br>		Assert.assertEquals(&quot;&lt;inputText name=&#39;txtCustomerProduct&#39;&quot; 				<br>                 + &quot; value=&#39;Alienware laptop&#39;/&gt;&quot;,<br>				txtCustomerProduct.toString());<br>		Assert.assertEquals(&quot;&lt;label value=&#39;Product:&#39;/&gt;&quot;,<br>				lblCustomerProduct.toString());<br>	}</pre><pre>	@Test<br>	public void javaAPICompositeTest() {<br>		Map&lt;String, String&gt; topWebComponents = new HashMap&lt;&gt;();</pre><pre>		topWebComponents.put(&quot;Component1&quot;, &quot;HTML&quot;);<br>		topWebComponents.put(&quot;Component2&quot;, &quot;InputText&quot;);</pre><pre>		Map&lt;String, String&gt; normalWebComponents = new HashMap&lt;&gt;();</pre><pre>		normalWebComponents.put(&quot;Component3&quot;, &quot;LabelText&quot;);</pre><pre>		Map&lt;String, String&gt; container = new HashMap&lt;&gt;();</pre><pre>		container.putAll(topWebComponents);<br>		container.putAll(normalWebComponents);</pre><pre>		Assert.assertEquals(EXPECTED_MAP_SIZE, container.size());<br>	}</pre><pre>}</pre><p><strong>Summary of actions</strong>:</p><ol><li>Created the <strong>UIComponent </strong>generic class.</li><li>Created add, remove and toString method inside <strong>UIComponent</strong>.</li><li>Created the objects that will be inside the <strong>UIComponent</strong>.</li><li>Composed the objects and printed the code.</li></ol><p>To practice the <strong>Composite </strong>pattern you can create another <strong>Component</strong> class and add inside the <strong>Form</strong> and then print out the code to make the test pass. Be sure to use <strong>TDD (Test Driven Development)</strong>.</p><p>Get daily tips about the best programming practices <a href="https://twitter.com/RafaDelNero">here</a>!</p><p>Get the FREE ebook:</p><p><a href="http://eepurl.com/cCGHQD">No Bugs, No Stress — Your Step by Step Guide to Creating Life-Changing Software</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=626d3a73fa9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DESIGN PATTERNS SAGA #15: REAL PROJECT SITUATIONS WITH STATE]]></title>
            <link>https://medium.com/@rafacdelnero/design-patterns-saga-15-real-project-situations-with-state-f0ce5c40f671?source=rss-ec833929e293------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0ce5c40f671</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rafael Chinelato Del Nero]]></dc:creator>
            <pubDate>Thu, 14 Sep 2017 15:33:03 GMT</pubDate>
            <atom:updated>2017-09-14T15:33:03.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlUtdMZyJ0_d0buGsFCOfw.png" /></figure><p>When it’s necessary to maintain State from an object we can create a big code full of ifs controlling the State from the class. Certainly, this is not the right approach to solve this problem. Repetition of code is what we must avoid, we must follow the DRY (Don’t repeat yourself) principle to keep the code flexible and powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*4eC_rHg6DK5xciJ3.png" /></figure><p>Get the <a href="https://github.com/rafadelnero/design-patterns-saga.git"><strong>Design_Patterns_Saga_GitHub_Source_Code</strong></a></p><p>Let’s first see a bad example of a “<strong>State</strong>” implementation.</p><p>1 — <strong>State Bad Example</strong>: There are two constants, <strong>OPEN</strong> and <strong>CLOSED.</strong> Whenever the openWindow or closeWindow methods are invoked all the rules will be manipulated inside them. As you can see in the code below, there is repetition.</p><pre>public class AutomaticWindow {</pre><pre>	final static int CLOSED = 0;<br>	final static int OPEN = 1;</pre><pre>	int state = CLOSED;</pre><pre>	public AutomaticWindow() {<br>		super();<br>	}</pre><pre>	public void openWindow() {<br>		if (state == OPEN) {<br>			System.out.println(&quot;Window is already open&quot;);<br>		} else if (state == CLOSED) {<br>			System.out.println(&quot;Opening window.&quot;);<br>			state = OPEN;<br>		}<br>	}</pre><pre>	public void closeWindow() {<br>		if (state == OPEN) {<br>			System.out.println(&quot;Closing window.&quot;);<br>			state = CLOSED;<br>		} else if (state == CLOSED) {<br>			System.out.println(&quot;Window is already closed.&quot;);<br>		}<br>	}</pre><pre>	public String toString() {<br>		if (state == OPEN) {<br>			return &quot;Window is open&quot;;<br>		} else {<br>			return &quot;Window is closed&quot;;<br>		}<br>	}<br>}</pre><p>Let’s now see how to use the <strong>State</strong> pattern for real! You will see the difference of a much cleaner and flexible code.</p><p>1 — <strong>State</strong>: It is the generic abstract class that handles the request from any class that must keep the <strong>State</strong>.</p><pre>public abstract class State {</pre><pre>	public abstract void handleRequest();</pre><pre>}</pre><p>2 — <strong>State concrete classes</strong>: They are basically the classes that extend the <strong>State</strong> class. They are responsible for changing the <strong>State</strong> to the next one in the sequence.</p><pre>public class GreenTrafficLightState extends State {</pre><pre>	private TrafficLight trafficLight;</pre><pre>	public GreenTrafficLightState(TrafficLight trafficLight) {<br>		this.trafficLight = trafficLight;<br>	}</pre><pre>	@Override<br>	public void handleRequest() {<br>		System.out.println(&quot;Turning traffic light to yellow.&quot;);<br>		trafficLight.setState(trafficLight.getYellowLightState());<br>	}</pre><pre>	public String toString() {<br>		return &quot;Traffic light is green.&quot;;<br>	}<br>}</pre><pre>public class RedTrafficLightState extends State {</pre><pre>	private TrafficLight trafficLight;</pre><pre>	public RedTrafficLightState(TrafficLight trafficLight) {<br>		this.trafficLight = trafficLight;<br>	}</pre><pre>	@Override<br>	public void handleRequest() {<br>		System.out.println(&quot;Turning traffic light to green...&quot;);<br>		trafficLight.setState(trafficLight.getGreenLightState());<br>	}</pre><pre>	public String toString() {<br>		return &quot;Traffic light is on red.&quot;;<br>	}<br>}</pre><pre>public class YellowTrafficLightState extends State {</pre><pre>	private TrafficLight trafficLight;</pre><pre>	public YellowTrafficLightState(TrafficLight trafficLight) {<br>		this.trafficLight = trafficLight;<br>	}</pre><pre>	@Override<br>	public void handleRequest() {<br>		System.out.println(&quot;Turning traffic light to red.&quot;);<br>		trafficLight.setState(trafficLight.getRedLightState());<br>	}</pre><pre>	public String toString() {<br>		return &quot;Traffic light is yellow.&quot;;<br>	}<br>}</pre><p>3 — <strong>Orchestrator</strong>: This class is responsible for orchestrating the changes of the traffic lights’ <strong>State</strong>. In the constructor, we initialize all the<strong> States</strong> and we pass the same instance in the constructor to each one of the <strong>States</strong> classes. In the changeState method, we just delegate the call to the <strong>State</strong> instance variable to change the <strong>State</strong>.</p><pre>public class TrafficLight {</pre><pre>	State red;<br>	State yellow;<br>	State green;</pre><pre>	State state;</pre><pre>	public TrafficLight() {<br>		red = new RedTrafficLightState(this);<br>		yellow = new YellowTrafficLightState(this);<br>		green = new GreenTrafficLightState(this);</pre><pre>		state = red;<br>	}</pre><pre>	public void changeState() {<br>		state.handleRequest();<br>	}</pre><pre>	public String toString() {<br>		return state.toString();<br>	}</pre><pre>	public State getGreenLightState() {<br>		return green;<br>	}</pre><pre>	public State getYellowLightState() {<br>		return yellow;<br>	}</pre><pre>	public State getRedLightState() {<br>		return red;<br>	}</pre><pre>	public void setState(State state) {<br>		this.state = state;<br>	}<br>}</pre><p>4- <strong>Unit Tests</strong>: Now let’s see if the states are changing as expected. We are expecting that traffic lights change from red to green, yellow to red and so forth. In the window case, we want it to open and close.</p><pre>public class StateTest {</pre><pre>	@Test<br>	public void stateTest() {<br>		TrafficLight trafficLight = new TrafficLight();</pre><pre>		trafficLight.changeState();</pre><pre>		trafficLight.changeState();</pre><pre>		trafficLight.changeState();</pre><pre>		trafficLight.changeState();</pre><pre>		Assert.assertEquals(trafficLight.state.getClass(),<br>				GreenTrafficLightState.class);<br>	}</pre><pre>	@Test<br>	public void badExampleStateTest() {<br>		AutomaticWindow automaticWindow = new AutomaticWindow();</pre><pre>		automaticWindow.openWindow();</pre><pre>		automaticWindow.closeWindow();</pre><pre>		Assert.assertEquals(automaticWindow.toString(),<br>				&quot;Window is closed&quot;);<br>	}</pre><pre>}</pre><p><strong>Summary of actions</strong>:</p><ol><li>Created the <strong>State </strong>abstract generic class.</li><li>Created the <strong>State</strong> classes that extend the <strong>State</strong> class.</li><li>Implemented the <strong>handleRequest </strong>method from the <strong>State</strong> class.</li><li>Created the <strong>TrafficLight</strong> class to manipulate the <strong>States</strong>.</li><li>Created the <strong>changeState</strong> method in the <strong>TrafficLight</strong> class.</li></ol><p>To practice the <strong>State Pattern</strong> you can create another State class with another scenario, for example changing any light state or anything else. Keep in mind that practicing the Patterns is crucial to fully master them. Be sure to use <strong>TDD (Test Driven Development)</strong>.</p><p>Get daily tips about the best programming practices <a href="https://twitter.com/RafaDelNero">here</a>!</p><p>Get the FREE ebook:</p><p><a href="http://eepurl.com/cCGHQD">No Bugs, No Stress — Your Step by Step Guide to Creating Life-Changing Software</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0ce5c40f671" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DESIGN PATTERNS SAGA #13: REAL PROJECT SITUATIONS WITH MEMENTO]]></title>
            <link>https://medium.com/@rafacdelnero/design-patterns-saga-13-real-project-situations-with-memento-36ca9b1a4971?source=rss-ec833929e293------2</link>
            <guid isPermaLink="false">https://medium.com/p/36ca9b1a4971</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Rafael Chinelato Del Nero]]></dc:creator>
            <pubDate>Wed, 06 Sep 2017 21:05:49 GMT</pubDate>
            <atom:updated>2017-09-06T21:05:49.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nD2R5Cz7p4fdYwumqc3Ww.png" /></figure><p>What if we need to keep many different states of an object? We could keep the information inside objects with a lot of setters and make the code a big mess. This would indeed work but it would be awful to change anything in the future. As we developers know, software that does not change is dead.</p><p>When we need to manipulate different states of an object we can use the <strong>MementoPattern</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*UNid4SvH--v_F00L.png" /></figure><p>Get the <a href="https://github.com/rafadelnero/design-patterns-saga.git"><strong>Design_Patterns_Saga_GitHub_Source_Code</strong></a></p><p>1 — <strong>Memento</strong>: Nothing special here, it is just the object information we encapsulated in order to keep only part of the <strong>Customer </strong>information.</p><pre>public class CustomerMemento {</pre><pre>	private String name;<br>	private String phone;</pre><pre>	public CustomerMemento(String name, String phone) {<br>		this.name = name;<br>		this.phone = phone;<br>	}</pre><pre>        <em>// Getters and setters, hashcode and equals omitted.</em></pre><pre>}</pre><p>2 — <strong>Caretaker</strong>: it encapsulates the <strong>Memento</strong> object history in a <strong>Stack</strong>.</p><p>Methods:</p><p><strong>save</strong>: it saves the state of the <strong>CustomerMemento</strong> object, pushing it to the top of the <strong>Stack</strong>.</p><p><strong>revert</strong>: it reverts the state of the <strong>CustomerMemento</strong> to the last saved state.</p><pre>public class Caretaker {</pre><pre>	private Stack&lt;CustomerMemento&gt; customerHistory = new Stack&lt;&gt;();</pre><pre>	public void save(Customer customer) {<br>		customerHistory.push(customer.save());<br>	}</pre><pre>	public void revert(Customer customer) {<br>		customer.revert(customerHistory.pop());<br>	}</pre><pre>}</pre><p>3 — <strong>Originator</strong>: This is the main <strong>Customer</strong> object, the <strong>Originator</strong> of the information. There are two important methods here:</p><p><strong>save</strong>: sets the <strong>name</strong> and <strong>phone</strong> from the <strong>Customer</strong> in the <strong>CustomerMemento</strong> object and returns the <strong>CustomerMemento</strong>.</p><p><strong>revert</strong>: it reverts the <strong>Customer</strong> with the <strong>CustomerMemento</strong> information.</p><pre>public class Customer implements Serializable {</pre><pre>	private static final long serialVersionUID = 574314732983681621L;<br>	private String name;<br>	private String address;<br>	private String phone;</pre><pre>	public Customer(String name, String address, String phone) {<br>		this.name = name;<br>		this.address = address;<br>		this.phone = phone;<br>	}</pre><pre>        public CustomerMemento save() {<br>		return new CustomerMemento(name, phone);<br>	}</pre><pre>	public void revert(CustomerMemento customer) {<br>		this.name = customer.getName();<br>		this.phone = customer.getPhone();<br>	}</pre><pre>        <em>// Getters and setters, hashcode and equals omitted.</em><br>}</pre><p><strong>Summary of actions</strong>:</p><ol><li>Created the <strong>Memento </strong>class with the necessary information.</li><li>Created the <strong>Caretaker </strong>class.</li><li>Declared the <strong>Stack</strong> to keep the <strong>Memento</strong> information into the <strong>Caretaker</strong>.</li><li>Created the <strong>Originator</strong> class with all the <strong>Customer’s</strong> information.</li><li>Created the <strong>save</strong> method that returns the <strong>CustomerMemento</strong> object.</li><li>Created the <strong>revert</strong> method to put <strong>CustomerMemento</strong> information into <strong>Customer</strong>.</li></ol><p>To practice the <strong>Memento Pattern</strong> you can create other <strong>Caretaker</strong>, <strong>Originator </strong>and<strong> Memento</strong> classes and make it work. Create another test method to make sure it works. Be sure to use <strong>TDD (Test Driven Development)</strong>.</p><p>Get daily tips about the best programming practices <a href="https://twitter.com/RafaDelNero">here</a>!</p><p>Get the <strong>FREE </strong>ebook:</p><p><a href="http://eepurl.com/cCGHQD">No Bugs, No Stress — Your Step by Step Guide to Creating Life-Changing Software</a></p><p>See you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36ca9b1a4971" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DESIGN PATTERNS SAGA #14: REAL PROJECT SITUATIONS WITH VISITOR]]></title>
            <link>https://medium.com/@rafacdelnero/design-patterns-saga-14-real-project-situations-with-visitor-b58fee08c786?source=rss-ec833929e293------2</link>
            <guid isPermaLink="false">https://medium.com/p/b58fee08c786</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Rafael Chinelato Del Nero]]></dc:creator>
            <pubDate>Wed, 06 Sep 2017 20:36:44 GMT</pubDate>
            <atom:updated>2017-09-06T20:36:44.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdp8Z9znhwlo4F8eRz-lbg.png" /></figure><p>Sometimes we need to implement different methods for a <strong>POJO</strong> with different business requirements. We could certainly create several methods inside the <strong>POJO</strong> but we would not be utilizing the main benefits of powerful code — cohesion and low coupling. When we want to encapsulate different business requirements inside a cohesive class we can use the <strong>Visitor Pattern</strong>!</p><p>Basically, when using <strong>Visitor Pattern</strong> we encapsulate the business requirements inside the <strong>Visitor</strong> classes making our code very flexible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rtu7BIxWA3BXRikM.png" /></figure><p>Get the <a href="https://github.com/rafadelnero/design-patterns-saga.git"><strong>Design_Patterns_Saga_GitHub_Source_Code</strong></a></p><p>Let’s see a bad example of code if we aren’t using the <strong>Visitor Pattern</strong>.</p><p>1 — <strong>Generic Interface</strong>: It’s basically the interface that declares the main method to calculate shipping.</p><pre>public interface CardDevice {<br>	public double calculateShipping();<br>}</pre><p>2 — <strong>Business POJOs</strong>: Now we have all the POJOs implementing the Generic interface in order to define the behavior to calculate shipping.</p><pre>public class Mobile implements CardDevice {<br>	@Override<br>	public double calculateShipping() {<br>		return 6;<br>	}<br>}</pre><pre>public class WiredPos implements CardDevice {<br>	@Override<br>	public double calculateShipping() {<br>		return 9;<br>	}<br>}</pre><pre>public class WirelessPos implements CardDevice {<br>	@Override<br>	public double calculateShipping() {<br>		return 7;<br>	}<br>}</pre><p>3 — <strong>Invoker</strong>: Now we can see the problem. We have the code very coupled with the specific calculateShipping method.</p><pre>public class CardDeviceOrder implements CardDevice {</pre><pre>	private List&lt;CardDevice&gt; cardDevices = new ArrayList&lt;&gt;();</pre><pre>	public CardDeviceOrder() {<br>		super();<br>	}</pre><pre>	public void addPart(CardDevice cardDevice) {<br>		cardDevices.add(cardDevice);<br>	}</pre><pre>	public List&lt;CardDevice&gt; getCardDevices() {<br>		return Collections.unmodifiableList(cardDevices);<br>	}</pre><pre>	public double calculateShipping() {<br>		double shippingCost = 0;<br>		for (CardDevice cardDevice : cardDevices) {<br>			shippingCost += cardDevice.calculateShipping();<br>		}<br>		return shippingCost;<br>	}</pre><pre>}</pre><p>4 — <strong>Unit Test</strong>: Let’s see if the calculateShipping method is working:</p><pre>public class BadExampleVisitorTest {</pre><pre>	public static final double EXPECTED_SHIPPING_COST = 22.0;</pre><pre>	@Test<br>	public void visitorBadExampleTest() {<br>		CardDeviceOrder order = new CardDeviceOrder();<br>		order.addPart(new Mobile());<br>		order.addPart(new WiredPos());<br>		order.addPart(new WirelessPos());</pre><pre>		double shippingCost = order.calculateShipping();</pre><pre>		Assert.assertTrue(EXPECTED_SHIPPING_COST == shippingCost);<br>	}</pre><pre>}</pre><p>Now let’s see the same example using the <strong>Visitor</strong> Pattern. Now you will realize that we will have more flexibility in the code.</p><p>1 — <strong>Visitor interface</strong>: We are going to define every business requirement inside this <strong>Visitor</strong>in order to manipulate these rules in an uncoupled mode. We are going to implement the rules inside the <strong>Visitor</strong> implementation.</p><pre>public interface CardDeviceVisitor {<br>	void visit(WirelessPos wirelessPos);<br>	void visit(Mobile mobile);<br>	void visit(WiredPos wiredPos);<br>	void visit(CardDeviceOrder cardDeviceOrder);<br>}</pre><p>2 — <strong>Visitor implementations</strong>: You will realize that the business requirements are implemented directly in the <strong>Visitor</strong> classes. They implement the <strong>Visitor</strong> generic interface and execute what is necessary for the business.</p><p><strong>CardDeviceDisplayVisitor</strong>: Displays basic device information.</p><p><strong>CardDeviceShippingVisitor</strong>: Calculates the shipping from each card device.</p><pre>public class CardDeviceDisplayVisitor implements CardDeviceVisitor {</pre><pre>	@Override<br>	public void visit(WirelessPos wirelessPos) {<br>		System.out.println(&quot;We have a: &quot; +  wirelessPos);<br>	}</pre><pre>	@Override<br>	public void visit(Mobile mobile) {<br>		System.out.println(&quot;We have a: &quot; + mobile);<br>	}</pre><pre>	@Override<br>	public void visit(WiredPos wiredPos) {<br>		System.out.println(&quot;We have: &quot; + wiredPos);<br>	}</pre><pre>	@Override<br>	public void visit(CardDeviceOrder cardDeviceOrder) {<br>		System.out.println(&quot;We have an: &quot;+ cardDeviceOrder);<br>	}</pre><pre>}</pre><pre>public class CardDeviceShippingVisitor implements CardDeviceVisitor {</pre><pre>	double shippingValue = 0;</pre><pre>	@Override<br>	public void visit(WirelessPos wirelessPos) {<br>		System.out.println(&quot;Calculating Wireless Pos shipping.&quot;);<br>		shippingValue += 15;<br>	}</pre><pre>	@Override<br>	public void visit(Mobile mobile) {<br>		System.out.println(&quot;Calculating Mobile shipping&quot;);<br>		shippingValue += 3;<br>	}</pre><pre>	@Override<br>	public void visit(WiredPos wiredPos) {<br>		System.out.println(&quot;Calculating Wired Pos shipping.&quot;);<br>		shippingValue += 9;<br>	}</pre><pre>	@Override<br>	public void visit(CardDeviceOrder order) {<br>		System.out.println(&quot;If they bought more than 3 things &quot;<br>				+ &quot;there will be a discount in the shipping.&quot;);<br>		List&lt;CardDevice&gt; cardDevices = order.getCardDevices();<br>		if (cardDevices.size() &gt; 3) {<br>			shippingValue -= 5;<br>		}<br>		System.out.println(&quot;Shipping amount is: &quot; + shippingValue);<br>	}</pre><pre>	public double getShippingValue() {<br>		return shippingValue;<br>	}<br>}</pre><p>3 — <strong>Business POJOs</strong>: We can clearly see that the <strong>POJOs</strong> are already different. They are not invoking the method to execute the specific business requirements. Now we invoke a method from a generic visitor. It decouples the code and the business requirement is manipulated inside the <strong>Visitor</strong>. Check it out:</p><pre>public class Mobile implements CardDevice {<br>	@Override<br>	public void accept(CardDeviceVisitor visitor) {<br>		visitor.visit(this);<br>	}<br>}</pre><pre>public class WiredPos implements CardDevice {<br>	@Override<br>	public void accept(CardDeviceVisitor visitor) {<br>		visitor.visit(this);<br>	}<br>}</pre><pre>public class WirelessPos implements CardDevice {<br>	@Override<br>	public void accept(CardDeviceVisitor visitor) {<br>		visitor.visit(this);<br>	}<br>}</pre><p>4 — <strong>Orchestrator, Invoker</strong>: The <strong>CardDeviceOrder</strong> class is responsible for orchestrating the cardDevices classes and invoking every method from the <strong>Visitors</strong> according to the specific <strong>Visitor</strong> class implementation.</p><pre>public class CardDeviceOrder implements CardDevice {</pre><pre>	private List&lt;CardDevice&gt; cardDevices = new ArrayList&lt;&gt;();</pre><pre>	public CardDeviceOrder() {<br>		super();<br>	}</pre><pre>	public void addPart(CardDevice cardDevice) {<br>		cardDevices.add(cardDevice);<br>	}</pre><pre>	public List&lt;CardDevice&gt; getCardDevices() {<br>		return Collections.unmodifiableList(cardDevices);<br>	}</pre><pre>	@Override<br>	public void accept(CardDeviceVisitor visitor) {<br>		for (CardDevice cardDevice : cardDevices) {<br>			cardDevice.accept(visitor);<br>		}<br>		visitor.visit(this);<br>	}<br>}</pre><p>5 — <strong>Unit Tests</strong>: Let’s test our <strong>Visitors</strong>! You will see the business methods being invoked through the <strong>Visitor</strong> classes.</p><p>First, add all the devices to the list of <strong>CardDeviceOrder</strong>.</p><p>Second, instantiate both visitors and pass them into the accept method from <strong>CardDeviceOrder</strong>.</p><p>Third, confirm the calculated shipping value is correct.</p><pre>public class GoodExampleVisitorTest {</pre><pre>	public static final double EXPECTED_SHIPPING_COST = 27.0;</pre><pre>	@Test<br>	public void visitorGoodExampleTest() {<br>		CardDeviceOrder order = new CardDeviceOrder();<br>		order.addPart(new WirelessPos());<br>		order.addPart(new Mobile());<br>		order.addPart(new WiredPos());</pre><pre>		CardDeviceShippingVisitor shipping<br>			= new CardDeviceShippingVisitor();</pre><pre>		order.accept(shipping);<br>		order.accept(new CardDeviceDisplayVisitor());</pre><pre>		Assert.assertTrue(EXPECTED_SHIPPING_COST ==<br>				shipping.getShippingValue());<br>	}</pre><pre>}</pre><p><strong>Summary of actions</strong>:</p><ol><li>Created the <strong>Visitor </strong>generic interface.</li><li>Implemented the <strong>Visitor</strong> classes with the necessary business requirements.</li><li>Created the business <strong>POJOs</strong> delegating responsibilities to the <strong>Visitor</strong> classes.</li><li>Created the orchestrator class responsible to manipulate the invocations.</li></ol><p>To practice the <strong>Visitor Pattern</strong> you can create another <strong>Visitor</strong> class with another specific business requirement, for example calculating the rent from every card device. Create another test method to make sure it works. Be sure to use <strong>TDD (Test Driven Development)</strong>.</p><p>Get daily tips about the best programming practices <a href="https://twitter.com/RafaDelNero">here</a>!</p><p>Get the <strong>FREE </strong>ebook:</p><p><a href="http://eepurl.com/cCGHQD">No Bugs, No Stress — Your Step by Step Guide to Creating Life-Changing Software</a></p><p>See you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b58fee08c786" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DESIGN PATTERNS SAGA #12: REAL PROJECT SITUATIONS WITH MEDIATOR]]></title>
            <link>https://medium.com/@rafacdelnero/design-patterns-saga-12-real-project-situations-with-mediator-a6f9f627d2e5?source=rss-ec833929e293------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6f9f627d2e5</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Rafael Chinelato Del Nero]]></dc:creator>
            <pubDate>Fri, 25 Aug 2017 19:51:36 GMT</pubDate>
            <atom:updated>2017-08-25T19:51:36.038Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5aMvWT-N9SpyfzxLKTsYfQ.png" /></figure><p>What should be done when we need to use a functionality that may be repeated in several classes? Should we repeat the code in all the classes? If the behavior of this functionality changes, you will be obligated to change it in the entire project and test everything. This would not be cool. Fortunately, there is a solution for this problem — we can use the <strong>Mediator Pattern</strong>!</p><p>Using the<strong> Mediator Pattern</strong> can encapsulate this behavior inside just one class allowing us to reuse this method in every necessary class. Doing this will result in cohesive code with low coupling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*Tj83tEdZBFoMQcJ2.png" /></figure><p>1 — <strong>Mediator</strong>: This class will be responsible to mediate the necessary behavior of calculating the Discount. This pattern is pretty straightforward, it simply mediates functionality.</p><pre>public class DiscountCalculatorMediator {</pre><pre>	private BigDecimal productValue;</pre><pre>	private BigDecimal DISCOUNT_RATE = new BigDecimal(&quot;0.10&quot;);</pre><pre>	public DiscountCalculatorMediator(BigDecimal productValue) {<br>		this.productValue = productValue;<br>	}</pre><pre>	public BigDecimal calculate() {<br>		return productValue.<br>                  subtract(productValue.multiply(DISCOUNT_RATE));<br>	}</pre><pre>}</pre><p>2 — <strong>Product POJO</strong>: We are going to mediate the <strong>calculateDiscount</strong> method to the <strong>Mediator </strong>class, and therefore we are not going to have the same code in different parts of the system. We will have this code only in the <strong>Mediator</strong>.</p><pre>public class Product {</pre><pre>	private BigDecimal productValue;</pre><pre>	public Product(BigDecimal productValue) {<br>		this.productValue = productValue;<br>	}</pre><pre>	public BigDecimal calculateDiscount() {<br>		return new DiscountCalculatorMediator<br>                  (productValue).calculate();<br>	}</pre><pre>}</pre><p><strong>Summary of actions</strong>:</p><ol><li>Created the <strong>Mediator </strong>class.</li><li>Created the <strong>calculateDiscount</strong> behavior inside the <strong>Mediator</strong>.</li><li>Reused the <strong>Mediator </strong>in the <strong>POJO</strong>.</li></ol><p>To practice the <strong>Mediator Pattern</strong> you can create another <strong>Mediator</strong> class where you encapsulate a specific behavior and just reuse it in a method. Create another test method to make sure it works. Be sure to use <strong>TDD (Test Driven Development)</strong>.</p><p>Get daily tips about the best programming practices <a href="https://twitter.com/RafaDelNero">here</a>!</p><p>Get the <strong>FREE </strong>ebook:</p><p><a href="http://eepurl.com/cCGHQD">No Bugs, No Stress — Your Step by Step Guide to Creating Life-Changing Software</a></p><p>See you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6f9f627d2e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DESIGN PATTERNS SAGA #11: REAL PROJECT SITUATIONS WITH ITERATOR]]></title>
            <link>https://medium.com/@rafacdelnero/design-patterns-saga-11-real-project-situations-with-iterator-bae9bdab3a47?source=rss-ec833929e293------2</link>
            <guid isPermaLink="false">https://medium.com/p/bae9bdab3a47</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Rafael Chinelato Del Nero]]></dc:creator>
            <pubDate>Fri, 18 Aug 2017 21:10:18 GMT</pubDate>
            <atom:updated>2017-08-18T21:10:18.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sp2wVTxNSshwFvtYEFVAHQ.png" /></figure><p>Most of the time we use the <strong>Iterator</strong> from the <strong>Collections API</strong>. It’s very important to know how to implement a customized <strong>Iterator</strong> in order to understand what is happening behind the scenes. If we read <strong>Java</strong> source code, for example, we are going to find out that the elements from <strong>ArrayList </strong>are actually manipulated in a normal array. If we read <strong>Java</strong> source code we can greatly improve our programming skills. I strongly recommend that you make this a habit.</p><p><strong>Iterator diagram</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*TzM8SvVeSm1P5akp.png" /></figure><p>Get the <a href="https://github.com/rafadelnero/design-patterns-saga.git"><strong>Design_Patterns_Saga_GitHub_Source_Code</strong></a></p><p>1 — <strong>Iterator</strong>: This is the main class where we are able to iterate the objects. The first detail to be aware of is that we are implementing the <strong>Iterable</strong> interface using <strong>String</strong> as a generic type.</p><p>We are declaring an array of products and the index.</p><p>In the constructor, we are initializing the array of products with the size of 10 and assigning zero to the index.</p><p>In the <strong>add</strong> method, we are adding a new element inside the array. We simply check if the index is the same size as the initial size of the array, in this case, 10. If so, we are going to make the array 5 times larger than before. Following this process, we copy the old array information to the <strong>largerArray</strong>. Finally, we add the product to the final array.</p><p>In the <strong>iterator</strong> method, we are using an <strong>anonymous inner class</strong> that implements <strong>Iterator</strong>. If we are using the <strong>Iterator</strong> interface we must implement all of its methods.</p><p>Again, we are declaring the index to control the iteration.</p><p>Let’s see what happens on the <strong>Iterator</strong> methods:</p><p><strong>hasNext</strong>: verifies if there is another element to be iterated. If the index from the <strong>iterator</strong> is lower than the size of the array and the element is different from null it means we have the next element.</p><p><strong>next</strong>: gets the next element from the products. It simply refers to the next element from the array and returns it.</p><p><strong>remove</strong>: it copies the old array without the removed position, returning the removed element.</p><pre>public class ProductRepository implements Iterable {</pre><pre>	private String[] products;<br>	private int index;</pre><pre>	public ProductRepository() {<br>		products = new String[10];<br>		index = 0;<br>	}</pre><pre>	public void add(String product) {<br>		if (index == products.length) {<br>			String[] largerProducts = new String[<br>                            products.length + 5];<br>			System.arraycopy(products, 0, largerProducts,<br>                            0, products.length);<br>			products = largerProducts;<br>			largerProducts = null;<br>		}</pre><pre>		products[index++] = product;<br>	}</pre><pre>	@Override<br>	public Iterator iterator() {<br>		return new Iterator() {</pre><pre>			private int currentIndex = 0;</pre><pre>			@Override<br>			public boolean hasNext() {<br>				return currentIndex &lt; products.length<br>                                  &amp;&amp; products[currentIndex] != null;<br>			}</pre><pre>			@Override<br>			public String next() {<br>				return products[currentIndex++];<br>			}</pre><pre>			@Override<br>			public void remove() {<br>				System.arraycopy(products, currentIndex + 1,<br>                                  products, currentIndex, products.length - 1);<br>			}</pre><pre>		};<br>	}<br>}</pre><p>2 — <strong>Unit Test</strong>: Now we are going to test the <strong>Iterator</strong>.</p><p><strong>customIteratorTest</strong>: we add some elements, we get the iterator, remove two elements and check if the remaining element is “Tablet”.</p><p><strong>javaAPIIteratorTest</strong>: we are just using the <strong>iterator</strong> from the <strong>Java Collections API</strong>, removing all the elements and checking if the <strong>Set</strong> <strong>Collection</strong> is empty.</p><pre>public class IteratorTest {</pre><pre>	@Test<br>	public void customIteratorTest() {<br>		ProductRepository repo = new ProductRepository();</pre><pre>		repo.add(&quot;Guitar&quot;);<br>		repo.add(&quot;Notebook&quot;);<br>		repo.add(&quot;Tablet&quot;);</pre><pre>		Iterator productIterator = repo.iterator();<br>		productIterator.remove();<br>		productIterator.remove();</pre><pre>		Assert.assertEquals(productIterator.next(), &quot;Tablet&quot;);<br>	}</pre><pre>	@Test<br>	public void javaAPIIteratorTest() {<br>		Set simpsons = new HashSet&lt;&gt;();</pre><pre>		simpsons.add(&quot;Homer&quot;);<br>		simpsons.add(&quot;Bart&quot;);<br>		simpsons.add(&quot;Margie&quot;);</pre><pre>		Iterator simpsonsItr = simpsons.iterator();</pre><pre>		while (simpsonsItr.hasNext()) {<br>			String name = simpsonsItr.next();<br>			System.out.println(name);<br>			simpsonsItr.remove();<br>		}</pre><pre>		Assert.assertEquals(0, simpsons.size());<br>	}</pre><pre>}</pre><p><strong>Summary of actions</strong>:</p><ol><li>Created the <strong>Iterator</strong> class.</li><li>Encapsulated an array inside the <strong>Iterator</strong> class.</li><li>Implemented the <strong>Iterable</strong> interface in the <strong>Iterator</strong> class.</li><li>Overrode the <strong>iterator</strong> method.</li><li>Created an <strong>anonymous inner class</strong> of the <strong>Iterator</strong> type.</li><li>Overrode all the methods from the <strong>Iterator</strong> interface.</li></ol><p>To practice the <strong>Iterator Pattern</strong> you can create another Repository and iterate over the elements from it. Create another test method to make sure it works. Be sure to use <strong>TDD (Test Driven Development)</strong>.</p><p>Get daily tips about the best programming practices <a href="https://twitter.com/RafaDelNero">here</a>!</p><p>Get the <strong>FREE </strong>ebook:</p><p><a href="http://eepurl.com/cCGHQD">No Bugs, No Stress — Your Step by Step Guide to Creating Life-Changing Software</a></p><p>See you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bae9bdab3a47" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>