+ All Categories
Home > Documents > Salman Marvasti Sharif University of Technology Fall 2015.

Salman Marvasti Sharif University of Technology Fall 2015.

Date post: 04-Jan-2016
Category:
Upload: myron-rich
View: 216 times
Download: 1 times
Share this document with a friend
Popular Tags:
52
Advanced Programming in Java Salman Marvasti Sharif University of Technology Fall 2015
Transcript

Advanced Programming in Java

Advanced Programming in JavaSalman MarvastiSharif University of TechnologyFall 2015ReviewJava Programming LanguagePrinciples of Object Oriented ProgrammingCharacteristics of objectsEncapsulationObjects in memoryReferencesHeapStackParameter PassingSharif University of Technology2Review (2)Initialization and CleanupConstructorfinalize()Order of initializationInitialization blocksAccess specifiersPublicPrivatePackage accessSharif University of Technology3Review (3)PackageStaticThe this referenceMethod overloadingtoString()equals()PolymorphismOverriding , UpcastingInterfaceSharif University of Technology4AgendaSoftware Quality Characteristic of a good softwareTestUnit TestingRefactoring

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

Sharif University of Technology6A CookSharif University of Technology7

In surgerySharif University of Technology8

A Car Maker

Sharif University of Technology9

Quality ControlQuality should be tested

A product is not finalized, before the test

Different kinds of test, check different kinds of qualitySharif 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

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

Sharif University of Technology12Test Side EffectsSharif 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 Sharif 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 methodSharif University of Technology15How to Test SoftwareManual TestTry it!Test ToolsPerformance TestProfilingJProfiler, TPTPLoad Test JmeterTest CodeUnit TestsTest TeamsSharif University of Technology16Test CodeBusiness CodeThe code, written for implementation of a requirement

Test CodeThe code, written for test of an implementationSharif University of Technology1717Unit 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

Sharif University of Technology18

Classical Unit TestingWriting main() methodSome printlnsDrawbacks?Sharif 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 automaticSharif University of Technology20A Good Unit Test CodeRepeatableAutomaticInvocationAcceptance (Pass/Failure)

JUnit helps you write such testsSharif University of Technology21JUnit, First ExampleSharif University of Technology22

JUnit, The Green BarSharif 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);}}

Sharif 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()

Sharif University of Technology25Annotations@Test@Before@After@BeforeClass@AfterClassSharif University of Technology26Sharif University of Technology27

A Good Unit Test isAutomatedThroughRepeatableIndependenceProfessional

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

Sharif University of Technology29TDDSharif 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.Sharif 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.

Sharif University of Technology33Martin Fowler

RefactoringBy continuously improving the design of code, we make it easier and easier to work withSharif 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 reportedSharif 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.Sharif 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 RefactoringSharif University of Technology37Bad SmellsDuplicated CodeLong MethodLarge ClassLong Parameter ListSharif University of Technology38Refactoring TechniquesExtract MethodMove MethodVariableClassExtract ClassRenameMethodVariableClassPull UpPush DownSharif University of Technology39IDE SupportRefactoring techniques are widely supported by IDEs

Practice it in EclipseSharif University of Technology40

The Two HatsKent Beck's metaphor of two hatsDivide your time between two distinct activitiesadding functionrefactoringSharif 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 maintainableSharif 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 ReviewSharif 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");

Sharif 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");Sharif 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;}}

Sharif 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");

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

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

Sharif 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;}

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

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

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

if(area1 == area2)System.out.println("Equal");Sharif University of Technology50ReferenceRefactoring: improving the design of existing code, Martin Fowler, Kent Beck,John Brant, William Opdyke, Don Roberts(1999)Sharif University of Technology51Sharif University of Technology52Additional Info for Bulk Test and Bulk Data Operations ONLY JAVA 1.8Listnames=Arrays.asList("Smith","Adams","Crawford"); Listpeople=peopleDAO.find("London"); //UsinganyMatchandmethodreference ListanyMatch=people.stream().filter(p->(names.stream().anyMatch(p.name::contains))).collect(Collectors.toList()); //Usingreduce Listreduced=people.stream().filter(p->names.stream().reduce(false,(Booleanb,Stringkeyword)->b||p.name.contains(keyword),(l,r)->l|r)).collect(Collectors.toList());


Recommended