DMS note book

  1. 1. A note book for my DMS learning.
  2. 2. lecture 1 - Basic OO Concept
    1. 2.1. 1.obeject-oriented programming is founded on these ideas:
    2. 2.2. 2.Public and Private
    3. 2.3. 3.Accessors and Modifiers
    4. 2.4. 4.Encapsulation
    5. 2.5. 5.The keyword “this”
    6. 2.6. 6.Constructors
  3. 3. lecture 2 - More Advanced Java Topics
    1. 3.1. 1.Passing by Value & Passing by Reference
    2. 3.2. 2.Static Fields & Static Methods
      1. 3.2.1. 2.1 Static Fields:
      2. 3.2.2. 2.2 Static Methods
    3. 3.3. 3.Java Collections Framework
    4. 3.4. 4. Aggregation and Composition
      1. 3.4.1. 4.1 Aggregation in java
      2. 3.4.2. 4.2 Composition in java
    5. 3.5. 5.Inheritance & Polymorphism
    6. 3.6. 6.Abstract Methods & Classes, Interface
    7. 3.7. 7.Java Release
    8. 3.8. 8.refactoring code
    9. 3.9. 9.Basic Maintenance
  4. 4. lecture 3 - Introduction to GUI programming in Java
    1. 4.1. 1.Graphical User Interfaces(GUI)
    2. 4.2. 2.Basics of GUI programming-Swing&Javafx
    3. 4.3. 3.getting started with Javafx
      1. 4.3.1. 3.1 Adding simple 2D Graphics
    4. 4.4. 4.MVC pattern and FXML
    5. 4.5. 5.FXML
    6. 4.6. 6.Multiple Windows in Javafx
  5. 5. lecture 4 - OO analysis and UML
    1. 5.1. 1.UML overview
    2. 5.2. 2.Use Case Diagrams
    3. 5.3. 3.Use Case Specification
    4. 5.4. 4.Activity Diagrams
    5. 5.5. 5.Sequence Diagrams:
    6. 5.6. 6.Stat machine Diagrams:
    7. 5.7. 7.Class Diagrams
    8. 5.8. 8.built tools
      1. 5.8.1. built tool 1 - Maven
      2. 5.8.2. built tool 2 - Gradle
  6. 6. lecture 5 - GUI-javafx adcances
    1. 6.1. 1.ImageView
    2. 6.2. 2.CheckBox
    3. 6.3. 3.ComboBox
    4. 6.4. 4.MeunBar
    5. 6.5. 5.Alert
    6. 6.6. 6.About styling
    7. 6.7. 7.JavaFX Application Thread
    8. 6.8. 8.Animation in JavaFX
      1. 6.8.1. Types of animations in Javafx:
      2. 6.8.2. Key concepts for Timeline Animation
  7. 7. lecture 6 - Coding and Repository Tools for DMS
    1. 7.1. 1.Use of git
    2. 7.2. 2.Coding Convention
      1. 7.2.1. Bob’s Rule 1 - Method Length (75 lines or less)
      2. 7.2.2. Rule 2 - Indentation缩进(less than 5 levels)
      3. 7.2.3. Rule 3 - Line Length below 80 characters
      4. 7.2.4. Rule 4 - Class Variable Names
      5. 7.2.5. Rule 5 - Accessor Methods
      6. 7.2.6. Rule 6 - Class Variables
      7. 7.2.7. Rule 7 - Method Naming
      8. 7.2.8. Rule 8 - Method Parameters (less than 5)
      9. 7.2.9. Rule 9 - Symbolic Constants
    3. 7.3. 3.Javadoc Documentation
  8. 8. lecture 7 - OO Software Design principles & Patterns
    1. 8.1. SOLID Principles
      1. 8.1.1. 1.S-Single Responsibility Principle,单一职责原则
      2. 8.1.2. 2.O-Open-Closed Principle,开闭原则
      3. 8.1.3. 3.L-Liskov’s Substitution Principle,里氏替换原则
      4. 8.1.4. 4.I-Interface Segregation Principle,接口隔离原则
      5. 8.1.5. 5.D-Dependency Inversion Principle,依赖反转原则
    2. 8.2. Design Patterns & Examples
      1. 8.2.1. 1.The Singleton Pattern(Creational)
      2. 8.2.2. 2.The Factory Pattern(Creational)
      3. 8.2.3. 3.Adapter Pattern(Structural)
      4. 8.2.4. 4.Observer Pattern(Behavioural)
  9. 9. lecture 8 - Refactoring
    1. 9.1. 1.Identify Code Smell(代码异味)
    2. 9.2. 2.Refactoring code
      1. 9.2.1. 2.1.Encapsulate Fields to retain private variables
      2. 9.2.2. 2.2.Extract(提取) method from a large block of code
      3. 9.2.3. 2.3 Replace Parameter with Explicit Method
      4. 9.2.4. 2.4 Inline Method to reduce indirection
      5. 9.2.5. 2.5 Repalce Temp with Query
      6. 9.2.6. 2.6 Rename Variable or Method To Self Document
      7. 9.2.7. 2.7 Remove assignments to parameters
    3. 9.3. 3.Refactoring code at a higher level
      1. 9.3.1. 3.1 Replace type code with polymorphism
      2. 9.3.2. 3.2 Single Reponsibility with Extract Class
      3. 9.3.3. 3.3 Generalization with Extract Interface
      4. 9.3.4. 3.4 Push Down/Pull Up of methods
    4. 9.4. 4.Applying a design pattern in Refactoring
  10. 10. lecture 9 - Open Source
    1. 10.1. 1.Liabrary
    2. 10.2. 2.open source software development and maintenance
    3. 10.3. 3.Licences

