53
Theory and practice – migrating your legacy code into our modern test driven development world. Hartmann, Jankowfsky, Rinne

Theory and practice – migrating your legacy code into our modern test driven development world

Embed Size (px)

Citation preview

Page 1: Theory and practice – migrating your  legacy code into our modern test  driven development world

Theory and practice – migrating your legacy code into our modern test driven development world.

Hartmann, Jankowfsky, Rinne

Page 2: Theory and practice – migrating your  legacy code into our modern test  driven development world

Jankowfsky, Rinne – Mayflower/swoodoo

Legacy Code?

Wikipedia says „Legacy code is source code that relates to a no-longer supported or manufactured operating system or other computer technology. The term can also mean code inserted into modern software for the purpose of maintaining an older or previously supported feature“

Page 3: Theory and practice – migrating your  legacy code into our modern test  driven development world

Jankowfsky, Rinne – Mayflower/swoodoo

Agenda

- Where are we now, and why?

- Ammunition!

- Refactor!

Bad News? -> Workshop

Page 4: Theory and practice – migrating your  legacy code into our modern test  driven development world

Who we are

Johann Peter Hartmann:

- CTO and Founder of Mayflower GmbH

- CEO and Founder of SektionEins GmbH

Jankowfsky, Rinne – Mayflower/swoodoo

Lars Jankowfsky:

- CTO and (Co)Founder swoodoo.com

- (Co)Founder of OXID eSales. Refactored OXID eShop during 1.5 years with 10 developers.

Thorsten Rinne:

- Senior Developer & Team Lead at Mayflower GmbH

- Founder and main developer of phpMyFAQ

Page 5: Theory and practice – migrating your  legacy code into our modern test  driven development world

Who are you?

- What‘s your profession?

- Sofware company or agency?

- What‘s your team size?

- Using MVC?

- Who does other languages, too?

- Using agile methods?

- Using continuous integration?

- Using unit tests?

Jankowfsky, Rinne – Mayflower/swoodoo

Page 6: Theory and practice – migrating your  legacy code into our modern test  driven development world

What about your projects?

- What‘s your average project lifetime?

- Is there PHP code more than 5 years old?

- How many lines of code?

- How many change requests per year?

- Has there been a specification?

- Were all features in the first released version implemented like they‘re specified in the specification?

Jankowfsky, Rinne – Mayflower/swoodoo

Page 7: Theory and practice – migrating your  legacy code into our modern test  driven development world

Typical problems?

- Typical legacy applications

- Started some years ago with PHP 4

- written in Spaghetti code

- half procedual, half object-orientated

- „PHP 4“ OOP

- using old, unmaintained libraries like PEAR::DB

Jankowfsky, Rinne – Mayflower/swoodoo

Page 8: Theory and practice – migrating your  legacy code into our modern test  driven development world

PHP, made in 2000

- no coding standards

- no PHPDoc

- no Design Patterns

- few separation of concerns

- has been changed a lot

- no refactoring, because „it worked“

- updated to run with php 4 in 2003

- updated to run with php 5 in 2006

Jankowfsky, Rinne – Mayflower/swoodoo

Page 9: Theory and practice – migrating your  legacy code into our modern test  driven development world

Big ball of mud

Jankowfsky, Rinne – Mayflower/swoodoo

http://en.wikipedia.org/wiki/Big_ball_of_mud

A Big Ball of Mud is a haphazardly structured, sprawling, sloppy, duct-tape-and-baling-wire, spaghetti-code jungle.

These systems show unmistakable signs of unregulated growth, and repeated, expedient repair....

Page 10: Theory and practice – migrating your  legacy code into our modern test  driven development world

Enough Ammunition?

Jankowfsky, Rinne – Mayflower/swoodoo

- change requests get more and more expensive

- bug rate is increasing

- clearly a dead-end street!

- team motivation decreases

- hard to bring in new members into the team

- deprecated functions cause problems in future PHP releases

Page 11: Theory and practice – migrating your  legacy code into our modern test  driven development world

Enough Ammunition?

Ever heard things like this?

„Only X can fix that.“

„It will take ages to fix it.“

„Changing this button will take two weeks.“

„I don‘t want to work for this project.“

