Wednesday, September 24, 2014

How to run junit tests inside the android project

Hi there!

Today i'm gonna show you how to create and run junit tests inside your android project without creating a separated test project. With those tests we will rapidly be able to automate and test the app's logic and some simple UI behaviors. The example below is very straightforward and much more intuitive than other approaches i saw out there.

Defining the TestInstrumentation 

First of all, define in your manifest file the following entries. IMPORTANT: While the definition of the test instrumentation will be placed outside your application tag, the test runner must be defined  inside your application tag.




< manifest >
...
< instrumentation 
  android:name="android.test.InstrumentationTestRunner"
  android:targetPackage="com.treslines.ponto" 
/ >
< / manifest >
< application >
...
< uses-library android:name="android.test.runner" / >
...
< / application >

Creating the test packages

Android works with some conventions while testing. So it is extremelly important to follow those conventions. Otherwise you'll get compile or run errors while trying to run it. One convention is that all tests for a specific class must be placed in the same package structure but with a futher sub-folder called test as you can see below. Because i want to test the activities in the package com.treslines.ponto.activity i must create a test package called com.treslines.ponto.activity.test



Creating the test itself

That's the cool part of it. Here you can write your junit tests as usual. Again android  gives us some conventions to follow. All test classes must have the same name as the class under test with the suffix Test on it. And all test methods must start with the prefix test on it. If you follow those conventions everything will work just fine.

// IMPORTANT: All test cases MUST have a suffix "Test" at the end
//
// THAN:
// Define this in your manifest outside your application tag:
//  < instrumentation 
//    android:name="android.test.InstrumentationTestRunner"
//    android:targetPackage="com.treslines.ponto" 
//  / >
//
// AND:
// Define this inside your application tag:
//  < uses-library android:name="android.test.runner" / >
//
// The activity you want to test will be the "T" type of ActivityInstrumentationTestCase2
public class AlertaActivityTest extends ActivityInstrumentationTestCase2 < AlertaActivity > {

 private AlertaActivity alertaActivity;
 private AlertaController alertaController;

 public AlertaActivityTest() {
  // create a default constructor and pass the activity class
  // you want to test to the super() constructor
  super(AlertaActivity.class);
 }

 @Override
 // here is the place to setup the var types you want to test
 protected void setUp() throws Exception {
  super.setUp();
  
  // because i want to test the UI in the method testAlertasOff()
  // i must set this attribute to true
  setActivityInitialTouchMode(true);

  // init variables
  alertaActivity = getActivity();
  alertaController = alertaActivity.getAlertaController();
 }

 // usually we test some pre-conditions. This method is provided
 // by the test framework and is called after setUp()
 public void testPreconditions() {
  assertNotNull("alertaActivity is null", alertaActivity);
  assertNotNull("alertaController is null", alertaController);
 }

 // test methods MUST start with the prefix "test"
 public void testVibrarSomAlertas() {
  assertEquals(true, alertaController.getView().getVibrar().isChecked());
  assertEquals(true, alertaController.getView().getSom().isChecked());
  assertEquals(true, alertaController.getView().getAlertas().isChecked());
 }

 // test methods MUST start with the prefix "test"
 public void testAlertasOff() {
  Switch alertas = alertaController.getView().getAlertas();
  // because i want to simulate a click on a view, i must use the TouchUtils
  TouchUtils.clickView(this, alertas);
  // wait a little (1.5sec) because the UI needs its time
  // to change the switch's state and than check new state of the switches
  new Handler().postDelayed(new Runnable() {
   @Override
   public void run() {
    assertEquals(false, alertaController.getView().getVibrar().isChecked());
    assertEquals(false, alertaController.getView().getSom().isChecked());
   }
  }, 1500);
 }
}

Running the JUnit tests

The only difference while running junit test in android is that you'll be calling Run As > Android JUnit Test instead of just JUnit Test like you are used to in java.


That's all! Hope you like it! :)

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Monday, September 8, 2014

how to import/parse or create json/gson as arraylist from strings.xml in android?

Hi there!

Today i'm gonna show to you, how we can profit from the existing Gson library while dealing with array lists in the string.xml file. The benefits of it is that can define as many strings.xml entries as we need and import/parse the whole list structures almost without any effort.

Gson library

