SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
from java to python
beating the stockholm syndrome
Javier Arias Losada
@javier_arilos
We are going to compare Java versus Python
through some random topics… but not trying to
be exhaustive or follow any logical patterns…
just aspects I liked, disliked or just caught my
attention.
Disclaimer
1. Some points have been improved in latest versions of Python
and Java
2. Opinions stated are those of the author, Javier Arias
Working since 1997 with OO languages, mainly in
Java and some Smalltalk… one has some rigidness
regarding idioms, mental schemes and patterns…
Python approach to many aspects is different
from Java and tends to be more pragmatic.
verbosity and ease of reading (I)
“(…) when you program, you have to think about how someone will read your
code, not just how a computer will interpret it.”
- Kent Beck
Indentation, expressiveness and idioms, libraries matter.
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// do something with line.
}
br.close();
with open(...) as f:
for line in f:
# do something with line
http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-in-java
http://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python
verbosity and ease of reading (II)
logical expressions & truthy values:
if x and x not in elements:
print ‘done’

if (x != null && !elements.contains(x))
{
System.out.println(“done”);
}
Python seems to be ahead here, improves this productivity?
Usually code is easier to read and maintain in Python.
Refactoring is faster and more secure in Java (static typing
+ advanced IDE’s).
verbosity and ease of reading (III)
method and function definition
An example: parse N lines of a file, searching for a text
Python keyword args: named and optional, default values.
def search(txt, file=’./f.txt’, lines=0):
return 0
Java method overriding: different methods with different
parameters (number and type)
public int search(String txt, String file, Integer lines){
return 0;
}
verbosity and ease of reading (IV)
Lets add optional params in Java:
public int search(String txt, Integer lines){
search(txt, “./f.txt”, lines);
}
public int search(String txt, String file){
search(txt, file, 0);
}
Java’s method signature overriding is very useful for
maintaining functions (and constructors) less cluttered.
verbosity and ease of reading (V)
New Requirement: extend our search function to search for a
client’s name, accept instances of Client class.
public int search(Client client, String file){
search(client.getName(), file);
}
def search(what, file=’./f.txt’, lines=0):
if isinstance(what, Client):
what = what.name
(...)
Results of the exercise:
Java: one core method and three “facilitator” methods.
Python: one method that is caring about type of parameters.
verbosity and ease of reading (VI)
List and dictionary comprehensions
a real example: filtering a dictionary.
filtered_policies = {pol: spr_message.policies[pol]
for pol in _GCM_ALLOWED_POLICIES
if pol in spr_message.policies}
Python Dict and list comprehension are very flexible and
powerful ways of creating lists and dict on the fly.
filteredPolicies = sprMessage.getPolicies().keySet()
.retainAll(GCM_ALLOWED_POLICIES);
Java is usually more verbose and less fluent for this
collection related tasks, but sometimes a well designed API
can do miracles, as in this example.
verbosity and ease of reading (end)
searched google looking for
the shortest tutorials of each language:
As an objective indicator,

Teach yourself Java in 21 minutes:
http://www.debevc.uni-mb.si/IT2003/Razno/teach_Java_21_minutes.pdf

Learn Python in 10 minutes:
http://www.stavros.io/tutorials/python/

Python is half as verbose as Java.
If you ignore me, in the time of this talk you can learn both
languages.
Just joking :-)
as object oriented languages (I)
inheritance
Liskov Substitution Principle: If S is a subtype of T, then
objects of type T may be replaced with objects of type S.
Use your code without caring about what type or subtype it is.

Java
simple inheritance.
interfaces.
statically-strongly typed.

Python
multiple inheritance.
dynamically-strongly typed.
as object oriented languages (II)
composition-inheritance-multiple inheritance
“In object-oriented programming, Inheritance is the evil forest (...) deep inside
the Dark Forest Inheritance is the Evil Queen Multiple Inheritance (...)”
- Learn Python the hard way:

http://bit.ly/O709e9

Java super
super();
super.aMethod();

Python super
super(class, object)
super may not call parent: MRO
A
/

super always call parent.



B

C



/
D

About MRO in Python: http://bit.ly/18RHQBC
as object oriented languages (III)
inheritance
The Circle / Ellipse problem:
➔ In maths, circle is a special case for an ellipse: both axes
are equal
➔ Who should be superclass and subclass?
◆
◆

If Ellipse is the parent: what happens with the Ellipse method that
stretches an axis? what does that mean for Circle instances?
If Circle is the parent, seems counterintuitive and no code reused.

Two ways of thinking about subclassing:
1.
2.

The OO classic view
Pragmatic’s non-taxonomy based approach
as object oriented languages (IV)
inheritance, classic OO view
a subclass is a specialization of a superclass.
Organize your code by taxonomies: "Is-a" relationships. e.g. Dog
is-an Animal.
"Inheritance is the idea that one class is a specialization of another class." Code Complete.

This is what the majority of us do: at least in Java, probably
in Python as well.
as object oriented languages (V)
inheritance, alternative approach
Inheritance as a mechanism for code reuse,
nothing to do with taxonomies.
Raymond Hettinger, Python core developer:

Put the Dog on top,
if the Dog has more code that is useful for Animal

From The art of subclassing, Raymond Hettinger.
"How do you decide which one is on top? There is no principle of specialization. (...) Why do we
subclass? Is just a way to reuse code. (...) the one that has more code that is reusable by the other
class should be the parent. If the Dog has more code that is useful for Animal, put the Dog on top.”
http://www.youtube.com/watch?feature=player_detailpage&v=miGolgp9xq8#t=640
as object oriented languages (VI)
polymorphism

[1]

- ad-hoc polymorphism: function overloading [already covered]
- parametric polymorphism: generic type that can handle
different types without worrying about their types.
Java: generics:
List<String> l = new ArrayList<String>();
Python: builtin:
l = []

[1]three types of polymorphism, according to wikipedia http://en.wikipedia.
org/wiki/Polymorphism_(computer_science)
as object oriented languages (VII)
polymorphism
- subtyping polymorphism: duck and chicken walk differently

