Next, Function or Method ?

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....

April 26, 2017 · 1 min · Rezha Julio

Using bounded type parameters in generic methods

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....

April 19, 2017 · 1 min · Rezha Julio

Updating interfaces by using default methods

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....

April 9, 2017 · 1 min · Rezha Julio