A note book for my DMS learning.

DMS stands for Developing maintainable software. I am now writing this note book for better understanding since there exist a mass of concepts. At the same time I hope this note help my future employment.
艹


lecture 1 - Basic OO Concept

1.obeject-oriented programming is founded on these ideas:

  • Abstraction: Simple things like objects represent more complex underlying code and data
  • Encapsulation: The ability to protect some components of the object from external access
  • Inheritance: The ability for a class(“subclass”) to extend or override functionality of another class(“superclass”)
  • Polymorphism: The provision(提供) of a single interface to entities of different types. It has two types.
    1. Method overriding: Run time polymorphism. Methods with same class name, input and parameters appear in both super class and subclass.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      //for overriding
      public class Parent {
      public void display() {
      // ...
      }
      }

      public class Child extends Parent {
      @Override
      public void display() {
      // ...
      }
      }
    2. Method overloading: Compile time polymorphism. Methods in same class have same name but different in parameters.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      //for overloading
      public class Example {
      public void display(String s) {
      // ...
      }

      public void display(String s, int num) {
      // ...
      }
      }

2.Public and Private

Access rules, 还有protected等.

  • declear as public: constructors, methods and static constants
  • declear as private: helper method(needed only inside the class), fields

3.Accessors and Modifiers

  • Accessors(getters): xxx.get(), method that return values of private fields.
  • Modifiers(setters/mutators): xxx.set(), method that set values of private fields.

4.Encapsulation

Encapsulation即“stop other changing it”

  • Hiding the impilmentation details of a class is called encapsulation
  • Encapsulation helps with program maintenance: a change in class does not affect other classes
  • A client of a class interacts with the class only through well-documented public constructors and methods; this facilitates team development

5.The keyword “this”

this“ refers to the implicit parameter inside your class. It can refer to a field this.field or call a method this.method(parameters). Can also be used in constructor(this化身变成Constructors,见下文).

6.Constructors

The constructor method is a special method of a class for creating object instances of that class.

  • 可以有多个,但不能同参: If a class has more than one constructor, they must have different numbers and/or types of parameters (constructor overloading)
  • Constructors are invoked using the operator new.
  • Constructors of a class can call each other using the keyword “this” (referred to as constructor chaining) - a good way to avoid duplicating code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    public class ExampleClass {
    private int x;
    private int y;
    private String name;

    // 主构造函数
    public ExampleClass(int x, int y, String name) {
    this.x = x;
    this.y = y;
    this.name = name;
    }

    // 辅助构造函数
    public ExampleClass(int x, int y) {
    this(x, y, "DefaultName"); // 调用主构造函数
    }

    // 另一个辅助构造函数
    public ExampleClass() {
    this(0, 0); // 调用上面的辅助构造函数
    }

    // 普通方法
    public void someMethod() {
    // 方法逻辑
    }
    }

lecture 2 - More Advanced Java Topics

1.Passing by Value & Passing by Reference

在java中,data is always passed by value(including object reference, in other word the pointer)!!!

  • Passing by value constitutes copying of data, where changes to the copied value are not reflected in the original value
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public class Test {
    public static void main(String[] args) {
    int x = 10;
    System.out.println("Before modify(): " + x);//10
    modify(x);// pass by value
    System.out.println("After modify(): " + x);//still be 10
    }

    public static void modify(int number) {
    number = 20;
    }
    }
  • Passing by reference constitutes(构成) the aliasing(别名) of data, where changes to the aliased value are reflected in the original value(in java, object references(pointer) are passed by value)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public class Test {
    static class MyObject {
    int value;
    }

    public static void main(String[] args) {
    MyObject obj = new MyObject();
    obj.value = 10;
    System.out.println("Before modify(): " + obj.value);//10
    modify(obj);//pass by reference
    System.out.println("After modify(): " + obj.value);//20
    }

    public static void modify(MyObject obj) {
    obj.value = 20;
    }
    }

