Java Experiment Three

Source: Internet
Author: User
Tags coding standards delete key gettext version control system

Lab Report

Study No.: 20135324

Name: Yang Shuwen

Instructor: Lou Jia Peng

Experiment Name: Java Agile Development and XP implementation (the picture shown in the code is for me to personally manipulate the experimental code)

Experimental content :

1. XP Basics

2. XP Core Practice

3. Related Tools

Experimental steps

(i) Agile Development and XP

Software engineering is the process of applying the systematic, orderly and quantifiable methods to the development, operation and maintenance of the softwares. Software engineering covers the following areas: Software requirements analysis, software design, software construction, software testing and software maintenance. People have many technologies, practices, habits and ideologies in the process of developing, operating, and maintaining software. Software engineering unifies these related technologies and processes into one system, called the "development process". The purpose of the software development process is to improve the efficiency of software development, operation and maintenance, and improve the quality of software, customer satisfaction, reliability and maintainability of software. It is not enough to have ideas of all kinds of processes, and we have a series of tools to ensure that these ideas can operate efficiently in practice. The important point of software development is not to see how many theories you can make, but also how you apply them to related tools, such as the combination of unit tests in Java and JUnit applications, and modeling to be combined with Umbrello or staruml applications. Programming learning is a 习而学 process. A common formula is: 软件工程=开发流程+工具 Xin Zou two formulas: 软件=程序+软件工程 and the 软件企业=软件+商业模式 development process you can refer to learning Xin Zou Teacher's software team and development process. The common development processes are:

    • RUP (Rational Unified Process)
    • PSP (Personal software Process)
    • TSP (Team software Process)
    • Agile Process
    • ......

Agile Development (development) is a human-centric, iterative, and progressive approach to development. "Agile Processes" are a collection of values and methodologies. Since 2001, some experts in the software industry have started advocating "agile" values and processes that affirm the value of popular practices, but emphasize that agile practices can bring value. Their manifesto for Agile development:

Agile development includes many modes:

Among them, extreme programming (EXtreme programming,XP) is a new and fast software development method. The XP team uses on-site customers, special planning methodologies, and ongoing testing to provide rapid feedback and comprehensive communication:

    • XP is a methodology developed to target software that meets customer needs
    • XP is a practice-based software engineering process and thought
    • XP believes that code quality is more important than people generally think.
    • XP is ideal for small, responsible, self-motivated teams to develop software that requires uncertainty or rapid change

XP软件开发是什么样的Use XP guidelines to express:

    • Communication: XP believes that communication between project members is key to the success of the project and regards communication as the main driver of coordination and cooperation in the project.
    • Simple: XP assumes that the future cannot be reliably predicted, and it is economically unwise to consider it now, so you should not think too much about the future but should focus on the urgent needs.
    • Feedback: XP considers the system itself and its code to be a reliable basis for reporting on the progress and status of the system development. The feedback of system development status can be used as a means to determine the progress of system development and determine the next development direction of the system.
    • Courage: It represents XP's view that people are one of the most important aspects of software development. In the development of a software product human participation throughout its entire life cycle, is the courage to eliminate the dilemma, let the team to the local optimal left behind, to achieve more significant goals. Demonstrates XP's basic trust in "people make projects successful".

A practical basis for successful use in XP environments is through XP的法则 presentation, including: Quick feedback, hypothesis simplicity, incremental changes, advocacy for change, and quality of work.

The cornerstone of XP software development is XP的活动 : coding, testing, listening, design.

The technology for project member users to successfully execute XP activities is XP实践 presented through 12 practices related to programming, teamwork, and process:

We are concerned with 编码标准 ,,, 结对编程 , and so on 代码集体所有 测试 重构 practice. The last experiment has already talked about TDD, and by learning these practices, you can form a test-centric development process:

Agile can be used as a way of doing things, and mastering good in the future work will also benefit from the infinite.

(ii) Coding standards

An important understanding of writing code is that "most of the time the program is for people to see", the programming standard makes the code easier to read and understand, and can even guarantee fewer errors. Programming standards include: Descriptive names, clear expressions, straightforward control flow, readable code and annotations, and the importance of consistently using certain rules and idioms when pursuing these content.

