Course: Java Lab class: 201352 Name: Ellis No.: 20135210
Score: Instructor: Lou Jia Peng Experimental Date: 15.05.05
Experiment level: Preview degree: Experiment time:
Instrument Group: Compulsory/Elective: Elective experiment number: 2
Experiment Name: Java Object-oriented programming
Experimental purposes and requirements:
1. Initial mastery of unit testing and TDD
2. Understanding and mastering the object-oriented three elements: encapsulation, inheritance, polymorphism
3. Initial mastery of UML modeling
4. Familiarity with S.O.L.I.D principles
5. Understanding Design Patterns
Experimental requirements
1. Students who do not have a Linux base are advised to start with the Linux basics (new version) Vim Editor course
2. Complete the experiment, write the experiment Report, the experiment report is published in the blog Garden, note that the experiment report focuses on the running results , problems encountered (tool find, installation, use, program editing, debugging, running, etc.), solutions (empty methods such as "Check the network", "Ask classmates", "reading" and so on all get 0 points) and analysis (from which can get what revelation, what harvest, lessons, etc.). The report can refer to the guidance of Fan Fei Dragon Teacher
3. Plagiarism is strictly forbidden, and the results of the experiment of the perpetrator are zero, and other punitive measures are added.
Experimental instrument:
Experiment contents, steps and experiences (attached paper):
(a) Unit testing
(1) Three kinds of code
Programming is intellectual activity, not typing, what to do before programming, how to do to think clearly to write the program, write well. With a lot of students at present, a program to open the editor to write code, I hope that students develop a habit, when you want to solve problems with the procedure, you will write three kinds of code:
- Pseudo code
- Product Code
- Test code
We use an example to illustrate how to write these three kinds of code.
Requirements: We want to MyUtil
solve a percentile grade in a class to turn into "excellent, good, medium, pass, fail" five grade system performance function.
we have designed a 测试用例(Test Case)
, 测试用例
is a set of test inputs, execution conditions, and expected results for a particular goal to test a program path or verify that a specific requirement is met. Here our test input is "50", the expected result is "fail". Running the results in Eclipse is as follows, and the test results match the expected:
Only a set of input tests is not sufficient, we test the general situation,
Running the results in Eclipse is as follows, and the test results match the expected:
We can not just test the normal situation, the following to see how the abnormal situation, such as the input is negative or greater than 100 of the score,
Run the program found that negative ticks and expectations are inconsistent, and finally found a bug, the reason is that when the failure of the judgment did not require a score greater than 0. We revise MyUtil.java
and increase our judgment on negative points.再次运行测试,测试结果符合预期,如所示:
Have you had enough testing? Not enough, the general code is the most error-prone at the boundary, we have not tested the boundary condition, we have tested the boundary conditions that are entered as "0,60,70,80,90,100",
The test results are as follows:
We found a bug when entering 100 in the boundary condition. We modify the MyUtil.java
condition of judging excellent to include the case of input 100,
At this time the test is in line with expectations, we give MyUtil.java
others to use, the heart is more confident. How do you ensure that the unit measure is adequate? Our general requirements are 测试代码
more than that 产品代码
. How to write the test, "the way of unit testing" put forward Right-BICEP
the method, we can refer to.
Software is done by the cooperation of many people, and the work of different people is dependent on each other. Many of the errors in the software come from the programmer's misunderstanding of the function of the module, negligence or the failure to understand the module changes. How can I be responsible for the module function definition as clear as possible, the internal changes of the module will not affect the other modules, and the quality of the module can be stable, quantitative guarantee? Unit testing is a very effective solution.
(2) TDD (test driven devlopment, testing-driven development)
The 测试代码
development method, written first, and then written, 产品代码
is called "Test-driven Development" (TDD).
The general steps for TDD are as follows:
- Clear the current functionality to be completed and record it as a test list
- Quick completion of writing test cases for this feature
- Test code compilation does not pass (no product code)
- Write the Product Code
- Test Pass
- Refactor the code and ensure the test passes (refactoring the next lab session)
- Cycle through the development of all functions
Based on TDD, we don't have an over-design situation where the requirements are expressed through test cases, and we just 产品代码
let the test pass.
There is a unit test tool JUnit in Java to aid in TDD, and we use TDD to rewrite the example of the previous percentile to five-point system, and realize the benefits of developing with the test tool support.
Open Eclipse
, click File->New->Java Project
Create a new TDDDemo
Java project,
In the TDDDemo
project, we put the mouse on the project name TDDDemo
, right-click, in the pop-up menu selected to New->Source Folder
create a new test directory test
, such as:
We put the mouse test
on the directory, right-click, in the pop-up menu selected to New->JUnit Test Case
create a new test case class MyUtilTest
, such as:
We add the first test case testNormal
, note that before the test case must have annotations @Test
, test case Method name arbitrary, enter the following code:
import org.junit.Test;import junit.framework.TestCase;public class MyUtilTest extends TestCase {@Testpublic void testNormal() {assertEquals("不及格", MyUtil.percentage2fivegrade(55));assertEquals("及格", MyUtil.percentage2fivegrade(65));assertEquals("中等", MyUtil.percentage2fivegrade(75));assertEquals("良好", MyUtil.percentage2fivegrade(85));assertEquals("优秀", MyUtil.percentage2fivegrade(95));}}
The input is complete Eclipse
as shown in the following:
The Red fork in the diagram shows a syntax error for a simple reason, the MyUtil
class does not exist, the Percentage2fivegrade method in the class does not exist, TDDDemo
we src
create a new class in the directory, MyUtil
and implement the Percentage2fivegrade method, as shown in:
You can see now that the test code is not grammatical error, we put the mouse MyUtilTest.java
on the right, click, select Run as->JUnit Test
, such as:
The test results showed a red bar, indicating that the test failed, the red bar summarized the test situation, ran a test, no errors, a test failed. The following reasons are also very clear: the test code tenth incoming 55 o'clock, the expected result is "failed", the code returned "error", modify MyUtil.Java
it, enter the following code:
Run the test again, as shown in:
The test results showed a green bar, indicating that the test passed.
TDD's goal is "clean Code that Works", TDD's slogan is "Keep the bar Green, to Keep the Code clean", we have a feel.
The coding rhythm of TDD is:
- Add test code, JUnit appears red bar
- Modify the Product Code
- JUnit appears green bar, Task complete
We add a use case to test for abnormal conditionstestException,
We add a use case to test the boundary condition testBoundary
,
How to get JUnit gree bar
out and try it out, such as:
Regardless of TDD, writing high-quality test cases is the most important, how to do unit testing, you can refer to the "Unit test of the road" this book. In addition, "Agile Java Chinese version" shows how to integrate Java and TDD effectively, through TDD Drive project development, interested can be consulted.
(2) encapsulation, inheritance and polymorphism
The three elements of object-oriented (object-oriented) include: encapsulation, inheritance, polymorphism. Object-oriented thinking involves all aspects of software development, such as object-oriented analysis (OOA), Object-oriented design (OOD), and object-oriented programming (OOP). OOA decomposes The system according to the abstract key problem domain and focuses on what. Ood is an object-oriented implementation of the symbolic design system, which constructs the system into a "real-world" object in a way that is very close to the problem domain terminology, and focuses on howto implement the functional specification through the model. OOP is coded in a programming language (such as Java) on a design basis. The main line that runs through OOA, Ood, and OOP is abstraction.
Ood Modeling uses the graphical Modeling language UML (Unified Modeling Language), UML is a generic modeling language, we experiment with Umbrello for modeling, and Windows recommends that you use STARUML.
The result of a process abstraction is a function, and the result of the data abstraction is an abstract data Type,adt, which can be used as an ADT with inherited and polymorphic mechanisms. Data Abstraction is the core and origin of OOP.
Encapsulation actually uses methods to hide the data of the class, controlling the user's modification of the class and the degree of access to the data, resulting in the benefits of modularity (modularity) and information hiding (information hiding) ; interface (interface) is an accurate description of the package.
- + indicates public
- #表示 protected
- -Indicates private
Inheritance refers to the definition of a class that can be based on another already existing class, that is, the subclass is based on the parent class, thus implementing the reuse of the parent code. The existing classes are called base classes, superclass, parent classes (base class, Super class, parent Class), and the new classes are called derived classes, inheriting classes, subclasses (derived class, inherited class, child class). An inheritance relationship expresses the relationship of "is a kind of", called the "ISA" relationship. The key to inheritance is to confirm that a subclass is a special type of parent class
。 Inheritance is the foundation of software reusability, and it is the main way to improve the expansibility and maintainability of software system.
As shown above, based on encapsulation, inheritance can implement code reuse , it should be noted that inheritance more important role is to implement polymorphism .
Object-oriented objects allow different classes of objects to respond to the same message, which means that the same message can be used in a variety of different ways depending on the sending object, and we call this behavior polymorphic. In Java, polymorphism refers to a phenomenon in which different class objects execute different code when they invoke the same signed member method. Polymorphism is the basis of the flexibility and extensibility of object-oriented programming .
(iii) design pattern preliminary (1) S.O.L.I.D principle
Object-oriented three elements are "encapsulation, inheritance, polymorphism", and any object-oriented programming language will support these three elements syntactically. It is very difficult to use the three elements, especially polymorphism, with the help of abstract thinking, and the S.O.L.I.D
principle of class design is a good guide:
- SRP (Single Responsibility Principle, sole responsibility principle)
- OCP (open-closed Principle, open-closed principle)
- LSP (Liskov substitusion Principle,liskov substitution principle)
- ISP (Interface segregation Principle, interface separation principle)
- DIP (Dependency inversion Principle, dependency inversion principle)
OCP
is one of the most important principles in Ood, OCP
the content is:
- Software entities (class, modules, function, etc) should open for extension,but closed for modification.
- Software entities (classes, modules, functions, etc.) should be open to expansion and closed to modifications.
The behavior of the extended open for Extension software module must be extensible, when the application needs change or needs to meet the new application needs, we have to let the module work in different ways, the modification is closed (Closed for modification Requires that the source code of the module is not modifiable, and no one is allowed to modify the existing module. Based on the OCP
use of object-oriented polymorphism (polymorphic), more flexibility in handling change embrace changes OCP
can be achieved by: (1) abstraction and inheritance, (2) interface-oriented programming.
-
(2) mode and design mode
reusable expert solutions to a problem . There are many patterns in computer science:
- grasp mode
- parsing mode
- software architecture mode
- design mode: Created, structured, behavioral
- Admin mode : The Manager Pool implementation mode
- interface design interactive mode
- ...
design pattern , where the position of the design pattern in object-oriented programming can be comparable to the status of data structure in a process-oriented program.
-
(3) design pattern Real example
design pattern provides a subsystem or component for refining a software system, or a diagram between them that describes the public rendition structure of a communication component, Communication components can solve a design problem in a particular context.
We see that the code conforms to the OCP principle by adding a layer of abstraction. Code has a good extensibility, maintainability, the price is more code, inefficient.
Design patterns beginners are prone to overuse them, leading to over-design, that is to say, complying with dry and OCP is certainly good, but will appear yagni (you aren ' t gonna need it and you won't need it) issues.
The dry principle and the Yagni principle are not fully compatible. The former pursues "abstraction" and asks for a common solution, while the latter pursues "fast and provincial", which means not focusing on abstraction, because it is likely that you will not need it. How to balance it? There is a rule of three (three principles): When you use a function for the first time, you write a specific solution, and the second time you use it, you copy the last code (in violation of dry), and the third time, you begin to "abstract" and write a general-purpose solution.
The design mode of learning first refer to the "Easy to design mode", the book is very readable.
There are many other object-oriented principles beyond the solid principle. Such as:
- "Combinatorial substitution Inheritance": this is to say that relative to inheritance, more inclined to use the combination;
- "The Law of the Piper": This means "the less you know about other classes, the better";
- "Common closure principle": This means that "related classes should be packaged together";
- "Stable abstract principle": This means that "the more stable the class, the more it should be composed of abstract classes";
Of course, these principles are not isolated, but closely linked, followed by one principle and followed by one or more principles, contrary to one of the principles is also likely to violate the other one or more principles. Design patterns are the result of the application of these principles in some specific scenarios. Therefore, the design pattern can be regarded as "framework" and the Ood principle as "norm". In the process of learning the design pattern, we should constantly reflect on it, which embodies the principle of object-oriented design.
(iv) Exercise 1 using TDD to design a complex that implements a complex number class.
Pseudo code:
No input---The real part of the complex number is 0 and the imaginary part is 0
Enter only the real part---the real part of the complex is the actual part entered, the imaginary part is 0
Enter only the imaginary part---the real part of the complex number is 0, the imaginary part is the imaginary part entered
The imaginary part of the real part---the real part of the complex number and the imaginary part correspond to the actual imaginary part of the corresponding input.
Addition---the real part and the real part of the complex, the imaginary part and the imaginary part, namely the output P1.repart+p2.repart,p1.impart+p2.impart
Subtraction---The real part of the complex number is subtracted from the real part, and the imaginary part is subtracted from the imaginary part, that is, the output P1.repart-p2.repart,p1.impart-p2.impart
Product Code:
Package Exercise;
public class Complex
{
Double Repart,impart;
Complex ()
{
this.repart=0;
this.impart=0;
}
Complex (double repart)
{
This.repart=repart;
this.impart=0;
}
Complex (double repart,double impart)
{
This.repart=repart;
This.impart=impart;
}
Complex Jia (Complex p1,complex p2)
{
Complex P =new Complex (P1.repart+p2.repart,p1.impart+p2.impart);
return p;
}
Complex Jian (Complex p1,complex p2)
{
Complex P =new Complex (P1.repart-p2.repart,p1.impart-p2.impart);
return p;
}
void Print ()
{
System.out.println ("The value of the plural is:");
if (this.impart!=0)
System.out.println (this.repart+ "+" +this.impart+ "I");
else System.out.println (This.repart);
}
}
Test code:
Package Exercise;
public class Test
{
public static void Main (string[] args)
{
Complex c=new Complex ();
Complex c1=new Complex (2,7);
Complex c2=new Complex (5,2);
C1. Print ();
C2. Print ();
System.out.println ("These two plural and for:");
System.out.println ((C.jia (c1, C2). repart+ "+" +c.jia (c1, C2). impart+ "I"). ToString ());
System.out.println ("These two complex differences are:");
System.out.println (C.jian (c1, C2). repart+ "+" +c.jian (c1, C2). impart+ "I");
}
}
2. In the lab report, when you count your PSP (Personal software Process)
Steps |
Take |
Percentage |
Demand analysis |
5 |
6.25% |
Design |
10 |
12.5% |
Code implementation |
50 |
62.5% |
Test |
10 |
12.5% |
Analysis Summary |
5 |
6.25%
|
3. Implement to have pseudo-code, product code, test code. 4. Summarize the benefits of unit testing
1. Accelerate the project process, and the design of the process is more complete.
2. Use the simple transaction rollback feature to perform real-world testing on a production environment without worrying about generating unnecessary data.
3. Define the function of the module that you are responsible for, and the internal changes between modules and modules will not have any effect.
Experiment two-Java object-oriented programming