2.Static Fields & Static Methods

2.1 Static Fields:

  • A static field (class field or class variable) is shared by all objects of the class
  • A non-static field (instance field or instance variable) belongs to an individual object
  • Modifying a Static Field Affects All Instances
  • Usually static fields are NOT initialised in constructors; they are initialised either in declarations or in public static methods or just use their default value

2.2 Static Methods

  • Static methods can access and manipulate(操纵) class’s static fields. They belong to the class - not an instance of it
  • Note that static methods cannot access instance fields or call instance methods of the class while instance methods can access all fields and call all methods of their class - both static and non-static(I have suffered a lot from the snake game cw)(静态不可引用全部,实例可以)

3.Java Collections Framework

Java collection Framework(JCF) is a set of classes and interface in java, provided for storing and processing collections of data. It is a part of the java.util package.可理解为java语言中的数据结构包

API&library

API stands for:

  • Application Programming Interface.

Difference between a library and an API:

  • An API is an interface or communication protocol between a client and a server, intended to simplify the building of client-side software. A library contains re-usable chunks(大块) of code.

A collection is an object that repersents a group of objects.
Core collection framework interface:

  • Iterable: Represents an iterator object
  • Collection: Represents a dynamic group of objects (elements)
  • Map: Maps keys to values; no duplicate keys(eg.HasMap)
  • Queue: Represents FIFO queues or LIFO stacks
  • Deque: Represents a double ended queue
  • Set: A collection that cannot contain duplicate elements(eg.HashSet, TreeSet)
  • List: An ordered sequence of elements that allows duplicate elements(eg.ArrayList, LinkedList)

following is about implementation of object oriented concepts in java

4. Aggregation and Composition

they both have “has-a” relationship

What is the difference between the Aggregations and Compositions?
  • answer comes from GPT:
    • 生命周期的依赖性:
      • 聚合(Aggregation):在聚合关系中,子对象可以独立于父对象存在。父对象的创建和销毁不会影响子对象的生命周期。
      • 组合(Composition):在组合关系中,子对象的生命周期完全依赖于父对象。当父对象被销毁时,子对象也会随之被销毁。
    • 所有权:
      • 聚合:表示一种较弱的关系。子对象可以被多个父对象共享或关联。
      • 组合:表示一种更强的关系。子对象严格属于一个父对象,并且通常不与其他父对象共享
  • answer from slids:
    • In Aggregation, The object exists outside the other, is created outside, so it is passed as an argument
    • In Composition, The object only exists, or only makes sense inside the other, as a part of the other

4.1 Aggregation in java

  • An object of class B is part of an object of class A (semantically) but the object of class B can be shared and if the object of class A is deleted, the object of class B is not deleted.

4.2 Composition in java

  • An object of class A owns an object of class B and the object of class B cannot be
    shared and if the object of class A is deleted, the object of class B is also deleted
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    // 聚合示例
    class Engine {
    // Engine 的方法和数据
    }

    class Car {
    private Engine engine; // 聚合关系Aggregation

    Car(Engine engine) {
    this.engine = engine;
    }
    }

    // 组合示例
    class Room {
    // Room 的方法和数据
    }

    class House {
    private Room room; // 组合关系Composition

    House() {
    room = new Room(); // Room 在 House 创建时被创建
    }
    }
    //在聚合示例中,Car 类有一个 Engine,但是 Engine 可以独立于 Car 存在。
    //在组合示例中,House 和 Room 之间的关系更紧密,Room 的生命周期与 House 相关联。
    //当 House 被销毁时,Room 也会被销毁。
    //更多是概念上的关系,而不是代码上的关系

5.Inheritance & Polymorphism

What is inheritance and why do we use it?
  • answer comes from slids:
    • Inheritance: Forming new classes based on existing ones
    • Superclass: Parent class being extended
    • Subclass: Child class that inherits behaviour from the parent class
    • “Is-A” relationship
What is the difference between polymorphism, method overloading, and method overriding?
  • answer comes from slids:
    • Polymorphism
      • Polymorphism is an object oriented concept
      • Method overloading and method overriding are two forms of polymorphism
    • Method overloading
      • Methods with same the name co-exists in the same class but they must have different method signature (number/type of parameters – think about constructors)
      • Resolved during compile time (static binding)
    • Method overriding
      • Method with the same name is declared in super and sub class (think about the bike1.currentState() example from labsheet 1)
      • Resolved during runtime

6.Abstract Methods & Classes, Interface


Usually abstract class(eg.animal) implement an interface(eg.Maintainable), and the abstract class get Inheritanced from other classes(eg.reptile). The abstract methods in abstract class(or it should be called superclass) and methods in interface can be overrided in subclass.

