Rezha Julio

Hi!
My name is Rezha Julio
I am a chemist graduate from Bandung Institute of Technology. Currently working as Data Engineer at Traveloka.
You can reach me by email:

contact@rezhajulio.id

, @ Q Q

Powered by Hugo

filter by tags

Python GeneratorNext, Function or Method ?

time to read 1 min | 74 words

While in Python 2 it was possible to use both the function next() and the .next() method to iterate over the resulting values of a generator, the later has been removed with the introduction of Python 3.

Consider the sample generator:

def sample_generator():
    yield "a"
    yield "b"
    yield "c"

In Python 2:

a = sample_generator()
print(next(a)) # prints 'a'
print(a.next()) # prints 'b'

But in Python 3:

print(next(a)) # prints 'a'
print(a.next()) # AttributeError

Java 101Using bounded type parameters in generic methods

time to read 1 min | 114 words

Sometimes it may be appropriate to write a generic method, however it will not be possible for it to accept every type while still maintaining all the necessary functionality.

To solve this, use bounded type parameters to restrict generic methods from accepting arguments of a particular kind.

public <T extends Shape> 
  void drawAll(List<T> shapes){
    for (Shape s: shapes) {
        s.draw(this);
    }
}

The above method is used to draw a list of shapes. Writing a generic method with an unbounded type parameter would cause problems because lists of other types cannot be drawn in this way.

By specifying that <T extends Shape> we guarantee that only Shape objects can be passed to the method.

Java 101Updating interfaces by using default methods

time to read 1 min | 127 words

Take the following interface:

public interface Cooking {
  public void fry();
  public void boil();
  public void chop();
}

To add new functionality, simply adding a new method to Cooking called microwave() will cause problems. Any class that previously implemented Cooking will now have to be updated in order to function again.

To avoid this, give microwave() a default implementation:

public interface Cooking {
  public void fry();
  public void boil();
  public void chop();
  default void microwave() {
    //some code implementing microwave
  }
}

As microwave() already has a default implementation defined in the Cooking interface definition, classes that implement it now don’t need to implement microwave() in order to work.

This allows us to add functionality without breaking old code.

Note: This has been possible since Java 8.

RECENT SERIES

  1. java 101 (13):
    Apr 29, 2017 - Translating Scanner tokens into primitive types
  2. python data structure (5):
    May 03, 2017 - Enhance your tuples
  3. python function (2):
    Apr 16, 2017 - Lambda Functions in Python
  4. python generator (4):
    Apr 26, 2017 - Next, Function or Method ?

Friends of Rezha