The layout in the coding standard is a good example, although the layout does not affect the function of the program, but it can affect the readability. The process of the layout of the pursuit of clear, beautiful, is a procedural style important factors. As a counter example, experience an example of the International C Language Chaos Code Contest (IOCCC, the International obfuscated C code Contest):

This is really a C language program that can be compiled to understand its readability. Of course, the writing of such code is also cattle people. We are familiar with this code:

The program does not have the most basic indentation, it is difficult to read, this problem is easier to solve in eclipse, we can click on the Eclipse menu Source->format or use the shortcut key ctrl+shift+f in accordance with Eclipse specification indentation,

The effect is as follows:

A very important part of the code standard is how to name packages, classes, variables, methods, and so on, so that you can name your code to go up a notch immediately. The general naming conventions in Java are:

    • To embody their own meanings.
    • Terms for packages, classes, variables
    • Method name with movable bin
    • Package name all lowercase, such as: IO,AWT
    • The first letter of the class name should be capitalized, such as: Helloworldapp
    • The first letter of a variable name is lowercase, such as: UserName
    • The first letter of the method name is lowercase: setName
    • ...

The name of the identifier should be intuitive and can be spelled, it is expected to understand the text, do not have to "decode", the general use of English words or their combination, easy to remember and read, avoid the use of Hanyu Pinyin to name, use the word to be accurate for example "current value" should be named currentValue , written nowValue is not accurate, but also dqz make it (Dang Qian Zhi first letter) is a joke.

The principle of “min-length && max-information” The length of the identifier, such as: maxVal better than maxValueUntilOverflow , can be by going to the vowel method to shorten the variable name, such as returnValue rtnVal , and, message msg general global variables with a descriptive name, Local variables with short names: single-character's name, common as i,j,k, etc. used as local variables.

Others can refer to the Code specification and code review written by Xin Zou teacher.

With respect to code standards, you can follow these guidelines:

Some companies, such as Google has published its own coding standards, can be used as a good reference for learning, we refer to the Code specification & code style written by Fan Fei, interested in how to try to practice the Google Java Style in Eclipse (Chinese version), That is, how to do "Click on the shortcut key Ctrl+Shift+F can let their code in line with the Google Java Style (Chinese version) requirements", after the completion of a separate blog, there are extra points .

(iii) Pair programming

Pairing programming is an important practice in XP. In pair programming mode, a pair of programmers work side-by-shoulder, equally, and in complementary way. They sit in front of a computer, facing the same monitor, working with the same keyboard and the same mouse. They analyze together, design together, write test cases together, encode together, do unit tests together, do integration testing together, write documents together, and so on. There are two roles in pairing programming:

    • The driver (Driver) is the person who controls the keyboard input.
    • The Navigator (Navigator) plays the role of pilotage and reminding.

How to pair programming, why to pair programming, we refer to pair programming and two people cooperation, the focus is:

    • Drivers: Write design documents, conduct coding and unit tests, and other XP development processes.
    • Navigator: Review the driver's documentation, the driver's implementation of the development process such as coding, consider the coverage of unit tests, think about the need for and how to refactor, and help drivers solve specific technical problems.
    • Drivers and pilots constantly rotate their roles and do not work for more than an hour, and take 15 minutes off each hour of work. The navigator has to control the time.
    • Active participation. Any task is the responsibility of the two people, and the responsibility of all. There is no "My Code", "Your Code" or "his/her code", only "our code".
    • There are only horizontal gaps, and there is no level difference. They are pairs, and although they may have different levels of seniority, both sides have equal decision-making rights in terms of analysis, design, or coding.

Teamwork is a spirit that is emphasized in many places, and the smallest team is a one-to-two team, and the team spirit starts with pairing programming. The most important thing for people to get along with in social life is honesty, empathy and mutual benefit . Pair programming in the people will be divided, how to cooperate more effectively to do things wrong people , master these can be a lifelong benefit, how to affect the small partners, we refer to two people cooperation: to make hamburgers.

(iv) version control