What is the difference between an abstract class and interface in Java?
  • answer comes from slids:
    • Java abstract class
      • Can have instance methods that implement a default behaviour(可以同时有abstract method和instance method)
      • May contain non-final variables
    • Java interfaces
      • Methods are implicitly(含蓄地) abstract and most cannot have implementations(无instance method)
      • Variables declared are by default static and final

7.Java Release

the history of java release from java8-java21 can be checked at https://www.codejava.net/java-se/java-se-versions-histor

8.refactoring code

  • Improved Code Quality
  • Enhanced Readability
  • Reduced Code Duplication
  • Maintainability
  • Scalability
  • Performance Optimisation

9.Basic Maintenance

  • Goal:
    • Improving current code without creating new functionality
    • Keep the code well organised and easy to maintain in the future
  • Examples (see also Lecture 1A)
    • Adding unit tests
    • Renaming
    • Packaging
    • Avoiding code duplication
    • Comments and documentation
    • Moving code to where it belongs
    • Using correct access modifiers (encapsulation)

lecture 3 - Introduction to GUI programming in Java

1.Graphical User Interfaces(GUI)

  • GUIs are a form of user interface that allow users to interact with electronic devices through graphical icons […] as primary notation, instead of text-based user interfaces, typed command labels or text navigation.
  • GUIs are event-driven, the user decides the order of execution depending whether they click a button, or select a
    drop-down, or choose a menu item etc.The system is waiting for something to happen
    Guiding principles for designing high quality GUIs?
    1. Keep it simple
    2. Create consistency and use common elements
    3. Be purposeful in page layout
    4. Strategically use colour and texture
    5. Use typography to create hierarchy and clarity
    6. Make sure that the system communicates what’s happening
    7. Think about the defaults

2.Basics of GUI programming-Swing&Javafx

  • Swing is java’s first attempt at a modern GUI apporach. it came about in late 1990s. Swing is built on the AWT(Abstract Window Toolkit)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    import javax.swing.*;
    import java.awt.*;
    pubtic class HelloWortdSwingGUIApp extends JFrame {
    public He1toWor1dSwingGUIApp(){
    initUI()
    }
    private void initUI(){
    setSize(width: 600, height: 600);
    setTitle("My first GU I in Java Swing. Hello wortd!");//窗口标题
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE) ;
    JPanel pannel= new JPanel(new GridBagLayout());
    JButton buttonl = new JButton(text: "Exit program");//按钮
    button1.addActionListener(new ActionListene() {
    @Override
    public void actionPerformed(ActionEvent e) {
    System.out.println("NOw we will exit the program");
    System.exit(0);
    }
    });
    pannel.add(bUtton1) ;
    this.add(pannet) ;
    }

    public static void main(String[] args){
    EventQueue.invokelater(new Runnable(){
    @Override
    public void run(){
    new HelloWorldSwingGUIApp().setVisible(true);
    }
    });
    }
    }
  • Swing is being slowly retired in favour of JavaFX, following are hello word for javafx.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    import javafx.application.Application;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;

    import java.io.IOException;

    public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) throws IOException {//take a stage as input
    //this stage is the whole windows
    stage.setTitle("你看什么看");
    Button button1 = new Button("我草泥马!!!");//button, one of node objects
    button1.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent actionEvent) {
    System.out.println("Bye Bye!");
    System.exit(0);
    }
    });
    StackPane root = new StackPane();//node object
    root.getChildren().add(button1);//node object can contain other node object, eg.button
    stage.setScene(new Scene(root,600,600));//put all the node object together,
    stage.show();//make it visible
    }

    public static void main(String[] args) {
    launch();//move to the javafx thread
    }
    }

3.getting started with Javafx

javafx consists of stage, scence and node

  • Stage: Think of it as an application window. Depending on OS, there may be only one. Equivalent to Swing’s JFrame (or JDialog)
  • Scence: Equivalent to a content pane. Holds other objects (JavaFX Node objects)
    In other word, if the application is a play. The whole play contains several Scence, at the same time all the action scence take place on a Stage. Node are some element in the scence.

3.1 Adding simple 2D Graphics

  • can change Pane to StackPane making the line staying at middle.
  • Except Pane and StackPane, there are other built-in layout panes in javafx. eg.vbox,gridpane,Hbox and AnchorPane….

4.MVC pattern and FXML

MVC stands for Model-View-Controller.

  • View tells controller what happened
  • Controller inform the model what to do
  • Views catches relevant notifications and updates

5.FXML

So far we build GUI in code. But if the GUI is going to get compilcated, Javafx supports describing the layout using FXML(in fx markup language).

  • We can use Scence builder to creat fxml file graphically.
    Why use FXML? What do people think are the benefits?
    • UI designers might not be programmers
    • The designers can use external software (such as Scene Builder) to design the look of the UI whilst the programmers can build the functionality
      • FXML glues the two aspects together
    • Building GUIs visually rather than programmatically makes intuitive sense
    • Event handling is simplified
    • We can test/fix application logic without touching the GUI design or vice versa