download the Gson library from here Gson 2.2.4. Don't worry about the "deprecated" tag. It is not really deprecated. Only parts of it acc. to its developer. We can continue using it. Than unzip it and cut/paste the following jar (gson-2.2.4.jar) in the libs folder from your project.

Json sample

Open your strings.xml file and copy/paste this line sample entry in it(It is a representation of an array list of Points with x and y coordinates):

 < string name="point_array" > {\"points\":[{\"x\": 255,\"y\": 689},{\"x\": 199,\"y\": 658}< / string > 

Defining a Data Container

You'll need a data container to hold the read points. So lets define a structure for it.
           
public class PointContainer {
    private List < Point > points;
    public List < Point > getPoints() {return points;}
    public void setPoints(List < Point > points) {this.points = points;}
}

Usage of the Gson lib

With the Gson lib, import/parse the array into a json structure. The benefits of it is that can define as many strings.xml entries as you need and import the whole list structure almost without any effort.
           
    String pointArray = getResources().getString(R.string.point_array);
    PointContainer pointContainer = new Gson().fromJson(pointArray, PointContainer.class);
    List < Point > points = pointContainer.getPoints();
    // do something with the data here...

Reading List of Lists

Here it gets more tricky. Offen we will need to read a list of list from json format into java code. To do so, lets see how it works by writing a simple example.We will do the same way as the code above. the only difference is to note that if we have list of list we will need to create a class that holds the sublists and so on...
 
< string name="string_points" >{"items":[{"points":[{"x": 644,"y": 420},{"x": 644,"y": 421},{"points":[{"x": 752,"y": 348},{"x": 752,"y": 349}]}]} < / string >

public class ItemContainer {
 private List < Item > items ;
 public List < Item > getItems() {
  return items 
 }
 public void setItems(List < Item > items ) {
  this.items  = items 
 }
}

public class Item {
 private List < Point > points;
 public List < Point > getPoints() {
  return points;
 }
 public void setPoints(List < Point > points) {
  this.points = points;
 }
}

String string = cxt.getResources().getString(R.string.string_points);
List < ItemContainer > l =  new ArrayList < ItemContainer >();
Gson gson = new Gson();
l.add(gson.fromJson(string, ItemContainer.class));

That's all! Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Wednesday, August 27, 2014

How to make intellij works like eclipse incl. appearance and shortcuts in 1 min.

Hi there!

Since a few days I'm thinking about to move to AndroidStudio's IntelliJ IDEA. One of biggest problem and resistance i had, was the fact that IntelliJ IDEA has totally different shortcuts than eclipse. We don't want to learn or invent the wheel again for the same thing, right? For this reason, i'll show to you, how to use eclipse's shortcuts in IntelliJ.

Another thing i don't like very much, is the color schema. I've been programming with eclipse since years and although I like the black look and feel, I still prefer the traditional white appearance. So i will also show, how we can override the color schema of IntelliJ with a few clicks


Changing the shortcut list

Once you´ve downloaded and installed your AndroidStudio, start it and follow the sequences bellow:





Changing the color Schema

Now let's change also the color schema. To do so, copy this eclipse.xml file and save it in your desktop with the extension .xml

 
< ?xml version="1.0" encoding="UTF-8"? >
< scheme name="eclipse" version="1" parent_scheme="Default" >
  < option name="LINE_SPACING" value="1.2" /  >
  < option name="EDITOR_FONT_SIZE" value="12" /  >
  < option name="EDITOR_FONT_NAME" value="Courier New" /  >
  < colors >
    < option name="CARET_ROW_COLOR" value="e8f2fe" /  >
  < / colors >
  < attributes >
    < option name="ANNOTATION_NAME_ATTRIBUTES" >
      < value >
        < option name="FOREGROUND" value="646464" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="1" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CSS.FUNCTION" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CSS.IDENT" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CSS.KEYWORD" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="1" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CSS.PROPERTY_NAME" >
      < value >
        < option name="FOREGROUND" value="ff" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CSS.PROPERTY_VALUE" >
      < value >
        < option name="FOREGROUND" value="8000" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CSS.STRING" >
      < value >
        < option name="FOREGROUND" value="8000" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CSS.TAG_NAME" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CSS.URL" >
      < value >
        < option name="FOREGROUND" value="8000" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CUSTOM_KEYWORD1_ATTRIBUTES" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CUSTOM_KEYWORD2_ATTRIBUTES" >
      < value >
        < option name="FOREGROUND" value="660e7a" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CUSTOM_KEYWORD3_ATTRIBUTES" >
      < value >
        < option name="FOREGROUND" value="6666" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CUSTOM_KEYWORD4_ATTRIBUTES" >
      < value >
        < option name="FOREGROUND" value="660000" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CUSTOM_LINE_COMMENT_ATTRIBUTES" >
      < value >
        < option name="FOREGROUND" value="8080" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="2" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CUSTOM_MULTI_LINE_COMMENT_ATTRIBUTES" >
      < value >
        < option name="FOREGROUND" value="8080" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="2" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="CUSTOM_STRING_ATTRIBUTES" >
      < value >
        < option name="FOREGROUND" value="8000" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="EL.BOUNDS" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="EL.BRACKETS" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="EL.IDENT" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="EL.KEYWORD" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="EL.NUMBER" >
      < value >
        < option name="FOREGROUND" value="ff" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="EL.PARENTHS" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="EL.STRING" >
      < value >
        < option name="FOREGROUND" value="8000" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="EL_BACKGROUND" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" value="edffed" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="HTML_ATTRIBUTE_NAME" >
      < value >
        < option name="FOREGROUND" value="ff" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="HTML_ATTRIBUTE_VALUE" >
      < value >
        < option name="FOREGROUND" value="8000" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="HTML_ENTITY_REFERENCE" >
      < value >
        < option name="FOREGROUND" value="ff" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="HTML_TAG_NAME" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="INSTANCE_FIELD_ATTRIBUTES" >
      < value >
        < option name="FOREGROUND" value="c0" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JAVA_BLOCK_COMMENT" >
      < value >
        < option name="FOREGROUND" value="3f7f5f" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="2" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JAVA_DOC_COMMENT" >
      < value >
        < option name="FOREGROUND" value="3f5fbf" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="2" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JAVA_DOC_MARKUP" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="1" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JAVA_INVALID_STRING_ESCAPE" >
      < value >
        < option name="FOREGROUND" value="c0" /  >
        < option name="BACKGROUND" value="ffcccc" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JAVA_KEYWORD" >
      < value >
        < option name="FOREGROUND" value="7f0055" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JAVA_LINE_COMMENT" >
      < value >
        < option name="FOREGROUND" value="3f7f5f" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="2" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JAVA_NUMBER" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JAVA_STRING" >
      < value >
        < option name="FOREGROUND" value="2a00ff" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JAVA_VALID_STRING_ESCAPE" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.BADCHARACTER" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" value="ffcccc" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.BLOCK_COMMENT" >
      < value >
        < option name="FOREGROUND" value="808080" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="2" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.BRACES" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.BRACKETS" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.COMMA" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.DOC_COMMENT" >
      < value >
        < option name="FOREGROUND" value="808080" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="2" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.DOC_MARKUP" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" value="e2ffe2" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.DOC_TAG" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="1" /  >
        < option name="EFFECT_COLOR" value="808080" /  >
        < option name="EFFECT_TYPE" value="1" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.DOT" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.INVALID_STRING_ESCAPE" >
      < value >
        < option name="FOREGROUND" value="8000" /  >
        < option name="BACKGROUND" value="ffcccc" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.KEYWORD" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.LINE_COMMENT" >
      < value >
        < option name="FOREGROUND" value="808080" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="2" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.NUMBER" >
      < value >
        < option name="FOREGROUND" value="ff" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.OPERATION_SIGN" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.PARENTHS" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.REGEXP" >
      < value >
        < option name="FOREGROUND" value="ff" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="-1" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.SEMICOLON" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.STRING" >
      < value >
        < option name="FOREGROUND" value="8000" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JS.VALID_STRING_ESCAPE" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="JSP_DIRECTIVE_NAME" >
      < value >
        < option name="FOREGROUND" value="ff" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="PROPERTIES.KEY" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="1" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="PROPERTIES.VALID_STRING_ESCAPE" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="PROPERTIES.VALUE" >
      < value >
        < option name="FOREGROUND" value="8000" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="SCOPE_KEY_Problems" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="SCOPE_KEY_Production" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="SCOPE_KEY_Tests" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="STATIC_FIELD_ATTRIBUTES" >
      < value >
        < option name="FOREGROUND" value="c0" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="2" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="TEXT" >
      < value >
        < option name="FOREGROUND" value="323232" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="WARNING_ATTRIBUTES" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" value="f4c82d" /  >
        < option name="EFFECT_TYPE" value="2" /  >
        < option name="ERROR_STRIPE_COLOR" value="f4c82d" /  >
      < / value >
    < / option >
    < option name="XML_ATTRIBUTE_NAME" >
      < value >
        < option name="FOREGROUND" value="ff" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="XML_ATTRIBUTE_VALUE" >
      < value >
        < option name="FOREGROUND" value="8000" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="XML_ENTITY_REFERENCE" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="XML_TAG_DATA" >
      < value >
        < option name="FOREGROUND" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
    < option name="XML_TAG_NAME" >
      < value >
        < option name="FOREGROUND" value="80" /  >
        < option name="BACKGROUND" /  >
        < option name="FONT_TYPE" value="0" /  >
        < option name="EFFECT_COLOR" /  >
        < option name="EFFECT_TYPE" value="0" /  >
        < option name="ERROR_STRIPE_COLOR" /  >
      < / value >
    < / option >
  < / attributes >
< / scheme >

Setting the color Schema

Now cut this saved file from your desktop using Ctrl+X and put it in your user's directory by pressing Ctrl+V like that: (Note, your user's color config directory may not be equal to my presented here in this example)


Now you should see this file by looking at:



Done! That's all! Hope you like it.

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Friday, August 22, 2014

Programming Design Pattern - Memento Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Memento design pattern in action. The Memento design pattern is a very useful programming design pattern whenever you need to perform save, undo and restore functions.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML Diagram of the Memento Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.





The example

In our example we will see, how we could perform save and undo actions restoring objects from a text file.

The Memento

That's the generic interface you could use while dealing with memento's capabilities. We will implement the memento on the fly in the Originator bellow. In other words, as soon as we need it in line.

// 1 STEP: DEFINE THE MEMENTO 
public interface Memento < T > {
    T getMemento();
    void setMemento(T state);
}

The Originator

That's the generic interface we will use to implement the Originator. I will create it also on the fly in the client. In a few seconds bellow. :)

//2 STEP: DEFINE THE ORIGINATOR 
public interface Save < T > extends Memento < T > {
    Memento < T > save();
    void restore(Memento < T > memento);
}

The Interface Undo

That's the generic interface we will use to create the care taker. I will create it also on the fly in the client. Be patient. :)

//3 STEP: DEFINE THE CARETAKER
public interface Undo < T > {
    public void addMemento(Memento < T > state) ;
    public Memento < T > getMemento(int index);
}

The concrete CareTaker

That's the abstract implementation of the generic interface. I will create it also on the fly in the client. Stay tuned. :)

//4 STEP: IMPLEMENT A ABSTRACTCARATAKER
public abstract class UndoCareTaker < T > implements Undo < T > {
    private List < Memento < T > > mementoList = new ArrayList < Memento < T > > ();
    public void addMemento(Memento < T > state) {
        if (state != null) {
            mementoList.add(state);
        }
    }
    public Memento < T > getMemento(int index) {
        int min = 0;
        int max = mementoList.size()-1;
        if(mementoList.isEmpty()){
            String msg = "CareTaker has no entry! Passed index:";
            throw new IndexOutOfBoundsException(msg + index);
        }
        if(!(index > = min && index < = max)){
            String msg = "Passed index:"+index+" > Allowed index range: ";
            throw new IndexOutOfBoundsException(msg + min + " - " + max);
        }
        return mementoList.get(index);
    }
}

The Originator Ifself

That's the abstract implementation of the interface generic interface Save.

//5 STEP: IMPLEMENT A ABSTRACTORIGINATOR
public abstract class SaveOriginator < T > implements Save < T >{
    private T state;
    public void setMemento(T state) {this.state = state;}
    public T getMemento() {return state;}
    public void restore(Memento < T > memento) {setMemento(memento.getMemento());}
    public Memento < T > save() {
        Memento < T > memento = new Memento < T > () { // created on the fly as i promissed! :)
            private T state;
            @Override
            public void setMemento(T state) {this.state = state;}
            @Override
            public T getMemento() {return state;}
        };
        memento.setMemento(state);
        return memento;
    }
}

The Test

Finally, let's see how it works in practise.

public class Client {
    public static void main(String[] args) {
        Save < String > originator = new SaveOriginator < String > (){};//created on the fly
        Undo < String > careTaker = new UndoCareTaker < String > (){};//created on the fly
        originator.setMemento("State #1");
        originator.setMemento("State #2");
        careTaker.addMemento(originator.save());
        originator.setMemento("State #3");
        careTaker.addMemento(originator.save());
        originator.setMemento("State #4");
        System.out.println("Current State: " + originator.getMemento());
        originator.restore(careTaker.getMemento(0));
        System.out.println("First saved State: " + originator.getMemento());
        originator.restore(careTaker.getMemento(1));
        System.out.println("Second saved State: " + originator.getMemento());
    }
}

That's all! Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Programming Design Pattern - Observer Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Observer design pattern in action. The Observer design pattern is a very useful programming design pattern whenever you need to notify classes or objects depending on changes or on user interactions. This is one of the most used pattern i think.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML Diagram of the Observer Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.





The example

In our example we will see, how we could notify all postmans every time new posts arrives in the post office central station.

Observer and Observable

Those interfaces are part of the default java library. For that reason we will not invent the wheel again. We will just use it.

The PostOffice Observable

This will be our observable. In other words, the object which holds a register method for observers interested in being notified, as soon as changes in the post office occurs.

import java.util.Observable;
public class PostOffice extends Observable {
    public void receberCartas(){
        System.out.println("New post arrived!");
        setChanged();
    }
    public void distributePost(){
        notifyObservers();
    }
}

The Postman Observer

This is the observer itself interested in being notified, as soon as changes in the post office occurs.

import java.util.Observable;
import java.util.Observer;
public class Postman implements Observer {
    @Override
    public void update(Observable o, Object arg) {
        System.out.println("Postman: distributing posts...");
    }
}

The Test

Let's see how those classes interacts together. Pay close attention, because this pattern will surely be one of the most used in your programming life! ;)

public class Client {
    public static void main(String[] args) {
        PostOffice postoffice =  new PostOffice();
        // adding postmans to the post office (observers)
        postoffice.addObserver(new Postman());
        // Simulating arrival of letters in the central post office
        postoffice.receberCartas();
        // simulating postmans distributing letters
        postoffice.distributePost();
    }
}

That's all! I hope you like it!


😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Programming Design Pattern - Adapter Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Adapter design pattern in action. The Adapter design pattern is a very useful programming design pattern whenever you need to ensure communication between incompatible interfaces, classes or objects.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML Diagram of the Adapter Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.





The example

In our example we will see, how we could adapt incompatible interfaces so that they can interact together. We will connect a  rounded 3-pins plug with a rectangular 2-pins plug.

Incompatible Classes

The classes to adapt.

public class CylinderSocket {
    public CylinderPin cylinderPin;
    
    public CylinderSocket(){
        this.cylinderPin=new CylinderPin("corrent", "neutro", "terra");
    }
}
public class RectangularPlug {//ADAPTEE
    public String corrente;
    public String neutro;

    public String getPower() {
        return "power on!";
    }
}

The Adapter

To be able to adapt something, first of all we must define the common interface between at least two classes/objects.

public interface Plugable { // "TARGET" INTERFACE
    public String getPower();
}

The Test

Finally, let's test our adapter which will connect a rounded plug with a rectangular plug.

public class Client {
    public static void main(String[] args) {
        // Rounded plug with 3 pins with rectangular plug with 2 pins
        CylinderSocket cylinderSocket = new CylinderSocket();
        // Client knows only the interface
        Plugable plugable = new PlugAdapter(cylinderSocket);
        // see if connection works
        System.out.println(plugable.getPower());
    }
}

That's all! Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Programming Design Pattern - Mediator Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Mediator design pattern in action. The Mediator design pattern is a very useful programming design pattern whenever you want to centralize logics making it maintainable when a lot of objects has to communicate together.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML Diagram of the Mediator Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.





The example

In our example we will see, how we could centralize the logic from a bunch of devices in a smart house making it better maintainable and decoupling the objects from each other.

The Events

In our example, we will be dealing with a lot of devices interacting with each other in a smart house. Those devices fire events. Let's define some events for each of them. After that we will define the devices itself.

public enum Evento {
    TERMOMETRO, METEOROLOGIA, LIXO, DISPERTADOR, 
    AGENDA, MAQUINA_CAFE, AR_CONDICIONADO,BORRIFADOR_PLANTAS;
}
public interface Occurrence {
    void ocorrencia(Evento evento, Object origin);
}

The Devices to mediate

In our example, we have a lot of devices in our house to mediate. Let's define some.

public abstract class Device{
    private Occurrence occurrence;
    public Device(Occurrence centralControl) {
        this.occurrence = centralControl;
    }
    public void inform(Evento evento) {
        occurrence.ocorrencia(evento, this);
    }
    public abstract void update();
}
public class Agenda extends Device{

    public Agenda(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    public void exameMedico(){
        inform(Evento.AGENDA);
    }
    @Override
    public void update() {
        System.out.println("Visitando médico...!");
    }

}
public class ArCondicionado extends Device{
    public ArCondicionado(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    public void fazerManutencao(){
        inform(Evento.AR_CONDICIONADO);
    }
    @Override
    public void update() {
        System.out.println("Manutenção feita com sucesso!");
    }
}
public class BorrifadorPlantas extends Device{
    public BorrifadorPlantas(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    public void faltandoAgua(){
        inform(Evento.BORRIFADOR_PLANTAS);
    }
    @Override
    public void update() {
        System.out.println("Registro aberto. Pode borrifar!");
    }
}
public class Dispertador extends Device {

    public Dispertador(Occurrence ocorrencia) {
        super(ocorrencia);
    }

    public void horaDeTrabalhar() {
        inform(Evento.DISPERTADOR);
    }

    @Override
    public void update() {
        System.out.println("Acorrrrrdaaaaaa! Vai trabalhar menino!!!");
    }
}
public class MaquinaCafe extends Device{

    public MaquinaCafe(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    public void cofreMoedasCheio(){
        inform(Evento.MAQUINA_CAFE);
    }
    @Override
    public void update() {
        System.out.println("Cofre esvaziado! Maquina is ready!");
    }

}
public class Meteorologia extends Device{

    public Meteorologia(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    
    public void alertaDeTempestade(){
        inform(Evento.METEOROLOGIA);
    }
    @Override
    public void update() {
        System.out.println("Fique em casa! Tornado se aproximando!");
    }

}
public class RecolhaLixo extends Device{

    public RecolhaLixo(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    public void colocarLixoPraFora(){
        inform(Evento.LIXO);
    }
    @Override
    public void update() {
        System.out.println("O caminhão de lixo irá passar daqui a pouco!");
    }

}

The Mediator

This class will be mediating between the devices in the house. It is like the CPU in the computer if you like the analogy. It centralizes the logic in one place.

public class CentralControle implements Occurrence {
    @Override
    public void ocorrencia(Evento evento, Object origin) {
        switch (evento) {
        case AGENDA:((Agenda)origin).update();break;
        case AR_CONDICIONADO:
            // FAZER MANUTENÇÃO...
            // ...ATUALIZAR APARELHO
            ((ArCondicionado)origin).update();
            break;
        case BORRIFADOR_PLANTAS:((BorrifadorPlantas)origin).update();break;
        case DISPERTADOR:((Dispertador)origin).update();break;
        case LIXO:((RecolhaLixo)origin).update();break;
        case MAQUINA_CAFE:((MaquinaCafe)origin).update();break;
        case METEOROLOGIA:((Meteorologia)origin).update();break;
        case TERMOMETRO:((Termometro)origin).update();break;
        default:break;}
    }
}

That's all! Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Programming Design Pattern - Iterator Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Iterator design pattern in action. The Iterator design pattern is a very useful programming design pattern whenever you need to iterate over structures without knowing how this structure is implemented.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML Diagram of the Iterator Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.





The example

In our example we will see, how we could iterate over a restaurant's menu, showing the food options to our clients.

The Iterable and Iterator

Because those interfaces are part of the java default library, we will not invent the wheel again. So we will make usage of it. You don't need to implement it. I've just inserted here in case you want to understand the details and ideas behind it.

import java.util.Iterator;
public interface Iterable < T > {
    Iterator < T > iterator();
}
public interface Iterator < E > {
    boolean hasNext();
    E next();
    void remove();
}

The Product

Well, the idea behind the iterator is to iterate over a structure without knowing the details about this implementation. We just want to iterate over it to get some information about this structure. For this reason we first need a product (in our case Food) and a structure (in our case the MenuIterator). Note: in the real world we would name it just Menu. But for this tutorial here, I've intentionally defined MenuIterator to facilitate the understanding.

public class Food {
    private String name;
    private String description;
    private boolean vegetarian;
    private double price;
    public Food(String name, String description, boolean vegetarian, double price) {
        super();
        this.name = name;
        this.description = description;
        this.vegetarian = vegetarian;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public boolean isVegetarian() {
        return vegetarian;
    }
    public void setVegetarian(boolean vegetarian) {
        this.vegetarian = vegetarian;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return getName()+", "+getPrice()+" R$\n  - "+getDescription();
    }
}
public class MenuIterator implements Iterator < Food > {
    private Food[] foodOptions;
    int position = 0;
    MenuIterator(Food[] foodOptions){this.foodOptions=foodOptions;}
    @Override
    public boolean hasNext() {
        if(position > = foodOptions.length || foodOptions[position]==null){
            return false;
        }return true;
    }
    @Override
    public Food next() {
        final Food food = foodOptions[position];
        position++;
        return food;
    }
    @Override
    public void remove() {/*NOP*/}
}

The Barmaid

Our Barmaid will use the iterator to navigate over the menu showing the food options to the client.

public class Barmaid {
    private Iterable < Food > menu;
    public Barmaid(Menu menu) {
        this.menu = menu;
    }
    public void showMenu(){
        final Iterator < Food > iterator = menu.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next().toString());
        }
    }
}

The Test

Finally, we've opened our restaurant and the barmaid is showing the menu's to the clients. :)

public class Client {
    public static void main(String[] args) {
        String name = "Roast beef";
        String description = "Delicious roast beef argentino";
        boolean vegetarian = false;
        double price = 12.99;
        final Food roastBeef = new Food(name,description,vegetarian, price);
        name = "Sopa tomate";
        description = "Deliciosa sopa de tomate com oregano e creme de leite";
        vegetarian = true;
        price = 8.50;
        final Food sopaTomate = new Food(name,description,vegetarian, price);
        Food[] foodOptions = new Food[]{roastBeef, sopaTomate };
        final Menu menu = new Menu(foodOptions);
        final Barmaid barmaid = new Barmaid(menu);
        barmaid.showMenu();
    }
}

That's all! Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Programming Design Pattern - Interpreter Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Interpreter design pattern in action. The Interpreter design pattern is a very useful programming design pattern while dealing with transformations, language issues, changing from one system to another and so on.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML Diagram of the Interpreter Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.





The example

In our example we will see, how we could interpret different number systems like decimal to octal or binary and so on.

The Context of the interpretation

This is one of the core concept of interpretation. It must define the context. It is in the nature of the thing. Without a context, no interpretation. So let's define our context first. We want to implement a number system interpretation. For this reason I'm defining the types of number system. After that I'm able to define the Interpreter itself and the NumberSystemInterpreter.

public enum InterpreterContext {INTEGER_TO_BIN,INTEGER_TO_HEX,INTEGER_TO_OCTAL;}

public interface Interpreter < T, V > {
    T interpret(V toInterpret, InterpreterContext context);
}

public class NumberSystemInterpreter implements Interpreter < String, Integer > {
    @Override
    public String interpret(Integer toInterpret, InterpreterContext context) {
        switch (context) {
        case INTEGER_TO_BIN:
            return Integer.toBinaryString(toInterpret);
        case INTEGER_TO_HEX:
            return Integer.toHexString(toInterpret);
        case INTEGER_TO_OCTAL:
            return Integer.toOctalString(toInterpret);
        default:return "No grammar available";
        }
    }
}

The Expressions

That's also typical for Interpreter pattern. We need some expressions to be interpreted. In our case we will be defining three Expressions. One for each number system to be interpreted.

public interface Expression < T, V > {
    String interpret(Interpreter < T, V > interpreter);
}
public class OctalExpression implements Expression < String, Integer > {
    private int toInterpret;
    public OctalExpression(int integer){this.toInterpret=integer;}
    @Override
    public String interpret(Interpreter < String, Integer > numberSystem) {
        return numberSystem.interpret(toInterpret, InterpreterContext.INTEGER_TO_OCTAL);
    }
}
public class HexExpression implements Expression < String, Integer > {
    private int toInterpret;
    public HexExpression(int integer){this.toInterpret=integer;}
    @Override
    public String interpret(Interpreter < String, Integer > numberSystem) {
        return numberSystem.interpret(toInterpret, InterpreterContext.INTEGER_TO_HEX);
    }
}
public class BinaryExpression implements Expression < String, Integer > {
    private int toInterpret;
    public BinaryExpression(int integer){
        this.toInterpret=integer;
    }
    @Override
    public String interpret(Interpreter < String, Integer > interpreter) {
        return interpreter.interpret(toInterpret, InterpreterContext.INTEGER_TO_BIN);
    }
}

The Test

Finally, let's see the interpreter in action. ;)

public class Client {
    public static void main(String[] args) {
        Interpreter < String, Integer > numberSystem = new NumberSystemInterpreter();
        Expression < String, Integer > decimalToBin = new BinaryExpression(23);
        System.out.println(decimalToBin.interpret(numberSystem));
        Expression < String, Integer > decimalToHex = new HexExpression(23);
        System.out.println(decimalToHex.interpret(numberSystem));
        Expression < String, Integer > decimalToOctal = new OctalExpression(23);
        System.out.println(decimalToOctal.interpret(numberSystem));
    }
}

That's all! Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Wednesday, August 20, 2014

Programming Design Pattern - Bridge Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Bridge design pattern in action. The Bridge design pattern is a very useful programming design pattern whenever you need to be able to vary abstractions and implementations of structures.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML Diagram of the Bridge Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.





The example

In our example we will see, how we could separete the remote control from the TV, so we can vary both sides. (The abstraction[remote controls] and the implemention[TV's] of it) This way we will be able to implement platforms dependent TV's and remote controls.

The Bridge

This is the common interface that acts between two object structures (the bridge). The TV types are the structure of different clients that can have different remote controls.

public interface TV {
    public void on();
    public void off();
    public void setChannel(int id);
}
public class Sony implements TV {
    public void on() {System.out.println("Sony TV on!");}
    public void off() {System.out.println("Sony TV off!");}
    public void setChannel(int id){System.out.println("Sony Channel set: "+id);}
}
public class Philips implements TV {
    private int channelId=0;//SPECIFIC FEATURE FROM PHILIPS
    public void on() {System.out.println("Philips TV on!");}
    public void off() {System.out.println("Philips TV off!");}
    public void setChannel(int id){
        this.channelId=id;
        System.out.println("Philips Channel set: "+id);
    }
    // SPECIFIC IMPLEMENTATION FROM PHILIPS
    public int getChannelId() {return channelId;}
}

The Remote Control

Each TV communicates over different remote controls and each of them could have more, less or different functions.

public abstract class ControleRemoto {
    protected TV tv;
    public ControleRemoto(TV tv) {this.tv = tv;}
    public abstract void on();
    public abstract void off();
    public abstract void setChannel(int id);
}
public class PhilipsControleRemoto extends ControleRemoto {
    public PhilipsControleRemoto(TV tv) {super(tv);}
    public void on() {tv.on();}
    public void off() {tv.off();}
    public void setChannel(int id) {tv.setChannel(id);}
    // SPECIFIC IMPLEMENTATION FOR PHILIPS
    public void nextChannel(){
        final int currentChannelId = ((Philips)tv).getChannelId();
        tv.setChannel(currentChannelId+1);
    }
}
public class SonyControleRemoto extends ControleRemoto {
    public SonyControleRemoto(TV tv) {super(tv);}
    public void on() {tv.on();}
    public void off() {tv.off();}
    public void setChannel(int id) {tv.setChannel(id);}
}

The Test

Here we can see how the clients (TV's) communicate over the bridges with the different remote controls. With this concept, both, TV's and Remote Control's, can vary.

public class Client {
    public static void main(String[] args) {
        final ControleRemoto philips = new PhilipsControleRemoto(new Philips());
        final ControleRemoto sony = new SonyControleRemoto(new Sony());
        sony.setChannel(3);
        // PHILIPS HAS MORE FUNCTIONALITIES
        philips.setChannel(18);
        ((PhilipsControleRemoto)philips).nextChannel();
    }
}

That´s all. Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†