„I don‘t want to touch this code.“

„I don‘t know how this bug could reappear.“

Jankowfsky, Rinne – Mayflower/swoodoo

Page 12: Theory and practice – migrating your  legacy code into our modern test  driven development world

Enough Ammunition?

60-80 % of all development effort is maintenance

http://elearning.tvm.tcs.co.in/SMaintenance/SMaintenance/6.htm

http://www.bitpipe.com/detail/RES/1138902960_291.html

Jankowfsky, Rinne – Mayflower/swoodoo

Page 13: Theory and practice – migrating your  legacy code into our modern test  driven development world

What you should never do!

Please don‘t try a complete rewrite!

- Too expensive

- Takes too long

- the old codebase is used, tested & bugfixed

- Developers love to rewrite:new code is more fun, code is easier to write than to read

Jankowfsky, Rinne – Mayflower/swoodoo

Page 14: Theory and practice – migrating your  legacy code into our modern test  driven development world

Remember?

Jankowfsky, Rinne – Mayflower/swoodoo

Netscape 6? Rewrite....

dBase for Windows? Rewrite....

Quattro Pro? Rewrite....

Access refatored...

Excel

Page 15: Theory and practice – migrating your  legacy code into our modern test  driven development world

joel in 2000

„When you throw away code and start from scratch, you are throwing away all that knowledge. All those collected bug fixes. Years of programming work.“

http://www.joelonsoftware.com/articles/fog0000000069.html

Jankowfsky, Rinne – Mayflower/swoodoo

Page 16: Theory and practice – migrating your  legacy code into our modern test  driven development world

Test Driven Adoption

1. Unit tests for existing code with PHPUnit

2. experience of confidence in own code

3. Insight: Tests are easier if written before software

4. Insight: Tests help documenting the code

5. Insight: Tests define the real API

Jankowfsky, Rinne – Mayflower/swoodoo

Page 17: Theory and practice – migrating your  legacy code into our modern test  driven development world

PHP and Unit Testing

- Layout & UI code is hard to unit-test, acceptance-test instead

- test maintenance costs:- unit test work fine with stable APIs- high change rate in PHP results in API changes- tests need to be changed, too

- slows down development, increases initial development costs

- ... but your software survives more than 4 years

Jankowfsky, Rinne – Mayflower/swoodoo

Page 18: Theory and practice – migrating your  legacy code into our modern test  driven development world

Refactoring?

- Modifying code without changing it‘s behaviour

- „cleaning up“

Jankowfsky, Rinne – Mayflower/swoodoo

“Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure.” (Martin Fowler)

Page 19: Theory and practice – migrating your  legacy code into our modern test  driven development world

Team?

Jankowfsky, Rinne – Mayflower/swoodoo

- experience in Test driven Development?

- „know how vs. understanding“

- In PHP? It‘s different to the Java World!

- Developers are conservative. They do not like any changes. How much use still vi or emacs?

- Courage?- You need to make sure

that everybody understands TDD before you start.

Page 20: Theory and practice – migrating your  legacy code into our modern test  driven development world

Let‘s start.

- Identify the nastiest, ugliest and...

- probably most important piece of code and let‘s start with this one.

- if you take the easy files you won‘t solve the critical issues and...

- move the risk to the end.

Jankowfsky, Rinne – Mayflower/swoodoo

Page 21: Theory and practice – migrating your  legacy code into our modern test  driven development world

Jankowfsky, Rinne – Mayflower/swoodoo

COURAGE

Page 22: Theory and practice – migrating your  legacy code into our modern test  driven development world

Modifying without... ?????

- if you refactor you need tests to proove that you did not break any functionality

- Have tests first. Then change code.

- legacy code ? There are no tests!!

Jankowfsky, Rinne – Mayflower/swoodoo

Page 23: Theory and practice – migrating your  legacy code into our modern test  driven development world

And now ?

- Write tests first.

- You will need to refactor your application while writing tests.

Jankowfsky, Rinne – Mayflower/swoodoo