6.Multiple Windows in Javafx

javafx use setScence() to swith scence, which makes user get different windows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class HelloApplication extends Application {
private Scene scene1, scene2;

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Java FX Multiple Scenes");

Label label1= new Label("Primary View");
Button button1= new Button("Switch to Secondary View");
button1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
primaryStage.setScene(scene2);//switch to scence2
}
});
VBox layout1 = new VBox(20);
layout1.setAlignment(Pos.CENTER);
layout1.getChildren().addAll(label1, button1);
scene1= new Scene(layout1, 300, 400);

Label label2= new Label("Secondary View");
Button button2= new Button("Switch to Primary View");
button2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
primaryStage.setScene(scene1);//switch to scence1
}
});
VBox layout2= new VBox(20);
layout2.setAlignment(Pos.CENTER);
layout2.getChildren().addAll(label2, button2);
scene2= new Scene(layout2,400,300);

primaryStage.setScene(scene1);//begin with scence1
primaryStage.show();
}

public static void main(String[] args) {
launch(args);
}
}

lecture 4 - OO analysis and UML

1.UML overview

UML:” A specification defining a graphical language for visualizing, specifying, constructuing and documenting the artifacts of distributed object systems.”

Advantages of using UML
  • Enhances communication and ensures the right communication
  • Captures the logical software architecture independent of the implementation language
  • Helps to manage the complexity
    • Abstraction
  • Enables reuse of design

Use Case Driven process is used in OO project.

2.Use Case Diagrams

Use cases diagram describe a set of actions that some system or systems should or can perform in collaboration with one or more external users of the system or systems
Use case diagram components:

  • Actors:
    • Entities that interface with the system
    • Can be people or other systems
  • Use cases:
    • Based on user stories
    • Represent what the actor wants your system to do for them
    • In the use case diagram only the use case name is represented
    • In a use case specification each use case is formally described
  • Subjext(system boundary)
    • Classifier representing a business, software system, physical system or device under analysis, design, or consideration
  • Relationship
    • Relationship between use case and actor: Association indicates which actor initiates which use case
    • Relationship between two use cases: Specifying common functionality and simplifying use case flows. Using <<include>> or <<extend>>
      difference between include and extend
      • include are used when multiple use cases share a piece of same functionality.即big action后面的small action, 箭头指向small one.
      • extend used when activities might be performed as part of another activity but are not mandatory for a use case to run successfully. 即part of optional action, 箭头指向大的

3.Use Case Specification

看不懂,先跳过

4.Activity Diagrams

Activity Diagrams representations of workflows of stepwise activities and actions related to an individual use case or across many use cases. Its’ components:

  • Activity: A state that is left once the activity is finished
  • Activity edge: Transition that fires when previous activity completes
  • Synchronisation bar: Describes the co-ordination of activities
  • Decision diamond: Used to show decisions
  • Start and stop marker: Used to define entry and exit points
  • Swim lane: A way to group activities performed by the same actor on an activity diagram or to group activities in a single thread

5.Sequence Diagrams:

Sequence diagrams are a temporal representation of objects and their interactions

6.Stat machine Diagrams:

Stat machine Diagrams shows the possible states of a single object, the events or messages that cause a transition from one state to another, and the action that result from that state change

7.Class Diagrams

A class diagrams shows the existence of classes and their structures and relationships in the logical view of a system

  • It has Following components:
    • Classes(name+attributes+operations)
    • Class relationships
    • Multiplicity indicators: Number of links between each instance of the source class and instances of the target class(1; ; 0..; 1..*; 3..7)
  • relationships:
    • 1.Realisation实现关系: a specialised abstraction relationship between two sets of model elements, one representing a specification (the supplier) and the other representing an implementation (the client) of the specification
      • 有implements关键词,指向interface,—– + 空心菱形
        1
        2
        3
        4
        5
        interface Running{...}

        class Human implements Running{
        //...A and B are realisation
        }
    • 2.Generalisation泛化关系/"is a": A directed relationship between a more general classifier (superclass) and a more specific classifier (subclass)
      • 有extend关键词,指向superclass,———— + 空心菱形
        1
        2
        3
        4
        5
        class Animal{...}

        class Bird extends Animal{
        //...B and A are generalisation
        }
    • 3.Dependency依赖关系: you may invoke one of the APIs of the received class reference and any modification to that class may break your class as well
      • 作为变量/返回值应用,指向原本class
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        class Die{
        public void roll(){...}
        }

        class Player{
        public void takeTurn(Die die){
        die.roll();
        //...Player and die are dependency
        }
        }
    • 4.Association关联关系: Class A holds a class level reference to class B
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      class Wheel{...}

      class Car{
      private Wheel wheel
      ...
      public Drive(Wheel new_wheel){
      this.wheel = new_wheel;
      ...
      }
      }
    • 5.Aggregation聚集关系/"is part of": used when an object logically or physically contains another. 在技术上和Association同
    • 6.Composition组合关系: class B is composed by class A, class A instance owns the creation or controls lifetime of instance of class B(拿房子和房间举例,Room is composed by House)