Java: inheritance + interfaces + static typing
public class Duck extends Bird implements Swimmer{
public String quack(){

(...)

public void walk(){

(...)

(...)

Duck donald = new Duck();
donald.walk();
donald.fly();
donald.quack();
donald.swim();
[1]three types of polymorphism, according to wikipedia http://en.wikipedia.
org/wiki/Polymorphism_(computer_science)
as object oriented languages (VII)
polymorphism
- subtyping polymorphism: duck and chicken walk differently

Python: inheritance + duck typing + protocols
class Duck(Bird):
def quack():
def walk():

(...)
(...)

(...)

donald = Duck()
donald.walk()
donald.fly()
donald.quack()
donald.swim()
[1]three types of polymorphism, according to wikipedia http://en.wikipedia.
org/wiki/Polymorphism_(computer_science)
as object oriented languages (VII)
encapsulation:
OCP (open closed principle) : "software entities (classes, modules,
functions, etc.) should be open for extension, but closed for modification"
http://en.wikipedia.org/wiki/Open/closed_principle

visibility (public, protected, ...), javabeans (Java)
versus
"_", "we are all consenting adults here" (Python)

[1]

Python name mangling.
[1] from python mail: https://mail.python.org/pipermail/tutor/2003-October/025932.
html
execution model (I)
Python execution model differs from those of Java and C++.

In Python everything is a name bounded to an object.
In Java class lifecycle is
separated in load,
initialization and execution.

In Python, LoC are executed.
No separation between
declaration and execution.

1. Class resolved and loaded.
2. Class is initialized.
3. Code in class used.

Functions (def)
(class)

Modules
Entry points to code well
defined: main

Classes

(import)

Entry points to code are the
same modules
execution model (III)

●

Diferenciate explicit execution from import time execution?

if __name__ == ‘_main__’:
“””your program here”””
execution model (III)
●
●
●

implicit variable declaration
duplicate declarations
parameter default values that are mutable

class A(object):
def __init__(self, p1=0,
p2=None,p3=[]):
self.v1 = p1
self.v2 = p2
self.v3 = p3
def method1(self, p):
self.v3.append(p)
def method1(self, p1, p2):
self.lastp1 = p1
self.v3.append(p2)
print self.lastp1

In [5]: a = A(p2=3)
In [6]: a.method1(1, 2)
1
In [9]: print a.lastp1
1
In [10]: a2 = A(p1=3)
In [12]: print a2.v3
[2]
In [13]: print a.v3
[2]
execution model (IV)
monkey patching
class A(object):
def __init__(self, p1=0,
p2=None,p3=[]):
self.v1 = p1
self.v2 = p2
self.v3 = p3
def method1(self, p):
self.v3.append(p)
def method1(self, p1, p2):
self.lastp1 = p1
self.v3.append(p2)
print self.lastp1

In [22]: a = A()
In [23]: a.method1(1, 2)
1
In [24]: def m1(self, p, p2):
print 'modified ' + str
(p)
....:
In [25]: A.method1 = m1
In [26]: a.method1(1, 2)
modified 1

Remember: in Python everything is a name bounded to an object.
wrap up

You solve the problems.
The most important part of
any language is you, the
developer.
No clear winner, today I
prefer Python.

Thanks for attending!

Contenu connexe

Tendances

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programmingSrinivas Narasegouda
 
Introduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsIntroduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsPhoenix
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1Kirti Verma
 
Python Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and PolymorphismPython Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and PolymorphismRanel Padon
 
Python-00 | Introduction and installing
Python-00 | Introduction and installingPython-00 | Introduction and installing
Python-00 | Introduction and installingMohd Sajjad
 
A Featherweight Approach to FOOL
A Featherweight Approach to FOOLA Featherweight Approach to FOOL
A Featherweight Approach to FOOLgreenwop
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
C++0x :: Introduction to some amazing features
C++0x :: Introduction to some amazing featuresC++0x :: Introduction to some amazing features
C++0x :: Introduction to some amazing featuresChristian Perone
 
Introduction to python 3
Introduction to python 3Introduction to python 3
Introduction to python 3Youhei Sakurai
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objectsrahulsahay19
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd roundYouhei Sakurai
 
Introduction about Python by JanBask Training
Introduction about Python by JanBask TrainingIntroduction about Python by JanBask Training
Introduction about Python by JanBask TrainingJanBask Training
 

Tendances (20)

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python ppt
Python pptPython ppt
Python ppt
 
Python Tutorial for Beginner
Python Tutorial for BeginnerPython Tutorial for Beginner
Python Tutorial for Beginner
 
Introduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsIntroduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data Analytics
 
Oop basic concepts
Oop basic conceptsOop basic concepts
Oop basic concepts
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
 
Python Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and PolymorphismPython Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and Polymorphism
 
Python-00 | Introduction and installing
Python-00 | Introduction and installingPython-00 | Introduction and installing
Python-00 | Introduction and installing
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
A Featherweight Approach to FOOL
A Featherweight Approach to FOOLA Featherweight Approach to FOOL
A Featherweight Approach to FOOL
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
C++0x :: Introduction to some amazing features
C++0x :: Introduction to some amazing featuresC++0x :: Introduction to some amazing features
C++0x :: Introduction to some amazing features
 
Python - Lesson 1
Python - Lesson 1Python - Lesson 1
Python - Lesson 1
 
Introduction to python 3
Introduction to python 3Introduction to python 3
Introduction to python 3
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd round
 
Introduction about Python by JanBask Training
Introduction about Python by JanBask TrainingIntroduction about Python by JanBask Training
Introduction about Python by JanBask Training
 
Oop
OopOop
Oop
 

En vedette

Jython: Integrating Python and Java
Jython: Integrating Python and JavaJython: Integrating Python and Java
Jython: Integrating Python and JavaCharles Anderson
 
Ruby vs python
Ruby vs pythonRuby vs python
Ruby vs pythonIgor Leroy
 
Closing the gap between Distros(devs) and their Users(ops)
Closing the gap between Distros(devs) and their Users(ops)Closing the gap between Distros(devs) and their Users(ops)
Closing the gap between Distros(devs) and their Users(ops)Kris Buytaert
 
Dev secops opsec, devsec, devops ?
Dev secops opsec, devsec, devops ?Dev secops opsec, devsec, devops ?
Dev secops opsec, devsec, devops ?Kris Buytaert
 

En vedette (7)

Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Jython: Integrating Python and Java
Jython: Integrating Python and JavaJython: Integrating Python and Java
Jython: Integrating Python and Java
 
Ruby vs python
Ruby vs pythonRuby vs python
Ruby vs python
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
Closing the gap between Distros(devs) and their Users(ops)
Closing the gap between Distros(devs) and their Users(ops)Closing the gap between Distros(devs) and their Users(ops)
Closing the gap between Distros(devs) and their Users(ops)
 
Dev secops opsec, devsec, devops ?
Dev secops opsec, devsec, devops ?Dev secops opsec, devsec, devops ?
Dev secops opsec, devsec, devops ?
 
Mixing Python and Java
Mixing Python and JavaMixing Python and Java
Mixing Python and Java
 

Similaire à From Java to Python: beating the Stockholm syndrome

These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2sadhana312471
 
PRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxPRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxabhishek364864
 
Interview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfInterview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfExaminationSectionMR
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxRohitKumar639388
 
Pursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHPPursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHPGiorgio Sironi
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| FundamentalsMohd Sajjad
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming LanguageYLTO
 
PythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programmingPythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programmingKhadijaKhadijaAouadi
 

Similaire à From Java to Python: beating the Stockholm syndrome (20)

These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
PRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxPRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptx
 
Oop java
Oop javaOop java
Oop java
 
Python for dummies
Python for dummiesPython for dummies
Python for dummies
 
Interview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfInterview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdf
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Python training
Python trainingPython training
Python training
 
Pursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHPPursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHP
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Python
PythonPython
Python
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Core java part1
Core java  part1Core java  part1
Core java part1
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming Language
 
PYTHON PPT.pptx
PYTHON PPT.pptxPYTHON PPT.pptx
PYTHON PPT.pptx
 
обзор Python
обзор Pythonобзор Python
обзор Python
 
PythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programmingPythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programming
 

Plus de Javier Arias Losada

Why do lazy developers write beautiful code?
Why do lazy developers write beautiful code?Why do lazy developers write beautiful code?
Why do lazy developers write beautiful code?Javier Arias Losada
 
Europython - Machine Learning for dummies with Python
Europython - Machine Learning for dummies with PythonEuropython - Machine Learning for dummies with Python
Europython - Machine Learning for dummies with PythonJavier Arias Losada
 
Pybcn machine learning for dummies with python
Pybcn machine learning for dummies with pythonPybcn machine learning for dummies with python
Pybcn machine learning for dummies with pythonJavier Arias Losada
 
OSCON - ES6 metaprogramming unleashed
OSCON -  ES6 metaprogramming unleashedOSCON -  ES6 metaprogramming unleashed
OSCON - ES6 metaprogramming unleashedJavier Arias Losada
 
Elastically scalable architectures with microservices. The end of the monolith?
Elastically scalable architectures with microservices. The end of the monolith?Elastically scalable architectures with microservices. The end of the monolith?
Elastically scalable architectures with microservices. The end of the monolith?Javier Arias Losada
 
Full Stack Bus with Javascript, RabbitMQ and Postal.js
Full Stack Bus with Javascript, RabbitMQ and Postal.jsFull Stack Bus with Javascript, RabbitMQ and Postal.js
Full Stack Bus with Javascript, RabbitMQ and Postal.jsJavier Arias Losada
 
Rabbitmq, amqp Intro - Messaging Patterns
Rabbitmq, amqp Intro - Messaging PatternsRabbitmq, amqp Intro - Messaging Patterns
Rabbitmq, amqp Intro - Messaging PatternsJavier Arias Losada
 
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel MessagingNoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel MessagingJavier Arias Losada
 

Plus de Javier Arias Losada (9)

Why do lazy developers write beautiful code?
Why do lazy developers write beautiful code?Why do lazy developers write beautiful code?
Why do lazy developers write beautiful code?
 
Europython - Machine Learning for dummies with Python
Europython - Machine Learning for dummies with PythonEuropython - Machine Learning for dummies with Python
Europython - Machine Learning for dummies with Python
 
Pybcn machine learning for dummies with python
Pybcn machine learning for dummies with pythonPybcn machine learning for dummies with python
Pybcn machine learning for dummies with python
 
OSCON - ES6 metaprogramming unleashed
OSCON -  ES6 metaprogramming unleashedOSCON -  ES6 metaprogramming unleashed
OSCON - ES6 metaprogramming unleashed
 
ES6 metaprogramming unleashed
ES6 metaprogramming unleashedES6 metaprogramming unleashed
ES6 metaprogramming unleashed
 
Elastically scalable architectures with microservices. The end of the monolith?
Elastically scalable architectures with microservices. The end of the monolith?Elastically scalable architectures with microservices. The end of the monolith?
Elastically scalable architectures with microservices. The end of the monolith?
 
Full Stack Bus with Javascript, RabbitMQ and Postal.js
Full Stack Bus with Javascript, RabbitMQ and Postal.jsFull Stack Bus with Javascript, RabbitMQ and Postal.js
Full Stack Bus with Javascript, RabbitMQ and Postal.js
 
Rabbitmq, amqp Intro - Messaging Patterns
Rabbitmq, amqp Intro - Messaging PatternsRabbitmq, amqp Intro - Messaging Patterns
Rabbitmq, amqp Intro - Messaging Patterns
 
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel MessagingNoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
NoSQL Matters BCN 2013. Sprayer Low Latency, Reliable, Mutichannel Messaging
 

Dernier

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Dernier (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

From Java to Python: beating the Stockholm syndrome

  • 1. from java to python beating the stockholm syndrome Javier Arias Losada @javier_arilos
  • 2. We are going to compare Java versus Python through some random topics… but not trying to be exhaustive or follow any logical patterns… just aspects I liked, disliked or just caught my attention. Disclaimer 1. Some points have been improved in latest versions of Python and Java 2. Opinions stated are those of the author, Javier Arias
  • 3. Working since 1997 with OO languages, mainly in Java and some Smalltalk… one has some rigidness regarding idioms, mental schemes and patterns… Python approach to many aspects is different from Java and tends to be more pragmatic.
  • 4. verbosity and ease of reading (I) “(…) when you program, you have to think about how someone will read your code, not just how a computer will interpret it.” - Kent Beck Indentation, expressiveness and idioms, libraries matter. BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { // do something with line. } br.close(); with open(...) as f: for line in f: # do something with line http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-in-java http://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python
  • 5. verbosity and ease of reading (II) logical expressions & truthy values: if x and x not in elements: print ‘done’ if (x != null && !elements.contains(x)) { System.out.println(“done”); } Python seems to be ahead here, improves this productivity? Usually code is easier to read and maintain in Python. Refactoring is faster and more secure in Java (static typing + advanced IDE’s).
  • 6. verbosity and ease of reading (III) method and function definition An example: parse N lines of a file, searching for a text Python keyword args: named and optional, default values. def search(txt, file=’./f.txt’, lines=0): return 0 Java method overriding: different methods with different parameters (number and type) public int search(String txt, String file, Integer lines){ return 0; }
  • 7. verbosity and ease of reading (IV) Lets add optional params in Java: public int search(String txt, Integer lines){ search(txt, “./f.txt”, lines); } public int search(String txt, String file){ search(txt, file, 0); } Java’s method signature overriding is very useful for maintaining functions (and constructors) less cluttered.
  • 8. verbosity and ease of reading (V) New Requirement: extend our search function to search for a client’s name, accept instances of Client class. public int search(Client client, String file){ search(client.getName(), file); } def search(what, file=’./f.txt’, lines=0): if isinstance(what, Client): what = what.name (...) Results of the exercise: Java: one core method and three “facilitator” methods. Python: one method that is caring about type of parameters.
  • 9. verbosity and ease of reading (VI) List and dictionary comprehensions a real example: filtering a dictionary. filtered_policies = {pol: spr_message.policies[pol] for pol in _GCM_ALLOWED_POLICIES if pol in spr_message.policies} Python Dict and list comprehension are very flexible and powerful ways of creating lists and dict on the fly. filteredPolicies = sprMessage.getPolicies().keySet() .retainAll(GCM_ALLOWED_POLICIES); Java is usually more verbose and less fluent for this collection related tasks, but sometimes a well designed API can do miracles, as in this example.
  • 10. verbosity and ease of reading (end) searched google looking for the shortest tutorials of each language: As an objective indicator, Teach yourself Java in 21 minutes: http://www.debevc.uni-mb.si/IT2003/Razno/teach_Java_21_minutes.pdf Learn Python in 10 minutes: http://www.stavros.io/tutorials/python/ Python is half as verbose as Java. If you ignore me, in the time of this talk you can learn both languages. Just joking :-)
  • 11. as object oriented languages (I) inheritance Liskov Substitution Principle: If S is a subtype of T, then objects of type T may be replaced with objects of type S. Use your code without caring about what type or subtype it is. Java simple inheritance. interfaces. statically-strongly typed. Python multiple inheritance. dynamically-strongly typed.
  • 12. as object oriented languages (II) composition-inheritance-multiple inheritance “In object-oriented programming, Inheritance is the evil forest (...) deep inside the Dark Forest Inheritance is the Evil Queen Multiple Inheritance (...)” - Learn Python the hard way: http://bit.ly/O709e9 Java super super(); super.aMethod(); Python super super(class, object) super may not call parent: MRO A / super always call parent. B C / D About MRO in Python: http://bit.ly/18RHQBC
  • 13. as object oriented languages (III) inheritance The Circle / Ellipse problem: ➔ In maths, circle is a special case for an ellipse: both axes are equal ➔ Who should be superclass and subclass? ◆ ◆ If Ellipse is the parent: what happens with the Ellipse method that stretches an axis? what does that mean for Circle instances? If Circle is the parent, seems counterintuitive and no code reused. Two ways of thinking about subclassing: 1. 2. The OO classic view Pragmatic’s non-taxonomy based approach
  • 14. as object oriented languages (IV) inheritance, classic OO view a subclass is a specialization of a superclass. Organize your code by taxonomies: "Is-a" relationships. e.g. Dog is-an Animal. "Inheritance is the idea that one class is a specialization of another class." Code Complete. This is what the majority of us do: at least in Java, probably in Python as well.
  • 15. as object oriented languages (V) inheritance, alternative approach Inheritance as a mechanism for code reuse, nothing to do with taxonomies. Raymond Hettinger, Python core developer: Put the Dog on top, if the Dog has more code that is useful for Animal From The art of subclassing, Raymond Hettinger. "How do you decide which one is on top? There is no principle of specialization. (...) Why do we subclass? Is just a way to reuse code. (...) the one that has more code that is reusable by the other class should be the parent. If the Dog has more code that is useful for Animal, put the Dog on top.” http://www.youtube.com/watch?feature=player_detailpage&v=miGolgp9xq8#t=640
  • 16. as object oriented languages (VI) polymorphism [1] - ad-hoc polymorphism: function overloading [already covered] - parametric polymorphism: generic type that can handle different types without worrying about their types. Java: generics: List<String> l = new ArrayList<String>(); Python: builtin: l = [] [1]three types of polymorphism, according to wikipedia http://en.wikipedia. org/wiki/Polymorphism_(computer_science)
  • 17. as object oriented languages (VII) polymorphism - subtyping polymorphism: duck and chicken walk differently Java: inheritance + interfaces + static typing public class Duck extends Bird implements Swimmer{ public String quack(){ (...) public void walk(){ (...) (...) Duck donald = new Duck(); donald.walk(); donald.fly(); donald.quack(); donald.swim(); [1]three types of polymorphism, according to wikipedia http://en.wikipedia. org/wiki/Polymorphism_(computer_science)
  • 18. as object oriented languages (VII) polymorphism - subtyping polymorphism: duck and chicken walk differently Python: inheritance + duck typing + protocols class Duck(Bird): def quack(): def walk(): (...) (...) (...) donald = Duck() donald.walk() donald.fly() donald.quack() donald.swim() [1]three types of polymorphism, according to wikipedia http://en.wikipedia. org/wiki/Polymorphism_(computer_science)
  • 19. as object oriented languages (VII) encapsulation: OCP (open closed principle) : "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification" http://en.wikipedia.org/wiki/Open/closed_principle visibility (public, protected, ...), javabeans (Java) versus "_", "we are all consenting adults here" (Python) [1] Python name mangling. [1] from python mail: https://mail.python.org/pipermail/tutor/2003-October/025932. html
  • 20. execution model (I) Python execution model differs from those of Java and C++. In Python everything is a name bounded to an object. In Java class lifecycle is separated in load, initialization and execution. In Python, LoC are executed. No separation between declaration and execution. 1. Class resolved and loaded. 2. Class is initialized. 3. Code in class used. Functions (def) (class) Modules Entry points to code well defined: main Classes (import) Entry points to code are the same modules
  • 21. execution model (III) ● Diferenciate explicit execution from import time execution? if __name__ == ‘_main__’: “””your program here”””
  • 22. execution model (III) ● ● ● implicit variable declaration duplicate declarations parameter default values that are mutable class A(object): def __init__(self, p1=0, p2=None,p3=[]): self.v1 = p1 self.v2 = p2 self.v3 = p3 def method1(self, p): self.v3.append(p) def method1(self, p1, p2): self.lastp1 = p1 self.v3.append(p2) print self.lastp1 In [5]: a = A(p2=3) In [6]: a.method1(1, 2) 1 In [9]: print a.lastp1 1 In [10]: a2 = A(p1=3) In [12]: print a2.v3 [2] In [13]: print a.v3 [2]
  • 23. execution model (IV) monkey patching class A(object): def __init__(self, p1=0, p2=None,p3=[]): self.v1 = p1 self.v2 = p2 self.v3 = p3 def method1(self, p): self.v3.append(p) def method1(self, p1, p2): self.lastp1 = p1 self.v3.append(p2) print self.lastp1 In [22]: a = A() In [23]: a.method1(1, 2) 1 In [24]: def m1(self, p, p2): print 'modified ' + str (p) ....: In [25]: A.method1 = m1 In [26]: a.method1(1, 2) modified 1 Remember: in Python everything is a name bounded to an object.
  • 24. wrap up You solve the problems. The most important part of any language is you, the developer. No clear winner, today I prefer Python. Thanks for attending!