BDD: Cucumber Hello World Using Java and IntelliJ

Categories: Java; Tagged with: ; @ March 14th, 2015 16:42

Example:

Feature: Convert between different currencies
  Scenario: Convert SGD to CNY
    Given currency:"SGD", amount:10
    Given fxRate is 4.60
    When convert to "CNY"
    Then the result is 46 in CNY

JUnit Test: it can be generated by cucumber plugins, but not perfect for my IDE. (cannot generate all steps, but you still can copy the generated JUnit code from the output)

package com.liguoliang.bdd;

import cucumber.annotation.Before;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import org.junit.Assert;

import java.math.BigDecimal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Created by guoliang on 3/14/15.
 */
public class FxConverterTest {

    private FxConverter fxConverter;

    @Before
    public void setUp() {
        fxConverter = new FxConverter();
    }


    @Given("^currency:\"([^\"]*)\", amount:(\\d+)$")
    public void currency_amount(String currency, BigDecimal amount) throws Throwable {
        fxConverter.setCurrencySource(currency);
        fxConverter.setAmountInput(amount);
    }

    @Given("^fxRate is (.+)$")
    public void fxRate_is_(BigDecimal rate) throws Throwable {
        fxConverter.setFxRate(rate);
    }

    @When("^convert to \"([^\"]*)\"$")
    public void convert_to(String currency) throws Throwable {
        fxConverter.convertTo(currency);

    }

    @Then("^the result is (.+) in CNY$")
    public void the_result_is_in_CNY(BigDecimal resultExpected) throws Throwable {
        assertTrue(resultExpected.compareTo(fxConverter.getAmountResult()) == 0);
    }

}

Java: calculate number complement using BitSet

Categories: Java; Tagged with: ; @ March 10th, 2015 20:15

Two’s complement is the way every computer I know of chooses to represent integers. To get the two’s complement negative notation of an integer, you write out the number in binary. You then invert the digits, and add one to the result.

www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html

    	Integer input = 50;
    	
    	String binString = Integer.toBinaryString(input);
    	BitSet bitSet = BitSet.valueOf(new long[] {input});
    	
    	for (int i = 0; i < binString.length(); i++) {
			bitSet.flip(i);
		}
    	
    	System.out.println(Arrays.toString(bitSet.toByteArray()));

Switch: throw an exception if default section shouldn’t be reached? #Route 85 – Quick Tip: Don’t Default that Switch!

Categories: Java; Tagged with: ; @ March 8th, 2015 21:32

There’s a quick tip from Google developers about switch, the suggestion is getting rid of throwing exception in switch default section if the default handler shouldn’t be reached.

Here’s an example in Java:

package com.liguoliang.java.core.lang.enum_;

/**
 * Created by Guoliang, Li(liguoiang.com) on 3/8/2015.
 */

public class SwitchDefaultDemo {

    public static void main(String[] args) {
        System.out.println(getBookCategoryDesc(BookCategory.JAVA));
;    }

    private static String getBookCategoryDesc(BookCategory bookCategory) {
        String desc = null;
        switch (bookCategory) {
            case JAVA:
                desc = "It's a Java book";
                break;
            case PYTHON:
                desc = "It's a PHP book";
                break;
            default:
                throw new RuntimeException("Unknown book category");
        }

        return desc;
    }

    public static enum BookCategory {
        JAVA, PYTHON, PHP;
    }
}

The tip’s point is if developer added a new enum and forgot to update the switch statement accordingly, there’ll be a issue, it may fail the test or crash the application.

so to improve the switch statement, the video suggest to remove the default section. if some client calls getBookCategoryDesc(PHP), the method will be executed normally, instead of throwing an exception.

it seems debatable for me, I prefer to keep the exception,  throwing an exception to exposure the risk instead of hiding it, because the exception tells the details, developers can fix the bug immediately. otherwise, developers will realize the issue and start to debug until user reporting it.

Using bounded wildcards in Java Generics

Categories: Java March 3rd, 2015 22:29

Code:

package com.liguoliang.java.core.lang.generics;

import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