8.built tools

  • built tools
    • helps reduce errors from manually running steps
    • increases the consistency of the process
    • manage the dependencies
    • keep a build log and allow better maintenance
    • automatied testing…
  • We have mentioned Maven and Gradle.

built tool 1 - Maven

  • manage dependencies and other settings in a POM (project object model) file, which base on xml.

built tool 2 - Gradle

  • Replaces XML in favour of a domain specific language groovy
  • the offical build system for android

lecture 5 - GUI-javafx adcances

1.ImageView

1
@FXML private ImageView myImageView;

2.CheckBox

1
@FXML private CheckBox myCheckBox;

3.ComboBox

1
@FXML private ComboBox myComboBox;

4.MeunBar

please search online

5.Alert

1
2
3
4
5
6
7
@FXML
private void onAboutClicked(){
Alter alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("About...");
alert.serContentText("This is the text for alert window");
alert.show();
}

6.About styling

can change the theme by using css (Cascading Style Sheet)

1
2
3
4
.button {
-fx-background-color: red;
-fx-text-size: 22;
}

the css file can get referenced by using scene.getStylesheets() in java file.

7.JavaFX Application Thread

  • JavaFX launches the UI on a JavaFX Application thread
  • This thread should be left handling the UI interaction, while other thread do heavy computation to prvent freezing.
  • Use javafx.concurrent pakage to make javafx creat and communicate with other threads.

8.Animation in JavaFX

Types of animations in Javafx:

  • Timeline Animation
  • Transition Animation
  • Path Animation…

Key concepts for Timeline Animation

  • Timeline: Denotes the progression of time during animation with an associated key frame at a given
    instance
  • Key Frame: Represents the state of the node being animated at a specific instant on the timeline
  • Key Value: Represents the value of a property of a node along with an interpolator to be use
  • Interpolator: By default linear; changes the property being animated linearly with time. (except LINEAR线性, it can also be EASE IN缓入, EASE OUT缓出, BOUNCE弹性, SPRING…)

an example of animation form my cw, this makes a lable change its size with time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Add jumping animation to a label at the main page
* @param label the label to which the animation will be applied.
*/
public static void addJumpingAnimation(Label label) {//makes the label has sample cartoon
Timeline timeline = new Timeline(); //Creat timeline object
KeyValue keyValue1X = new KeyValue(label.scaleXProperty(), 1);
KeyValue keyValue1Y = new KeyValue(label.scaleYProperty(), 1);
KeyValue keyValue2X = new KeyValue(label.scaleXProperty(), 1.2);
KeyValue keyValue2Y = new KeyValue(label.scaleYProperty(), 1.2);
KeyValue keyValue3X = new KeyValue(label.scaleXProperty(), 1);
KeyValue keyValue3Y = new KeyValue(label.scaleYProperty(), 1);
KeyFrame keyFrame1 = new KeyFrame(Duration.ZERO, keyValue1X,keyValue1Y); //creat key frames
KeyFrame keyFrame2 = new KeyFrame(Duration.seconds(0.8), keyValue2X,keyValue2Y);
KeyFrame keyFrame3 = new KeyFrame(Duration.seconds(1.6), keyValue3X,keyValue3Y);
timeline.getKeyFrames().addAll(keyFrame1, keyFrame2, keyFrame3);
timeline.setCycleCount(Timeline.INDEFINITE); //Set the animation properties
timeline.play(); //run the animation
}

lecture 6 - Coding and Repository Tools for DMS

1.Use of git

  • 基本操作:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    git checkout http://svn.example.com/repos/calc //change a branch?
    git clone xxx.xx //clone a repository
    git commit xxx -m "your message here" //commit message
    git push //或者git push -u origin master
    git pull //update local code

    git branch dev //creat a new 'dev' branch
    git branch -d dev //delect a branch
    git checkout dev //change to to the dev current branch
    git status //knowing which branch we are

    git checkout -- README.md //roll back to the latest commit version(仅限local change)
    git checkout HEAD README.md //checks out the most recent version of file
  • 如何把dev branch给merge到master branch:
    • 先把dev该commit的commit好
    • git checkout master切换到master branch
    • 使用git pullpull any changes made to this branch from the server
    • 使用git merge dev将dev branch merge into the master
    • 使用git pushpush the merge result back to the server
  • Ignoring files using .gitignore file:
    • touch .gitignore
    • echo "*.class">.gitignore
  • commit is a atomic operation(要么完全发生要么不发生)
  • 一些可能存在的文题:
    • 1.Edit Collision(编辑冲突): 多个编辑者对同一文件的同一部分进行修改便会发生
    • 2.3-Way Merge(三方合并): 两个同祖先MASTER的分支FEATURE和做过了修改的MASTER在merge时,git会执行三方合并(新master,旧master,feature)
    • 3.Head Error: 使用git checkout检测一个不存在的分支时发生