- Write selenium tests for your application. - no :(

Page 24: Theory and practice – migrating your  legacy code into our modern test  driven development world

While refactoring ...

- adjust coding style

- add missing documentation

- remove redundant code / copy & paste-code

- remove unused(!) code

- maintain a list of future todos with priorities

Jankowfsky, Rinne – Mayflower/swoodoo

Page 25: Theory and practice – migrating your  legacy code into our modern test  driven development world

Spaghetti Code?

Jankowfsky, Rinne – Mayflower/swoodoo

- Very old code, maybe developed in the last PHP 3 century

- a lot of redundant copy-paste code

- missing separation of concerns

- No or just minor separation of code and layout

- No use of libraries like PEAR, Zend Framework or eZ components

- No or outdated documentation

- No tests at all

Page 26: Theory and practice – migrating your  legacy code into our modern test  driven development world

Spaghetti Code?

Jankowfsky, Rinne – Mayflower/swoodoo

function getThema($id, $lang){global $db, $PMF_LANG;

$result = $db->query(sprintf("SELECT thema FROM %sfaqdata WHERE id = %d AND lang = '%s'", SQLPREFIX, $id, $lang));

if ($db->num_rows($result) > 0) { while ($row = $db->fetch_object($result)) { $output = htmlentities($row->thema);

} } else { $output = $PMF_LANG["no_cats"]; } return $output;

}

phpMyFAQ 1.3.x 2002/2003

Page 27: Theory and practice – migrating your  legacy code into our modern test  driven development world

Spaghetti Code - strategy

- Identify recurring code parts and implement classes

- Use of standard libraries like Zend Framework or eZ components

- Add inline documentation

- Fix your coding styles!

- Add unittests for the new, refactored backend

- Add Selenium tests for the frontend

Jankowfsky, Rinne – Mayflower/swoodoo

Page 28: Theory and practice – migrating your  legacy code into our modern test  driven development world

„Half procedual –halb object-orientated“

- Code with different quality

- Just a few documentation

- Maybe some tests ... maybe ...

- „the typical current PHP 4 project“

- Found everywhere! Really everywhere!

Jankowfsky, Rinne – Mayflower/swoodoo

Page 29: Theory and practice – migrating your  legacy code into our modern test  driven development world

„Half procedual –half object-orientated“ - strategy

- Add inline documentation for all classes and methods

- Improve the re-using of duplicate code

- Add unittests and Selenium tests

- Improve every code part with PHP 5 functions, for example using file_put_contents() instead of fopen(), fwrite(), and fclose().

Jankowfsky, Rinne – Mayflower/swoodoo

Page 30: Theory and practice – migrating your  legacy code into our modern test  driven development world

PHP 4 OOP

- Application was developed using „object-orientated“ PHP 4

- Using of - PHP 4 references - Re-declaration of $this

Jankowfsky, Rinne – Mayflower/swoodoo

Page 31: Theory and practice – migrating your  legacy code into our modern test  driven development world

PHP 4 OOP - strategy

- Maybe you‘re lucky and there are no problems. Maybe.

- If you see problems, they are fatal errors like - Objects are referenced by value - $foo =& new Foo();

- Solution: - Implement unittests - UsestandardAPIs

- Fix the PHP 5 problems

Jankowfsky, Rinne – Mayflower/swoodoo

Page 32: Theory and practice – migrating your  legacy code into our modern test  driven development world

Global Problems

- OOP, Public, Private ?

- Globals ?

- Super Globals...

- Session

- Cookies

Jankowfsky, Rinne – Mayflower/swoodoo

Page 33: Theory and practice – migrating your  legacy code into our modern test  driven development world

Proxy for testing protected methods

Jankowfsky, Rinne – Mayflower/swoodoo

public function getProxy($superClassName) { $proxyClassName = "{$superClassName}Proxy";

if (!class_exists($proxyClassName)) {

$class = <<<CLASS class $proxyClassName extends $superClassName { public function __call(\$function, \$args) { \$function = str_replace('protected_', '_', \$function); return call_user_func_array(array(&\$this, \$function), \$args); } }CLASS; eval($class); } return new $proxyClassName(); }

Page 34: Theory and practice – migrating your  legacy code into our modern test  driven development world

Global ?

Jankowfsky, Rinne – Mayflower/swoodoo

class someOtherClass { var $setting;

function calculateSomething($a, $b) { return $a+$b; }}

class myOldNastyClass {

function needToTestThisFunction() {

$class = new someOtherClass();

$z = $_GET['input'];

// ....

return $class->calculateSomething( $class->setting, $z); }}

Page 35: Theory and practice – migrating your  legacy code into our modern test  driven development world

Jankowfsky, Rinne – Mayflower/swoodoo

class someOtherClass { private $setting;

public function calculateSomething($a, $b) { return $a+$b; }

public function setSetting($set) { $this->setting = $set; }

public function getSetting() { return $this->setting; }}

class myInput { public function getParameter($name) { return $_GET[$name]; }}

class myOldNastyClass {

private $input; // set e.g. in constructor

public function needToTestThisFunction(someOtherClass &$class, $z) {

$z = $input->getParameter('input'); // ....

return $class->calculateSomething( $class->getSetting(), $z); }}

Page 36: Theory and practice – migrating your  legacy code into our modern test  driven development world

Dependencies...

- Separate Logic from View

- Create accessors, add all Parameter in calls

Jankowfsky, Rinne – Mayflower/swoodoo

Page 37: Theory and practice – migrating your  legacy code into our modern test  driven development world

Dependencies...

Jankowfsky, Rinne – Mayflower/swoodoo

class displayUserDetails(){ /** * Processes input and sends user first name, last name to display; */ function show() { global $dbLink; global $templateEngine; $itemId = (int) $_REQUEST['user_id']; $firstName = $dbLink->getOne("select first_name from users where id = $itemId"); $lastName = $dbLink->getOne("select last_name from users where id = $itemId"); $templateEngine->addTemplateVar('firstName', $firstName); $templateEngine->addTemplateVar('lastName', $lastName); $templateEngine->display(); }}

Page 38: Theory and practice – migrating your  legacy code into our modern test  driven development world

Jankowfsky, Rinne – Mayflower/swoodoo

/** * A view class responsible for displaying user details. */class userView(){ /** * Loads user object and sends first name, last name to display */ public function show() { $userId = $this->_inputProcessor->getParameter("user_id"); $this->templateEngine->addTemplateVar('user', $this->model->loadUser(userId)); $this->templateEngine->display(); }} /** * And the corresponding model */class userModel(){ public function loadUser($userId) { $user = new User( $userId ); return array( 'firstName' => $user->getFirstName(), 'lastName' => $user->getLastName()); }}

Page 39: Theory and practice – migrating your  legacy code into our modern test  driven development world

Fixtures

- Make sure that tests do not alter fixture.

- Fixture is FIXture

- if you feel that creating fixtures is too much work - refactor more!

- Do never let tests leave altered data!

Jankowfsky, Rinne – Mayflower/swoodoo

Page 40: Theory and practice – migrating your  legacy code into our modern test  driven development world

Fixtures the ruby way...

- Ruby uses „YAML Ain’t Markup Language“

- http://www.yaml.org/

- PHP YAML support done via Syck

- Syck = YAML + fast.

- http://whytheluckystiff.net/syck/

- http://www.frontalaufprall.com/2008/05/05/

Jankowfsky, Rinne – Mayflower/swoodoo

Page 41: Theory and practice – migrating your  legacy code into our modern test  driven development world

yaml - loading

Jankowfsky, Rinne – Mayflower/swoodoo

public static function create($fileName) { $fileName = 'Fixtures'.DIRECTORY_SEPARATOR.$fileName; ob_start(); include $fileName; $fileContents = ob_get_contents(); ob_clean(); $yamlData = syck_load($fileContents); return $yamlData; }

Page 42: Theory and practice – migrating your  legacy code into our modern test  driven development world

yaml - storing

Jankowfsky, Rinne – Mayflower/swoodoo

public static function load($fixtures, $tableName) { if (is_array($fixtures) && count($fixtures)) { foreach ($fixtures as $fixture) { if (is_array($fixture) && is_array(current($fixture))) { Fixtures::load($fixture, $tableName); } $fields = array_keys($fixture); $statement = "INSERT INTO $tableName (" . implode(', ', $fields) . ") VALUES (:" . implode(", :", $fields) . ")"; $stmt = self::$_db->prepare($statement); if (count($fixture)) { foreach ($fixture as $key => $value ) { $stmt->bindValue(':'.$key, $value); } } $stmt->execute(); self::$_usedTables[$tableName] = $tableName; } } }

Page 43: Theory and practice – migrating your  legacy code into our modern test  driven development world

yaml - cleanup

Jankowfsky, Rinne – Mayflower/swoodoo

if (!empty(self::$_usedTables)) { foreach (array_reverse(self::$_usedTables) as $tableName) { self::$_db->execute("TRUNCATE TABLE $tableName"); } }

Page 44: Theory and practice – migrating your  legacy code into our modern test  driven development world

Fixtures the other side...

- manual fixtures are too much work?

- use a test database

- think about automatic creation of yaml files

Jankowfsky, Rinne – Mayflower/swoodoo

Page 45: Theory and practice – migrating your  legacy code into our modern test  driven development world

Mocking Stubs?

Jankowfsky, Rinne – Mayflower/swoodoo

„...may simulate the behavior of existing code (such as a procedure on a remote machine) or be a temporary substitute for yet-to-be-developed code...“

Why do we need this ?

stub: einfache klasse, die so tut, als wäre sie wie das original mock: das gleiche, aber mit introspektion und von aussen konfigurierbar

Page 46: Theory and practice – migrating your  legacy code into our modern test  driven development world

Stubs

- Unit testing is about testing a unit of work, not a complete workflow

- isolates your code from external dependencies

- can be done with PHPunit, but doesn‘t need to

Jankowfsky, Rinne – Mayflower/swoodoo

Page 47: Theory and practice – migrating your  legacy code into our modern test  driven development world

Stubs

/** * A simple stub providing a simple result directly instead of using the database */class UserModelStub extends UserModel { public getUserCount() { return 10; }}

UserModelStub extends PHPUnit_Framework_Testcase { public function testGetUserCount() { $stub = $this->getMock(‘UserModel‘); $stub->expects($this->any())->method(‘getUserCount‘)->will($this->returnValue(10)); }}

Jankowfsky, Rinne – Mayflower/swoodoo

/** * The PHPUnit way */

Page 48: Theory and practice – migrating your  legacy code into our modern test  driven development world

Mock Objects

- Helpful tool to fake complex objects

- Useful to mock service apis, external software, ...

/** * The PHPUnit way */class UserModelTest extends PHPUnit_Framework_Testcase { public function testGetUserCountIsCalled() { $usermock = $this->getMock(‘UserModel‘); $usermock->expects($this->once())->method(‘getUserCount‘)->with($this->equalTo(ADMIN)); $admin = new AdminModel($usermock); $admin->getNumber(); }}

Jankowfsky, Rinne – Mayflower/swoodoo

Page 49: Theory and practice – migrating your  legacy code into our modern test  driven development world

About Mocking

- a better separation of concerns helps

- writing less mock objects

- writing easier mock objects

- if there is a lot of mock objects, rethink your architecture -> refactor more!

Jankowfsky, Rinne – Mayflower/swoodoo

Page 50: Theory and practice – migrating your  legacy code into our modern test  driven development world

Golden rules

- know your budget: what are your maintenance costs? What are the things you can‘t do now?

- there is no silver bullet. Introducing TDD takes A LOT of time

- TDD wins on the long run, not on the short

- Confident developers are efficient developers

- There is no way around proper coding style and documentation

- You have to rewrite code, some even twice.Jankowfsky, Rinne – Mayflower/swoodoo

Page 51: Theory and practice – migrating your  legacy code into our modern test  driven development world

Tools?

- CruiseControl for continous integration- PHPUnit- SeleniumRC and SeleniumIDE

- PHP Code Sniffer- PHP CodeBrowser

Jankowfsky, Rinne – Mayflower/swoodoo

Page 52: Theory and practice – migrating your  legacy code into our modern test  driven development world

Jankowfsky, Rinne – Mayflower/swoodoo

Questions?

Page 53: Theory and practice – migrating your  legacy code into our modern test  driven development world

Jankowfsky, Rinne – Mayflower/swoodoo

Thank you for your interest!

eMail: [email protected]@mayflower.de