Sadegh Aliakbary. Review Java Programming Language Principles of Object Oriented Programming...

52
Advanced Programming in Java Sadegh Aliakbary

Transcript of Sadegh Aliakbary. Review Java Programming Language Principles of Object Oriented Programming...

Advanced Programming in Java

Advanced Programming in JavaSadegh Aliakbary

ReviewJava Programming LanguagePrinciples of Object Oriented ProgrammingCharacteristics of objectsEncapsulationObjects in memoryReferencesHeapStackParameter PassingFall 2012Sharif University of Technology2Review (2)Initialization and CleanupConstructorfinalize()Order of initializationInitialization blocksAccess specifiersPublicPrivatePackage accessFall 2012Sharif University of Technology3Review (3)PackageStaticThe this referenceMethod overloadingtoString()equals()RefactoringBad smellsRefactoring techniquesFall 2012Sharif University of Technology4AgendaSoftware Quality Characteristic of a good softwareTestUnit TestingRefactoring

Fall 2012Sharif University of Technology5Quality of ProductThe producer should ensure about the quality of the productsQuality ControlAny business, any product

Fall 2012Sharif University of Technology6A CookFall 2012Sharif University of Technology7

In surgeryFall 2012Sharif University of Technology8

A Car MakerFall 2012Sharif University of Technology9

Quality ControlQuality should be tested

A product is not finalized, before the test

Different kinds of test, check different kinds of qualityFall 2012Sharif University of Technology10

Software QualityWe are programmersProgrammers produce softwareWhat are characteristics of a good software?Many parameters. E.g.Conformance to requirementsPerformanceTime MemoryMaintainabilityChangeabilityDifferent kinds of test, check different kinds of quality

Fall 2012Sharif University of Technology11Test in Other IndustriesTest side effectsA damage to the productTest of a buildingTest of a carTest of a part of a product

Fall 2012Sharif University of Technology12Test Side EffectsFall 2012Sharif University of Technology13

What to do with Test Side Effects?Testing a sample of the productSimulationMathematical analysis

In software testingAlong with all of these techniques And we can also test the software itself!(Usually) no damage to the software Fall 2012Sharif University of Technology14Test TargetSystem TestTest the system as a wholeFor performance, correctness and conformance.Unit TestTest the units and modulesTest of a componentTest of a classTest of a methodFall 2012Sharif University of Technology15How to Test SoftwareManual TestTry it!Test ToolsPerformance TestProfilingJProfiler, TPTPLoad Test JmeterTest CodeUnit TestsTest TeamsFall 2012Sharif University of Technology16Test CodeBusiness CodeThe code, written for implementation of a requirement

Test CodeThe code, written for test of an implementationFall 2012Sharif University of Technology17Unit TestingA process for the programmerNot a test team procedureFor improving the code qualityReduces bugsTest of units of software before the software is completedUnit: method, class

Fall 2012Sharif University of Technology18

Classical Unit TestingWriting main() methodSome printlnsDrawbacks?Fall 2012Sharif University of Technology19DrawbacksTest code coupled with business codeIn the same classWritten tests are discardedOne test at a timeThe programmer executes the tests himselfTest execution is not automaticThe programmer should check the result of each test himselfThe test is passed or failed?The test result interpretation is not automaticFall 2012Sharif University of Technology20A Good Unit Test CodeRepeatableAutomaticInvocationAcceptance (Pass/Failure)

JUnit helps you write such testsFall 2012Sharif University of Technology21JUnit, First ExampleFall 2012Sharif University of Technology22

JUnit, The Green BarFall 2012Sharif University of Technology23

public class Testing {@Testpublic void testNormal() {int[] array = {3,2,1,4};int[] sorted = {1,2,3,4};Business.sort(array);for (int i = 0; i < sorted.length; i++) {Assert.assertEquals(sorted[i], array[i]);}}@Testpublic void testEmptyArray() {int[] array = {};try{Business.sort(array);}catch(Exception e){Assert.fail();}Assert.assertNotNull(array);Assert.assertEquals(array.length, 0);}}

Fall 2012Sharif University of Technology24AssertionsassertNull(x)assertNotNull(x)assertTrue(boolean x)assertFalse(boolean x)assertEquals(x, y)Uses x.equals(y)assertSame(x, y) Uses x ==yassertNotSamefail()

Fall 2012Sharif University of Technology25Annotations@Test@Before@After@BeforeClass@AfterClassFall 2012Sharif University of Technology26Fall 2012Sharif University of Technology27

A Good Unit Test isAutomatedThroughRepeatableIndependenceProfessional

Fall 2012Sharif University of Technology28Test Driven DevelopmentTest First DevelopmentBefore writing a code, write the tests!

Fall 2012Sharif University of Technology29TDDFall 2012Sharif University of Technology30

RefactoringRefactoringA disciplined way to restructure codeIn order to improve code qualityWithout changing its behavior

a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.Fall 2012Sharif University of Technology32Martin FowlerRefactoringRefactoring is the process of changing a software system In such a way that it does not alter the external behavior of the code But improves its internal structureIt is a disciplined way to clean up code It minimizes the chances of introducing bugsWhen you refactor, you are improving the design of the code after it has been written.