2.Coding Convention

  • legible software contain fewer bugs, more legible software is more flexible and encourages reuse.
  • This include Bob’s coding convention and Java Coding Conventions from Sun Microsystems

Bob’s Rule 1 - Method Length (75 lines or less)

Rule 2 - Indentation缩进(less than 5 levels)

Rule 3 - Line Length below 80 characters

Rule 4 - Class Variable Names

Rule 5 - Accessor Methods

  • Enforce encapsulation
  • please define them at the “top” of the file, since they are most common to use.

Rule 6 - Class Variables

  • Keeping class variables private enforces encapsulation.

Rule 7 - Method Naming

  • Private method lower-case begin, Public mrthod Upper-case begin.

Rule 8 - Method Parameters (less than 5)

Rule 9 - Symbolic Constants

  • Do not use numbers in your code, but rather symbolic constants.
  • xx + xx = 255 –> xx + xx = MAX_ALPHA

3.Javadoc Documentation

  • Describe what you are commenting about
  • simmiler to in-line comment, but in class or higher level.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /**
    * main class for the whole project
    * @author NingboWEI
    */
    public class Main {
    /**
    * start the game
    * @param args default input for main, it is useless at here
    */
    public static void main(String[] args) {
    GreedySnakeApp.launchGame();
    }
    }

lecture 7 - OO Software Design principles & Patterns

Why OOD Principles and Patterns
  • Software development specifications keep changing constantly
  • Software need to be smart enought to cope
    • easy to maintain
    • easy to extend
  • Following systematically conventions(惯例) so others can also maintain your code.

SOLID Principles

  • Object Oriented Design Principles for Clean Coders. This could help us to develop our code sense.

1.S-Single Responsibility Principle,单一职责原则

  • A class/method should have one and only one responsibility

2.O-Open-Closed Principle,开闭原则

  • Software entities(classes, modules, functions…) should be open for extension, but closed for modification
    • behavior of the modules can be extend
    • source code of such a module is invoilate. No one is allowed to make source code change of it
  • Abstraction and override is a key
    The right one is a better approch, perfer extension instead of modifying

3.L-Liskov’s Substitution Principle,里氏替换原则

  • Subtypes must be substitutable(替代物) for their base types
  • This is just a way of ensuring that inheritance is used correctly(保证inheritance类的一致性consistency)
    eg.duck can get inheritance from bird class and use fly(), but penguin can't get inheritance since they don't use fly()
    example

4.I-Interface Segregation Principle,接口隔离原则

  • Client should not be forced to depend upon interfaces that they do not use.
  • an extension of the single responsibility principle. Fat interfaces should be broken down.
    interface居然有inheritance???

5.D-Dependency Inversion Principle,依赖反转原则

  • “High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.
  • aims to reduce coupling(耦合) between difference pieces of code by adding a layer of abstraction.
    • 高层和低层模块都应当依赖于一组定义良好的abstraction,从而降低二者耦合(减少互相影响)
  • Dependency inversion is a generalisation for the Open-Close and Liskov Substitution Principles

Design Patterns & Examples

  • A pattern provides an abstract description of a design problem and how a general arrangement of elements solves it
  • Design patterns are organised in two ways:
    • Purpose:
      • Creational: Concern the process of object creation.
      • Structural: Deal with the composition of classes and objects.
      • Behavioural: Characterise the way in which classes and objects interact and distribute responsibility.
    • Scope:
      • Class: These patterns deal with relationships between classes and sub-classes (which are fixed at compile time)
      • Object: Deal with object relationships (which can be changed at runtime)

1.The Singleton Pattern(Creational)

  • Create a one of a kind object for which there is only one instance
  • Use static method and private classes to ensure only one instance and able to providing a global point of access to it.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    public class Singleton {
    private static Singleton uniqueInstance;//Static variable to hold single instance

    private Singleton ( ) {
    //private constructor
    }

    //Instantiate class and return a single instance of it
    public static Singleton getInstance( ) {
    if ( uniqueInstance == null){
    uniqueInstance = new Singleton( );
    }
    return uniqueInstance;
    }
    }
  • However Singleton have problem in concurrent request, threading, interfacing with subclasses…