public class GenericsWildCardTest {

private GenericsWildCard genericsWildCard;

private List<Integer> listOfIntegers;
private List<Number> listOfNumbers;
private List<Long> listOfLong;
private List<Object> listOfObjects;

@Before
public void before() {
genericsWildCard = new GenericsWildCard();

listOfIntegers = new ArrayList<Integer>();
listOfIntegers.add(1);
listOfIntegers.add(2);

listOfNumbers = new ArrayList<Number>();
listOfNumbers.add(1.1);

listOfLong = new ArrayList<Long>();
listOfLong.add(100L);

listOfObjects = new ArrayList<Object>();
}

@Test
public void testMergeList_() throws Exception {
List<Integer> listOfIntegers = new ArrayList<Integer>();
List<Number> listOfNumbers = new ArrayList<Number>();

int sizeExpected = listOfIntegers.size() + listOfNumbers.size();
genericsWildCard.mergeList_(listOfIntegers, listOfNumbers);
assertEquals(sizeExpected, listOfNumbers.size());
}

@Test
public void testMergeListWithWildCard() {
int sizeExpected = listOfIntegers.size() + listOfNumbers.size();
genericsWildCard.mergeListWithBoundedWildCard(listOfIntegers, listOfNumbers);
assertEquals(sizeExpected, listOfNumbers.size());

sizeExpected = listOfLong.size()+ listOfObjects.size();
genericsWildCard.mergeListWithBoundedWildCard(listOfLong, listOfObjects);
assertEquals(sizeExpected, listOfObjects.size());
}
}

 
package com.liguoliang.java.core.lang.generics;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
* Created by Guoliang, Li(liguoiang.com) on 3/3/2015.
*/
public class GenericsWildCard {

protected void mergeList_ (List<Integer> subList, List<Number> superList) {
}

protected void mergeListWithBoundedWildCard(List<? extends Number> subList, List<? super Number> superList) {
for (Number number : subList) {
superList.add(number);
}

Number firstItem = subList.get(0);

// subList.add(firstItem); // cannot be applied to Number;
// subList.add(Integer.valueOf(1)); // cannot be applied to Interger;

// superList.add(firstItem);
// superList.add(Integer.valueOf(1));
// superList.add(new Object()); // cannot be applied to Object
}


private static void mergeList(List<? extends Number> subList, List<? super Number> superList) {
Integer i = (Integer) subList.get(0);
Number n = i;

//subList.add(n); // cannot be applied
Number n1 = 0;
// subList.add(0);
// subList.add(n1);
// subList.add(0);

superList.add(i);
superList.add(n);
}

public static void main(String[] args) {
List<Number> listOfNumbers = new ArrayList<Number>();
listOfNumbers.add(0.9);
listOfNumbers.add(2.1);

List<Integer> listOfIntegers = new ArrayList<Integer>();
listOfIntegers.add(1);
listOfIntegers.add(3);

List<Object> listOfObjects = new ArrayList<Object>();

mergeList(listOfNumbers, listOfNumbers);
// mergeList(listOfNumbers, listOfIntegers);
// mergeList(listOfIntegers, listOfObjects);
}
}
 

Notes:

List<Integer> is not List<Number>
List<Integer> is List<? extends Number>

PECS – producer-extends, consumer-super;

Cannot add any item to List<? extends Object>

赶路的人

Categories: 垃圾山 February 26th, 2015 13:03

站在村头的小山顶,看着被落日余晖跟炊烟覆盖的小村庄,这是生我养我的地方,我的父母常年生活在这里,我的爷爷奶奶住在我旁边的坟里。 十几年前,我扑棱棱的飞了,越飞越远 – 不仅仅是距离,更多的是差别。 每年过年前,我站在这里,就会觉的舒畅,踏实。

生活被机场隔开了,在机场这边,我期待能够飞的更远,可在机场那边,我却朝思暮想的期待有一天能让父母开心幸福的生活。 在家乡读着流浪的书,却在异乡想念故乡的酒。

在我的家乡,过年有一定的流程,对我来说大致可以简化为 上坟,贴对联,喝酒,喝酒,以及更多的喝酒。每年是应该喝几两辣心口的白酒,听一听那些掏心窝子却又有些刺耳的酒后真言,老少爷们们在一杯又一杯之间就开心的把一年度过了。

我希望奔波了这么久,回家能够温和谦逊的孝顺父母,可往往我对他们有更多的不满,这样的懊悔感日益增强,直到临走前一天,甚至希望自己不曾回来过 – 因为没有带给父母开心与欢喜,没有带走多少父母的寄托,却给他们留下了更多担心。

北风吹。 在新加坡的时候我经常怀念这样的冷风,这样的风,凌烈,清澈,嗖嗖的吹在脸上,吹过树梢,吹过马屁股,冷风吹在脸上,家的温馨就容易涌上心头。

二堂哥说,我们堂兄弟们这么亲,过年都会回来上坟磕头,不知下一代会怎么样,他们还知道家里几口人,谁是谁的谁吗?作为长久以来离开农村的第一代,我隐约觉得我的孩子们甚至可能不喜欢农村,甚至讨厌回国(假如我留在国外),他们身体跟灵魂只会偶尔飘过这个小土村,再过几十年,坟头会杂草丛生,没人在清明添土,没人在年前上坟。 再过几十年,杂草或是地产商占领里这里,不会再有人牵挂这里的人,更不会有人想起这里平凡朴素的生活。 这或许是一种进步,但这样的进步让我心痛。

我习惯了赶两条路,一条是回家的,另一条是离家的。 前一条走的欢喜 迫切,像小孩子蹦蹦跳跳的追糖葫芦,后一条却忧伤 拉扯,慢慢的吃一盘拔丝红薯就是那种感觉。

今天我又踏上了这条离家的路,希望这条路走的顺利,希望我能带给挂念我的人欢喜与快乐。

愿平凡与朴素陪伴你。

Newer Posts <-> Older Posts



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.