Fall 2012Sharif University of Technology33Martin Fowler

RefactoringBy continuously improving the design of code, we make it easier and easier to work withFall 2012Sharif University of Technology34Joshua Kerievsky, Refactoring to PatternsExampleDuplicate CodeWhat are the drawbacks?What is the solution?

Refactoring:Finding a Bad SmellChanging the code to remove the bad smellSome well-known bad smells are reportedFall 2012Sharif University of Technology35Bad SmellA bad smell in codeAny symptom in the source code that possibly indicates a deeper problem.The term is coined by Kent Beck.Fall 2012Sharif University of Technology36

Bad SmellsIf it stinks, change it!Kent Beck and Martin Fowler.Bad smells in codeBad smells are source of problemsRemove bad smellsHow?By RefactoringFall 2012Sharif University of Technology37Bad SmellsDuplicated CodeLong MethodLarge ClassLong Parameter ListFall 2012Sharif University of Technology38Refactoring TechniquesExtract MethodMove MethodVariableClassExtract ClassRenameMethodVariableClassPull UpPush DownFall 2012Sharif University of Technology39IDE SupportRefactoring techniques are widely supported by IDEs

Practice it in EclipseFall 2012Sharif University of Technology40

The Two HatsKent Beck's metaphor of two hatsDivide your time between two distinct activitiesadding functionrefactoringFall 2012Sharif University of Technology41Why Should I Refactor?Refactoring Improves the Design of SoftwareRefactoring Makes Software Easier to UnderstandRefactoring Helps You Find BugsRefactoring Helps You Program Faster

Refactoring makes your code more maintainableFall 2012Sharif University of Technology42When Should You Refactor?The Rule of Three:Refactor When You Add FunctionRefactor When You Need to Fix a BugRefactor As You Do a Code ReviewFall 2012Sharif University of Technology43Scanner s = new Scanner(System.in);

System.out.println("Rectangle Info.");System.out.print("Enter the width: ");int a1 = s.nextInt();System.out.print("Enter the length: ");int a2 = s.nextInt();

System.out.println("Rectangle Info.");System.out.print("Enter the width: ");int b1 = s.nextInt();System.out.print("Enter the length: ");int b2 = s.nextInt();

int x = a1*a2;int y = b1*b2;

if(x == y)System.out.println("Equal");

Fall 2012Sharif University of Technology44Find bad smells!Refactor the Code!Scanner scanner = new Scanner(System.in);

System.out.println("Rectangle Info.");System.out.print("Enter the width: ");int width1 = scanner.nextInt();System.out.print("Enter the length: ");int length1 = scanner.nextInt();

System.out.println("Rectangle Info.");System.out.print("Enter the width: ");int width2 = scanner.nextInt();System.out.print("Enter the length: ");int length2 = scanner.nextInt();

int area1 = width1*length1;int area2 = width2*length2;

if(area1 == area2)System.out.println("Equal");Fall 2012Sharif University of Technology45Renameclass Rectangle{private int length , width;public int getLength() {return length;}public void setLength(int length) {this.length = length;}public int getWidth() {return width;}public void setWidth(int width) {this.width = width;}public Rectangle(int length, int width) {this.length = length;this.width = width;}}

Fall 2012Sharif University of Technology46Extract ClassScanner scanner = new Scanner(System.in);

System.out.println("Rectangle Info.");System.out.print("Enter the width: ");int width = scanner.nextInt();System.out.print("Enter the length: ");int length = scanner.nextInt();Rectangle rectangle1 = new Rectangle(length, width);

System.out.println("Rectangle Info.");System.out.print("Enter the width: ");width = scanner.nextInt();System.out.print("Enter the length: ");length = scanner.nextInt();Rectangle rectangle2 = new Rectangle(length, width);

int area1 = rectangle1.getWidth()*rectangle1.getLength();int area2 = rectangle2.getWidth()*rectangle2.getLength();

if(area1 == area2)System.out.println("Equal");

Fall 2012Sharif University of Technology47class Rectangle{...public int area(){return length * width;}}

int area1 = rectangle1.area();int area2 = rectangle2.area();

Fall 2012Sharif University of Technology48Extract Methodprivate static Rectangle readRectangle(Scanner scanner) {int width;int length;System.out.println("Rectangle Info.");System.out.print("Enter the width: ");width = scanner.nextInt();System.out.print("Enter the length: ");length = scanner.nextInt();Rectangle rectangle2 = new Rectangle(length, width);return rectangle2;}

Fall 2012Sharif University of Technology49Extract MethodRefactored CodeScanner scanner = new Scanner(System.in);

Rectangle rectangle1 = readRectangle(scanner);Rectangle rectangle2 = readRectangle(scanner);

int area1 = rectangle1.area();int area2 = rectangle2.area();

if(area1 == area2)System.out.println("Equal");Fall 2012Sharif University of Technology50ReferenceRefactoring: improving the design of existing code, Martin Fowler, Kent Beck,John Brant, William Opdyke, Don Roberts(1999)Fall 2012Sharif University of Technology51Fall 2012Sharif University of Technology52