2.The Factory Pattern(Creational)

  • Create objects without exposing(暴露) the create logic to the client, and refer to newly created object using a common interface.
  • They hide how objects are created and help make the overall system independent of how its objects are created.

  • There are also Abstract Factories, a factory of factories.
    Abstract Factories/ AbstractPizzaFactor

3.Adapter Pattern(Structural)

  • This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces.允许不兼容的接口一起工作

4.Observer Pattern(Behavioural)

  • Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically.
  • It consists of two roal: Subject + Observer
    Observer Pattern Example

lecture 8 - Refactoring

  • Legacy Code maintenance is the core of software enginering.(legacy code即旧版本老代码)

1.Identify Code Smell(代码异味)

Code smells because it is hard to undersdand, not because it is incorrect. Here are some examples:

  • Duplicated Code: it is bad because if you modify one instance duplicated code but not the others, you may have introduces a bug
  • Long Method/Class: long method are more difficult to understand, reduce cohesion
  • Long Parameter Lists: hard to undrsatand, can become inconsistent
  • and Lazy Class, Temporary Field, Data Class….

2.Refactoring code

Refactoring means modiy the exisiting code making it easy to read, maintance, more efficient…
Refactoring reduces repetition and helps focus on objects

2.1.Encapsulate Fields to retain private variables

  • Un-encapsulated data是对OOP的一种违背(violation)
  • 要合理的使用get和set
  • 可以Encapsulating Fields Automatically With IDEs

2.2.Extract(提取) method from a large block of code

  • Short, well named methods are easier to maintain
  • can Create a new method to perform the extract method

2.3 Replace Parameter with Explicit Method

  • Create a separate method for each value of the parameter
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    void setValue (String name, int value) { 
    if (name.equals("height")) {
    height = value;
    return;
    }
    if (name.equals("width")) {
    width = value;
    return;
    }
    Assert.shouldNeverReachHere();
    }
    //change the above one to-->
    void setHeight(int arg)
    {
    height = arg;
    }
    void setWidth (int arg)
    {
    width = arg;
    }

2.4 Inline Method to reduce indirection

  • 使用return num > 5 ? 2 : 1;将method压缩至一行

2.5 Repalce Temp with Query

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
double calculateTotal(){
double basePrice = quantity * itemPrice;
if (basePrice > 1000){
return basePrice * 0.95;
}
else
return basePrice * 0.98;
}
//change the above code into-->
double calculateTotal() {
if (basePrice() > 1000) {
return basePrice() * 0.95;}
else {
return basePrice() *
}
double basePrice() {
return quantity * itemPrice;
}
}

2.6 Rename Variable or Method To Self Document

2.7 Remove assignments to parameters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int discount (int inputVal, int quantity){
if (inputVal > 50)
{
inputVal -= 2;
}
// ...
}
//change the above code into-->
int discount (int inputVal, int quantity){
int result = inputVal;
if (inputVal > 50)
{
result -= 2;
}
// ...
}

3.Refactoring code at a higher level

3.1 Replace type code with polymorphism

  • switch替换为polymorphism, switch在oop中不常用,会被认为code smell

3.2 Single Reponsibility with Extract Class

  • break one class into two

3.3 Generalization with Extract Interface

  • Extract an Interface from class, folloing the Interface Segregation design principle

3.4 Push Down/Pull Up of methods

  • move a method to a higher hierarchy(super class) if it is duplicate on one or more classes. push down反之亦然(移动到subclass)

4.Applying a design pattern in Refactoring

  • 看不懂一点,先过

lecture 9 - Open Source

  • an overview of how to use third party code in the form of libraries and open source projects

1.Liabrary

  • Library is Some 3rd party software packaged up (in binaries) and ready-to-use in your own code
  • Libraries in java consists of:
    • a jar file(a zip file, not runnable jar file)
    • an API
    • Usually include a licence

2.open source software development and maintenance

  • Open source software(OSS) is free software that uses any licence approved by the Open Source Initiative (OSI) from their list of approved open source licences (link below)
  • Why go open source?:
    • Higher quality, Customisable, Improvable, Collaborative bug finding/fix, Free
    • It is a good thing in industry since it has good advertising and attract talented developers
  • open source可以是仅仅几行代码,也可以是a method, a class,…or a complete system(Linux, Android)

3.Licences

  • Software licences are to protect ur code and any future developers of the code.
  • Some common OSS(open source software) licences:
    • Permissive license: Subsequent(随后的) users can produce close source version and sell the software(我开源但不强制二次开发开源,写上我的名字就好)
    • CopyLeft license: Any subsequent versions are left with the same rights e.g. source code must be supplied, and can be modified(我开源了二次开发也必须开源)