The collective ownership of XP means that everyone is responsible for all the code, which in turn means that everyone can change any part of the code. Pair programming contributes a lot to this practice: by working in different pairs, all programmers can see the full code. One of the main advantages of collective ownership is to increase the speed of the development process, because any programmer can fix it once there is an error in the code. This means that the code is placed in a place where everyone can easily get it, and we call it a code repository. This leads to another topic called versioning (version control).

Versioning provides a number of benefits for both teams and individuals.

    • Versioning provides item-level undo (undo) functionality: Nothing is a finalized version, and any error must be easily rolled back. Let's say you're using the world's most complex word processing system. It has all the features you can think of, that is, the DELETE key is not supported. Imagine how cautious and slow you are when typing, especially when a large document is approaching the end of the day, a careless will start again (imagine you select all the text, accidentally pressed the DELETE key, because there is no undo function, had to re-enter). Edit text and versioning are the same, and anytime you need to roll back, whether it's one hours, a day, or a week, it makes your team work free and fast, and is confident about correcting bugs.
    • Versioning allows multiple people to work on the same code, as long as they follow certain control principles. There is no longer a case where one person overwrites another person's edited code, causing the person's modification to be invalid.
    • The version control system preserves the history of changes made in the past. If you encounter some surprising code, the version control system can easily find out who did it, what was changed, how long it was modified, and if so, why.
    • The version control system also supports the release of multiple software versions while developing on the mainline. There is no need for the entire team to stop working when the software is released, and there is no need to freeze the code.
    • Version control is also a project-level time machine, you can choose any time to accurately view the project at the time of the situation. This is useful for research and is the basis for reproducing a previously problematic release version.

The popular version Control tool has Cvs,svn,git and so on, more can refer here. Git is another important addition to the Linux operating system, Linus.

Lab building on-line My Code base feature provides a built-in open git service for everyone in the lab environment. The course of study automatically creates a public code repository named shiyanlou_cs[Course ID], such as the code base named shiyanlou_cs212 for this course, which automatically executes git pull in the environment to launch the experiment, gets the latest code for the course repository, and stores it in/ Home/shiyanlou/code directory. The git push operation needs to be done manually, so be sure to push all changes before stopping the experiment , otherwise the code will be lost. Attention:

• Code base Links: http://git.shiyanlou.com/[your user name] the link to the course Code warehouse is: http://git.shiyanlou.com/[your exclusive username]/shiyanlou_cs[course id] Code path in Lab environment:/home/shiyanlou/code/shiyanlou_cs[Course ID]

For example, my private username is rocedu, then my code base link is: http://git.shiyanlou.com/rocedu, my Java Programming Course Code Warehouse link is: http://git.shiyanlou.com/ rocedu/shiyanlou_cs212, the code path in the experimental environment for this course is:/home/shiyanlou/code/shiyanlou_cs212.

Click Open now can open My Code library function, access to the page to complete information can, if already opened services, please note that the exclusive user name must be a combination of letters and numbers , it is recommended to include the number of information.

Here's how to use it:

    1. If you're unfamiliar with git, it's recommended to learn git lessons first
    2. When you start the experiment, if you already have the code warehouse for the course, it will automatically sync (gitpull) to the /home/shiyanlou/code directory in your lab environment and will automatically create and synchronize if you have not created it.
    3. Go to the experimental environment to modify the code, you need to execute the following command to submit:

$ cd/home/shiyanlou/code/shiyanlou_cs212

# Modify Code files

# Add modified File

$ git Add all modified files

# commit to the local code warehouse in the environment

$ git commit-m ' description of this modification '

# push to git.shiyanlou.com without entering a password

$ git push

Cloning other user code warehouses only need to know the other side of the warehouse link, we encourage people to modify the code based on:

$ git clone http://git.shiyanlou.com/[each other's exclusive username/[Course code warehouse name]

We give an example of a HelloWorld: first enter the code directory, you will find the shiyanlou_cs212 directory, enter shiyanlou_cs212, as shown:

Create the HelloWorld directory as shown in:

Create and edit the Helloworld.java file as shown in:

Note that the code submitted to the code base must compile, run, test no problem of code, we have no problem with the test code above, we can submit: we can first use Git status to view the code status, showing the non-tracking code, and suggest git add <file> ... Add, we use git add helloworld.* to add the information of the file to be submitted to the index library. When we use git commit, Git commits the file based on the contents of the index library. This is only local operation, close the experimental environment, will delete the code, if you want to save the code to a remote hosting server, you need to use Git push, before the experiment is completed, do not forget to use git push, Otherwise, it's equivalent to editing a half-day file in Word and not saving it at the end. We can modify the Helloworld.java as shown in:

Compile, run, test and commit without problems, git commit-a is used here:,

We can view the code submission record via git log:

It's very clear who wrote the code at what time. The end of the example, there is a problem is helloworld.class should not be saved in the code base, as long as we have Helloworld.java on the line, what to do? Solve it through a search engine.

Of course, Git is not only for programmers, but for all the "Undo" situations, versioning can help. Refer to Git for non-programmers (Chinese version).

Further learning, refer to git usage, tools, principles, advanced Links

(v) Reconstruction

Let's look at the concept of refactoring first:

Refactoring (refactor) is to change the structure within the software without changing the external behavior of the software, making it easier to read, easy to maintain, and easy to change.

One of the key prerequisites in refactoring is to "not change the external behavior of the software", which guarantees that we will not bring new bugs to the original system while reconstructing the original system, so as to ensure the security of the reconstruction. How to ensure that the software external behavior is not changed ? The reconstructed code should be able to pass the unit test . How can you make it easier to read, easier to maintain, and easy to change ? The design pattern gives the goal of refactoring.

Does refactoring matter? You can see from the Eclipse menu that there is a refactor menu, and refactoring is almost standard for modern Ides:

We say that "naming the identifiers" in the coding standard is an important skill of the programmer, and there is no such consciousness before, what should I do now? No problem, the first function in refactoring is rename, which can change names to classes, packages, methods, and variables. For example, there is an ABC class:

This class, the class name, the method name, and the parameter name of the method are problematic, and the code cannot be understood without comments. We can use the refactoring feature in Eclipse to rename it. To modify the method, click the name you want to change with your mouse, select the Refactor->rename in the Eclipse menu ... :

The effect of refactoring is as follows:

function unchanged, code level immediately on a grade, experience the name of the power it?

Students who have studied the C language often make mistakes in Java that are not encapsulated, and where the use of the class is structured. For example, to define a class student, a code like this would appear:

Refactor->encapsulate Field ... in the Eclipse menu, such as:

The 34th, 35 line is still problematic, every time the student information printed code violates the dry principle, resulting in code duplication, normal refactoring can use the eclipse in the extract Method ..., such as:

Since all classes in Java have a dedicated tostring method, we use Eclipse in Source->generate tostring () ... To give the student Class A ToString method, modify the main code, the result is as follows:

Let's think about it, what are the benefits of such a refactoring? What's wrong with refactoring?

We want to modify the software, original aim, is nothing more than four kinds of motives:

    • Add new features;
    • The original function has a bug;
    • Improving the structure of the original procedures;
    • Optimize the performance of legacy systems.

The first and second motivations originate from the functional needs of the customer, and the fourth is the non-functional requirements of the customer. The external quality of the software is measured by the customer's satisfaction with the functional and non-functional requirements of the software. It relates to an enterprise, a software reputation and vitality, so for all software enterprises attach great importance to. To improve the internal quality of software is undoubtedly the third motive of software modification: to improve the structure of the original program. Its value is hidden, not reflected in one or two times development, but gradually reflected in the future long-term maintenance of the software process. High-quality software to ensure that developers (even novice) can easily read the software code, to ensure that every future software maintenance can be easily completed (no matter how many times the software has changed, maintained for many years), Ensures that every change in future needs can be done easily (not hurt –). It is not easy to achieve these points, it requires us to continuously optimize and improve the internal quality of the system. This is the value of system refactoring. The following important question is which areas need to be refactored? There is the code for the foul-smelling lane (badsmell) . What's a smelly smell? Imagine you open the refrigerator door, come out a stink way you know there is something rotten in the refrigerator, to clear. The code smells the same way:

The first thing in the stink is duplicated code. If you see the same program structure in more than one place, then you can be sure that if you try to combine them, the program will become better.

    • The simplest Duplicated Code is that [the two methods within the same class contain the same expression]. All you need to do is use the Extract Method extracted code, and then let the two locations invoke the extracted piece of code.
    • Another common scenario is that [two siblings (sibling) subclasses contain the same expression]. To avoid this, use only two classes Extract Method , and then use the extracted code to Pull Up Method push it into the superclass.
    • If the code is just similar, not exactly the same, then you have to Extract Method split the similarity and Difference sections to form a single method. Then you may find that you might be able to apply Form Template Method a Template Method design pattern.
    • If there are methods that do the same thing with different algorithms, you can choose one that is clearer and Substitute Algorithm replace the algorithm with other methods.
    • If two unrelated classes are present Duplicaded Code , you should consider using one Extract Class , refining the duplicate code into a separate class, and then using the new class within another class. However, the method of repeating the code may indeed belong to only one class, the other class can only invoke it, or the method may belong to the third class, and the other two classes should refer to the third class. You have to decide where this method fits best and make sure that it is placed and will not appear anywhere else.

Other Bad Smell and corresponding refactoring techniques are shown in the following table:

Refactorrefactoring hand in the menu in eclipse:

A more complete approach can be found in the blog of Martin Fowler, the author of refactoring. The use of basic techniques in eclipse can be referred to by anyone who can refactor to learn and practice.

A complete refactoring process consists of:

    1. Check out code from the version control system library
    2. Read code (including test code)
    3. Find Bad smell
    4. Refactoring
    5. Run all the unit Tests
    6. Check in code to codebase

Let's combine git to give a more complete example.

(vi) Practical items 1. Group cooperation: 20135303 Wei Hao: Find materials, write, modify code blog address: http://www.cnblogs.com/20135303whq/20135324 Yang Shuwen is responsible for: Consider requirements, test code, modify the code

2. Selected game: Man-machine scissors. The user through the button below the screen to make "stone, scissors, cloth" choice, the computer randomly make a choice, prompting the user to win or lose or draw.

The code is as follows:

Import Java.awt.Color;
Import Java.awt.EventQueue;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Java.util.Random;
Import Javax.swing.JButton;
Import Javax.swing.JFrame;
Import Javax.swing.JLabel;
Import Javax.swing.JPanel;
Import javax.swing.SwingConstants;
Import Javax.swing.border.EmptyBorder;
Import Javax.swing.border.LineBorder;
@SuppressWarnings ("Serial")
public class Game extends JFrame {
Private JPanel ContentPane;
Private JPanel Userpanel;
Private JPanel Computerpanel;
Private JLabel Uservalue;
Private JLabel Computervalue;
Private JLabel resultlable;
/**
* Launch the application.
*/
public static void Main (string[] args) {
Eventqueue.invokelater (New Runnable () {
public void Run () {
try {
Game frame = new game ();
Frame.setvisible (TRUE);
} catch (Exception e) {
E.printstacktrace ();
}
}
});
}
/**
* Create the frame.
*/
Public Game () {
Setdefaultcloseoperation (Jframe.exit_on_close);
SetBounds (100, 100, 450, 300);
ContentPane = new JPanel ();
Contentpane.setborder (New Emptyborder (5, 5, 5, 5));
Setcontentpane (ContentPane);
Contentpane.setlayout (NULL);

JButton shitoubtn = new JButton ("stone");
Shitoubtn.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent e) {
Uservalue.settext ("stone");
Computervalue.settext (Getcomputervalue ());
Comparevalues ();
}
});
Shitoubtn.setbounds (144, 216, 146, 46);
Contentpane.add (SHITOUBTN);

JButton bubtn = new JButton ("cloth");
Bubtn.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent e) {
Uservalue.settext ("cloth");
Computervalue.settext (Getcomputervalue ());
Comparevalues ();
}
});
Bubtn.setbounds (288, 216, 146, 46);
Contentpane.add (BUBTN);

JButton jiandanbtn = new JButton ("scissors");
Jiandanbtn.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent e) {
Uservalue.settext ("scissors");
Computervalue.settext (Getcomputervalue ());
Comparevalues ();
}
});
Jiandanbtn.setbounds (0, 216, 146, 46);
Contentpane.add (JIANDANBTN);

Computerpanel = new JPanel ();
Computerpanel.setbackground (Color.White);
Computerpanel.setforeground (Color.Black);
Computerpanel.setborder (New Lineborder (new Color (0, 0, 0)));
Computerpanel.setbounds (318, 60, 95, 87);
Contentpane.add (Computerpanel);

Computervalue = new JLabel ("");
Computerpanel.add (Computervalue);

Userpanel = new JPanel ();
Userpanel.setbackground (Color.White);
Userpanel.setborder (New Lineborder (new Color (0, 0, 0)));
Userpanel.setbounds (64, 60, 95, 87);
Contentpane.add (Userpanel);

Uservalue = new JLabel ("");
Userpanel.add (Uservalue);

JLabel Lblnewlabel = new JLabel ("Welcome to the Human Machine Scissors Program");
Lblnewlabel.sethorizontalalignment (Swingconstants.center);
Lblnewlabel.setbounds (10, 10, 414, 15);
Contentpane.add (Lblnewlabel);

JLabel label = new JLabel ("result");
Label.sethorizontalalignment (Swingconstants.center);
Label.setbounds (0, 154, 424, 15);
Contentpane.add (label);

resultlable = new JLabel ("");
Resultlable.sethorizontalalignment (Swingconstants.center);
Resultlable.setbounds (0, 179, 424, 15);
Contentpane.add (resultlable);

JLabel label_2 = new JLabel ("You Punch:");
Label_2.setbounds (0, 67, 54, 46);
Contentpane.add (label_2);

JLabel label_3 = new JLabel ("Computer punch:");
Label_3.setbounds (242, 64, 77, 53);
Contentpane.add (Label_3);
}

Computer Punch, generate a random number (0,1,2) representative: Stone, scissors, cloth
Computer Punch, generate a random number (0,1,2) representative: Stone, scissors, cloth
Public String Getcomputervalue () {
String[] Quans = {"Stone", "scissors", "cloth"};
Random random = new random ();
int value = random.nextint (100);
value = value%3;
return Quans[value];
}
private void Comparevalues () {
String Usertext = Uservalue.gettext ();
String Computertext = Computervalue.gettext ();
String result = "PK";

if (Usertext.equals (Computertext)) {
result = "Qifengduishou!" Come Again ";
} else {
if ("Stone". Equals (Usertext)) {
if ("Scissors". Equals (Computertext)) {
result = "You won!!" Very good!! ";
}else if ("cloth". Equals (Computertext)) {
result = "You lost!!" Come on, man! ";
}
}
if ("Scissors". Equals (Usertext)) {
if ("cloth". Equals (Computertext)) {
result = "You won!!" Very good!! ";
}else if ("Stone". Equals (Computertext)) {
result = "You lost!!" Come on, man! ";
}
}
if ("cloth". Equals (Usertext)) {
if ("Stone". Equals (Computertext)) {
result = "You won!!" Very good!! ";
}else if ("Scissors". Equals (Computertext)) {
result = "You lost!!" Come on, man! ";
}
}
}
Resultlable.settext (result);
}
}

The initial operating interface is as follows:

Lose:

Win:

Draw:

2. Report the time of your PSP (Personal software Process)

time-consuming

TD valign= "Top" >

steps

percentage

demand analysis

20min  14%

design

 20min  14%

Code implementation /p>

 60min  43%

test

 30min  21%

Analysis summary

 10min  8%

(vii) Experimental summary

This experiment for me a relatively difficult experiment, especially the last self-made mini-game, check a lot of data to be difficult to complete. In the experiment, the content of the version control is not detailed, and the HelloWorld can not be stored in. In the experimental building after you create an empty document, put the code in, you can continue to do experiments

Java Experiment Three

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.