Beiyou State Institute of Internet of Things Software Engineering Software Engineering Notes

Mainly follow the exam-oriented study of the ppt in the class.
Acquisition of pdf files: Add the WeChat public account at the end of the article: Huihaisong, and reply "software engineering" in the background to obtain the files.


Article directory

Introduction

software types

general: developed for a general market. (ps, office)

custom: developed for a particular aim. (embeded system)

good software features

delivers required functionality

usable

efficient

dependable

maintainable

understandable

cost-effective

security

what is software engineering?

using proper theories, tools, methods(organized and systematic), constraints to develop high quantity software.

4 layers

Tools, method, process, quality focus.

Why important?

large scale projects are hard to finish in time properly because of time, budget, disaster, etc. guiding scientific principles and universally applicable methods can reduce practice and frequent failures.

General issues that affect software

Heterogeneity (distributed systems, different type of devices), business and social change, security and trust, scale.

Software process

a set of structured activities to produce software.

includes: required specification, development(analysis, design, implementation), validation (test), evolution.

  • required specification: what should this system do? a complete desc of the problem and environment constraints. contains: system function, future extension, documentation amount, time and preformance response
  • analysis: create a conceptual model.
  • design: implementable model (architecture, components of this system).
  • implementation: implementation of interfaces.
  • testing: unit, functional, integration, system, acceptance. test and implementation should run in parallel.
  • deployment: install, run and test on real environment.
  • evolution: corrective, adaptive, perfective, preventive.

process models

a abstraction of process. activities must be modelled to be managed.

waterfall

1685629715429

Easy to manage monitor, well structured. The previous modules must be completed before jumping to the next one, which requires us to be very clear about the requirements at the time of the initial design, but it is difficult not to encounter some problems, and it is difficult to follow the normal process.

evolutionary development

1685629943510

Interactive activities, timely feedback. The core requirements can be well met, but the scalability is poor, the structure is poor, and the visibility in the process is lacking. Good for small projects.

rational unified process

1685630556923

inception: Analyze project feasibility.

elaboration: Analyzing risk, architecture.

construction: iterative Iterative development until the beta version.

transition: delivered to the customer.

Generic complete flow, dynamic. But it costs a lot.

Agile Software Development

The Modern Software Development Process: Agile Development.

Rapid software development Rapid development: Strive to deliver something deliverable to customers for each version.

Agile development: The system is built in small increments one iteration at a time. specification, design, implementation, testing in parallel. Focus on code, lightweight code is released frequently, and maintenance is simple.

image-20230507002834816

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Customer collaboration over contract negotiation

Responding to change over following a plan

Agile development requires project managers beyond programmers, operations, testing...

Agile development focuses on value, and don't design things that are worthless. In practice, we must solve the problem of document segmentation, and the documents must have corresponding audiences, and the system should not be over-designed.

Agile development focuses on steer rather than percise prediction. An iterative plan is jointly developed by customer priorities and programmer estimates of feature difficulty.

Development principles:

• Emphasis on simple design and refactoring.

• Removing duplication.

• Increasing cohesion.

• Reducing coupling

Common agile development methods: such as Extreme Programming.

  • Build new versions several times a day
  • Submit an incremental version to users every two weeks
  • Requirements are described by users
  • Programmer Pair programming (two people sit together and develop together, the efficiency is almost the same, and they know each other's code better)
  • Develop test units first, then write code
  • After testing, the build is complete

Test Driven Development (TDD):

  • Define both an interface and a specification.
  • Write the test first and then the code.
  • Test Incremental based on incremental design.
  • Automated testing after each build.
  • Customers participate in testing User involvement, including programmer unit testing (unit test), customer confirmation testing (acceptance testing, to see if it meets the requirements).

Agile development issues:

  • Customers tend to lose motivation customers interests.

  • Team members don't necessarily like team development.

  • Multiple stakeholders are involved, prioritizing change is difficult.

  • Difficult to maintain simplicity, maintaining simplicity.

  • Frequent changes, contract design is difficult to contract.

Suitable for changeable, small and medium-sized systems with clear customer requirements.

requirements

Determining requirements is the most important part of software design.

  • feature to satisfy customer.

  • indicates what should this sys do.

  • It may be high-level abstract or low-level specific.

Stakeholder Stakeholders: Organizations or individuals affected by the system (of course, some software may be developed for market needs without specific users). These people have different opinions from different angles.

Customers do not necessarily clearly describe their needs, nor do they necessarily have a clear understanding of product features and functions, and their needs may change continuously.

The extra time invested in identifying requirements saves more time and money in the long run.

Requirements are divided into: functional and non functional.

functional requirements

Define the requirements of the system and what to do. For example, the educational administration system provides different services for teachers and students.

This part should be completeness, clear and consistent, describe the large requirements of consistency, and avoid unnecessary misunderstandings.

non-functional requirements

This part is more important than functionality, which is equivalent to system errors that do not meet this part, and there are some small bugs in the system that does not meet the functional requirements.

Define system properties and constraints, such as time and space complexity, equipment capability.

Process requirements: such as quality standards, programming languages, etc.

Organizational requirements: For example, the system must comply with IT policies.

external requirements: For example, "user passwords cannot be disclosed".

1685634113657

Non-functional requirements require quantitative description indicators. Otherwise, for example, "I hope the program runs faster" is very vague. There must be a measure method area to measure quantitative indicators.

Requirement conflicts

Trade-off needs to be weighed, so that everyone agrees on an optimal demand.

Requirement document

Software Requirements Specification (SRS) Software Requirements Specification, a reference specification for confirmation testing, specifies the requirements that should be realized, but does not specify how to achieve them.

Requirements Capture

Background Reading

Interviewing

Observation (observe the user's use of the system)

Document or Record Sampling (professional observation)

Questionnaires

Requirements in agile development

usr stories

User needs are called user stories, and a sentence or two is written on a card.

The customer sorts their requirements, and the development team decomposes the implementation tasks.

As a user, I want to backup my entire hard drive so that I won’t lose any work.

Write it on the stories cards, and post them on the wall in order for everyone to discuss. Note that the focus is not on the record but on everyone's discussion.

Project glossary

Some technical terms related to the project are suggested to be summarized to facilitate everyone's understanding and discussion.

image-20230601235612956

Epics

Great usr story. Often it is broken into small chunks before starting a discussion.

image-20230601235720919

Acceptance Criteria

Acceptance criteria, usually written on the back of the story card, help in understanding requirements and invite negotiation with the team about the business value that we are trying to create.

Non-functional Requirements as User Stories

For example, the user said: I want the computer to play cf fps higher than 100.

Notes on usr stories

  1. Anyone can write, it is better to let more members write.
  2. It can be written throughout the agile development process. At the beginning, the story discussion meeting will determine the basics, and it can be added at any time later.

Product backlog

Requirements table with requirements sorted by priority. Comprehensive consideration of various factors.

MoSCoW: A dsdm approach to dynamic systems development.

  • must have: the most important.
  • should have: Can be overridden if the time resource is exceeded.
  • could have: the needs expected by users, and the user satisfaction will be high after completion. But not necessary.
  • want to have: Not important at the current stage.

Estimating

Estimate project time.

story point: A story point used to represent an estimate of all the work required to complete a product backlog item or any other piece of work.

When estimating in story points, we assign a point to each backlog item. The original data of the estimated results of the backlog items is not important, we only focus on the relative estimated results obtained at the end. A user story with an estimate of 2 should be twice as large as a user story with an estimate of 1. And it should also be two-thirds of the other user story with an estimate of 3.

Instead of 100, 200, 300, or 1 million, 2 million, 3 million, teams use 1, 2, 3. Estimates are ratios, not absolute values.

What exactly is a story point in agile development? - Zhihu (zhihu.com)

Judge good usr story

INVEST principle.

– Independent – Negotiable – Valuable – Estimatable – Small – Testable

Prototyping

physical: such as drawing gui.

logical: elements, associations between elements...

Low-fidelity low-fidelity: the simplest, such as hand-drawn drawings, made of cardboard, quickly verify the feasibility of the product concept.

Medium-fidelity: digital models.

high-fidelity: such as 3D printing, the closest to the product but troublesome to make.

1685636483862

analysis

The information obtained only from the needs of users is not comprehensive and needs to be analyzed. The user may think that you understand, or he has not considered comprehensively and feels that some places are unnecessary.

So we need analysis to Refining requirements.

gather requirements-analyse in real world context-develop the architecture

Analysis includes: Textual analysis (for document analysis), Entities and concepts (application level analysis), Experience (past experience analysis)

conceptual model

Object-oriented UML diagrams.

The boundary class is used to model the external environment and internal interaction of the system. My understanding is the glue layer between different systems. Coupling between systems can be reduced.

Control classes are used to model control behavior specific to one or a few use cases. Control classes are derived from the definition of behavior in use case scenarios.

Entity classes are classes that model the information and associated behavior that must be stored.

UML-Analysis Class_Iron_Sky's Blog-CSDN Blog

image-20230602013913446

attributes: attributes and corresponding data types. Such as name, string.

Operations: behavior method. An operation generally only does one thing.

relationships: – Association – Inheritance.

  • associations means that there is a two-way connection between two classes. For example, a teacher teaches many students. There are 1-to-1, 1-to-many, etc. relationships.
  • Inheritance inheritance, parent class generalization subclass specialization.

Activities:

  1. Identify Entity, Boundary and Control classes
  2. Identify class relationships
  3. A conceptual class diagram
  4. Identify attributes for each entity class
  5. Add constraints

design

Design is to transform the analysis model into a design model, not code implementation! Implementation is the realization.

design must have a purpose: how things works.

A software design: enough information for a development team to implement the solution.

roles

  • finish non-functional requirements
  • break down the overall task.
  • Create a 'skeleton' of the system Create a skeleton structure that is easy to implement.

Fundamental Concepts

  • Abstraction: Functionality of abstract classes and behaviors.
  • Encapsulation: information hiding. Restricts direct access to content by certain objects.
  • Modularity: Packaged into modules and provide interfaces to other modules.
  • Coupling: Coupling, the closeness of the relationship between modules. It is best to loosely couple, so that it is not easy to affect the whole body.
  • Cohesion: Cohesion, the correlation of its own elements within the module. Preferably high.
  • Refactoring: Correct the code to reduce duplication under the premise that the code is normally completed. Major improvements to non-functional properties.

The benefits of object-oriented design: objects are entities; objects can be reused and inherited; some system objects are obvious mappings of the real world.

steps

conceptual class diagram

Class Relationships

operations

Describing methods

Captures implementation requirements

Produce detailed design class diagram

Implementation

The analysis and design phase basically lays out the ideas. The implementation is to type the code mechanically according to the previous design.

Use some components to achieve. Components mainly include: excutable executable file, file source code and data, document, table database table.

The implementing subsystem implements some functions and uses the packaging function to export a module with an interface.

Integration Build Plan iteratively builds the project, and each build points out the functions realized by the build and the subsystems and components needed for the build.

OOP: There are classes, objects, methods. But the association is not bidirectional, but only unidirectional, such as:

1685692184183

1685692194908

One-to-many allows one class to contain a collection of objects of another class.

The implementation of the class should be from least coupled to most coupled.

Testing

Find errors as much as possible before delivering to users, and verify the results of each stage. Testing takes up 40%.

Component level: developer testing.

Integration Tests: Test Engineers, focus on quality.

  • Validation testing: Validation testing, the normal requirements of the test system have been met.
  • Defect testing: Detect system defects.

Testing policies

It is impossible for us to find and test all possible situations. Therefore, only a representative subset can be selected.

Good testing: Testers can predict where errors may occur; there are no redundant test cases; use cases that are "most likely to fail" should be selected; appropriate complexity.

1685693050733

test case: the specification of the input and the expected output.

test data: input.

1685693215844

testing strategy

what test case? when test? how to test? How to compare the output is correct?

Example of test cases (correct input. Wrong input such as student number input in English):

image-20230602160905111

Test Procedures Test procedures are usually set to be universal, so that they can be modified and reused later. This program is not necessarily a code, it may be in the form of process guidance (for example, press the login button, enter the account number 99001122 to log in...)

test matrix:

image-20230602161119974

Found defects: For example, in the above example, a wrong password can also log in, so the test engineer returns the error message to the developer:

image-20230602161157432

Testing: Techniques

Black box test, black box/behavior test, that is, the module we want to test, looks like a black box whose internal structure is invisible to us. We focus on whether its behavior is correct, whether the interface with the outside world is correct, and whether the access to the external database is correct. Incorrect.

  • Partition testing: A typical black-box test that divides the data into several equivalent areas, such as positive and negative 0.
  • Scenario-based testing: Triggered from the user's perspective, analyze the user's possible correct and incorrect operations.
  • Regression Testing: Integration testing, adding new tests as increments are added, and running all test cases each time to ensure that the previous functions are not disturbed when the system is updated.

White box test, white/glass/clear box test, mainly focuses on the internal structure of the program to run according to the specification, and all internal components are correct.

Make sure all paths inside the box are executed correctly; consider right and wrong use cases; test in and out of bounds; use internal data structures where possible.

  • Basis Path Testing: Execute the minimum number of test cases for all paths.

1685696256126

Overall testing process: white box testing, build a test harness testing device, test correctness, test robustness; then black box testing.

TDD

assertEquals(20, student.getAge());//判断返回值是不是20岁

Write tests before developing code. Simple, short-cycled mechanism.

1685710646767

small cycle: write test, write code, test fails, modify code, test passes.

Software architecture

Functional requirements are closely related to software architecture, and non-functional requirements are the result of software architecture selection (a good architecture has high operating efficiency, etc.). Can be in the form of a table or a diagram, such as a UML diagram.

Design is difficult to change. An early stage of agile development is designing the system architecture.

benefit:

  • system analysis: It is beneficial to analyze whether the system meets the non-functional requirements.
  • large-scale reuse: The architecture is reusable, safer and faster.
  • Stakeholder communication: Can be a discussion point.

Project management

So that the project can be implemented within the limited time and budget as expected and with high quality.

Software engineering is relatively flexible, and there is no standard and completely correct solution. It requires adaptability and keen insight.

Project planning

The most time-consuming part.

The plan is not complete until the project is complete, because the plan is constantly changing during the project development phase.

Plans may include various such as quality plans, staff development plans...

Activity organisation

Activities should be organized into tangible outputs and progress that can be judged.

Milestone: marks the end of the stage, not necessarily a result that can be output to users. Like documentation, or the end of a logic phase.

Deliverables: Designs, specifications, etc. that can be delivered to users.

image-20230602221047262

Project scheduling

Estimate the cost of the project time budget and arrange it in order.

It is difficult to estimate. Usually estimated based on past project experience.

First break down a large project into several small projects, and then organize tasks concurrently—make full use of labor force as much as possible, and minimize task dependencies to minimize delays in subsequent tasks because previous tasks are not completed.

It is impossible to have no mistakes. About 30% expected problems + 20% unanticipated problems.

Usually represented graphically:

Task list:

1685724379869

Activity network: The longest is the critical path, because if the task on this path is postponed, the entire construction period will be postponed.

1685724395138

Gantt chart:

1685724424966

Monitoring/Reporting: Regular weekly meetings and weekly reports to monitor progress.

Metrics

Lines of code, defects in code, test case passing.

People in the process

Select members, manage them, motivate them, and solve technical and non-technical problems that everyone encounters.

  • Consistency: The attitude towards everyone is the same.
  • Respect: Everyone has different skills and respects each other.
  • Inclusion: Let everyone participate in the project and listen to everyone's opinions.
  • Honesty: Progress is kept honest.

Group working

Not just a collection of individuals. Composition of team capabilities, cohesion, communication, hierarchy of large teams.

The teamwork method of agile development: Scrum approcah, there is a Scrum master, daily meetings, follow the progress, record decisions, and communicate with customers.

Projects are broken down into manageable and understandable small pieces. Unstable requirements do not affect the project schedule. Team members have better control over the visibility of the project, customers can often see the progress of the project, and the two sides communicate more trust each other.

Risk management

Failure is common. We have to prepare alternative plans, postpone the time or give up the goal.

Risk management is anticipating possible failures and deciding where to develop alternative plans.

Project risks: Project development or resource issues. For example, the project staff left; the raw materials could not be received in time; the project required time was advanced.

Product risks: Product quality and performance issues. For example, there are bugs in the developed software, the quality of the developed software is not good, the user is not satisfied with the GUI, and there are mistakes that have not been considered.

Business risks: development, procurement organization issues. For example, when the technology of other companies was listed on the market, the competing products were better than ours; the organization responsible for the system closed down due to financial reasons.

Project+Product: The requirements keep changing; the analysis phase is too slow; the development team's skills are not good enough; the project is bigger than expected.

Risk Identification

Identify risks.

Risk Analysis

Assess the impact of the risk.

Risk Planning

Create a plan to address the risks.

Risk Monitoring

Monitor risks during project development.

Avoidance Strategies

Try to use familiar models, but also accept new technologies and keep an eye on market trends;

Reasonable training for employees to ensure that technology is not in the hands of one person; create a good working environment;

Employees should not lie about the progress, and executives should always know the progress and its importance to the project.

Contingencies

Change people, change tools, change resources.

Change, abandon part of the goal.

Strive to make the smallest changes, but also minimize the loss.

We know that agile development continues to submit small versions, so testing and revisions are often made when stage errors occur. But the disadvantage is that agile development does not pay attention to long term planning, so it may cause some problems.

Quality Management

The assessment of quality is best taken out of the software development process. Because the development process will wrongly affect the developer's own assessment of quality (I have worked so hard, the things I made must be good).

In the waterfall model, software quality is tested separately after the system is implemented. Agile development tests every time a new version is released. Because it is mainly a test in actual use, it will think more than the system "developed to achieve the test".

Good software fits the purpose of Fitness for purpose, with good standards, easy to use, high efficiency, and well-written code (of course, from the user's point of view, he cannot see this layer. But well-written code is the premise, such as time complexity. quick). Under the premise of considering the needs of users, developers need to use their professional knowledge to think: Is the realization of this demand reasonable. Then drink more users to communicate and express their opinions.

Distinguish between bugs and features: what works is the feature. Sometimes even if the system has unexpected bugs, but the function is unexpectedly suitable, this can also be a feature.

Features are difficult to remove. When users start to rely on feature functionality, users may not be happy and unaccustomed to it; and backward (version) compatibility becomes difficult.

Software standards have many benefits, new employees get started quickly, and everyone is more familiar with the project, etc., but the standard may take an attitude of ignoring some problems that often occurred in the past but rarely occur now, resulting in compatibility problems; and it may waste a lot of time to fill in paperwork. Focus on the good parts.

Design principle

The designed software must not only run correctly and efficiently, but also under limited time, manpower, software, and economic conditions. Poor code may take a lot of time to make up for hidden dangers in the later stage; and the codes of different modules often interact, and poor code will also have security risks.

It is not enough for us to just think about how to write code "correctly", but also to develop with less trouble and effort.

Software lifespan: Software life cycle, software is continuously developed, such as new technologies and new needs of customers.

Software scale: Most projects have large specifications, developed by many people, with many codes and multiple revisions.

Decomposition: The project is broken down into small modules for development. It has the characteristics of Locality (implementing a module without checking the implementation of other modules) and Modifiability (modifying a module without considering the module that uses this module).

Specification and implementation: The specification connects the design and implementation, specifying which services the module should provide and how to use the services. The interaction between modules should be limited to specifications, so as to realize the locality and modifiability of the decomposed modules.

Classes and Methods: Modules in object-oriented thinking are classes.

Separation: Separately consider the function what and how of a module to be realized. One application level, one implementation level.

Splitting Methods and Classes: When designing methods and classes, consider how to split methods and classes. If the class is too large, consider whether to dismantle it. Several variable patterns are more commonly used, and consider whether to abstract it into a class.

Helper Methods and Classes: There are some methods and classes that are only used to abstract them to assist in splitting code. These are generally private helper methods and nested classes, which only work in specific classes and are private to other classes. .

Reuse: Use the previous code to repeat the function, save the code, and change it completely. Reusable code may be provided by vendors, provided by programming languages, and developed by early developers.

Abstraction and generalization: Abstraction is to extract some concepts, such as interfaces and classes; generalization is to extract some repetitive elements for code reuse, such as parent classes.

UML class diagrams: A higher level than code, which is a very important content of object-oriented programming.

Static v. Dynamic: Match static content and content generated when the code runs. Corresponds to the class diagram class diagram and the sequence diagram sequence diagram in UML.

Source: UML Class Diagram and Sequence Diagram_Relationship between Sequence Diagram and Class Diagram_lingchen336's Blog-CSDN Blog

img

img

class and objects: classes and objects. Objects are instances of classes. The relationship between the two is very similar to the method in static and the method call in dynamic.

static: Static methods can only be called by the class itself and its attached classes. The object instantiated by the static class is only one common object, instead of instantiating countless objects.

Variables and referencing: Variables in java are references to objects. For example, var2=var1 is not an assignment but changes the reference of var2 to var1. Including a variable's own method

image-20230603233317997

1685806438306

Scope and garbage collection: As long as there are variables in the scope of the object that still refer to the object, it is alive. Automatic garbage collection when no one references it.

Basic design principles: design objects refer to targets; object methods refer to the operations they can do; Locality and Modifiability; objects can only interact through method calls.

Client-Contractor model: An idea in which an object calls a method of another object to get a return value to use it, like a client or a contractor. The reason why modern society has made great progress is that everyone has their own specialties, so each category in the project can play more roles under the premise of the same amount.

  • A contract from a client to a contractor is like a specification that defines classes and methods. Code writers are obliged to Obligations to ensure that the software is executed correctly and does not do damage, etc. after taking the benefits of the money.

  • Design by Contract: a thought. The client code should meet the pre-conditions of the contractor; it should handle exceptions; the post-conditions should be incorporated into the program as assertions in the test. (Pre-condition: premise; Post-condition: state after the method runs)

Single Responsibility Principle (SRP)

Single Responsibility Principle: Each class has a responsibility responsibility, and all its objects serve this responsibility. Leads to highly cohesive

Open-Closed Principle (OCP)

Open and closed principle: modules (classes and methods) open to extension, close to modification

Being open to extension means that when there are new requirements or changes, the existing code can be extended to adapt to new situations.

Closed to modification means that once the class is designed, it can complete its work independently without any modification to the class. For example, a class is expressed in the form of different objects, which is extension, because the requirements change or there are new requirements.

Do not Repeat Yourself principle (DRY)

Don't repeat the machine principle (don't repeat yourself principle). If duplicate content is found in this module, it is recommended to abstract it into methods and classes.

**Liskov Substitution Principle (LSP) **

Liskov Substitution Principle: Overriding a method should not hold the idea of ​​"modifying its method". The strengthening precondition cannot be strengthened, and the weaken postcondition cannot be weakened.

For example, the parent class people method AddPeople(String name, int age) and the subclass Student construction method AddPeople(String name, int age) first check the age of the student. If the age is greater than 25 years old, add is not allowed, which modifies the original method . This means that the preconditions have been strengthened, and the required age limit has been increased.

For example, if the post-condition originally returned a value greater than 0, but now the return value can be less than 0, then the return value restriction is weakened, the post-condition is weakened, and the Liskov principle is not satisfied.

Reference: Six Principles of Design Patterns (2) - Li-style Replacement Principle - Blooming Sun - Blog Garden (cnblogs.com)

Association, Aggregation and Composition: Association is the correspondence between two different things, such as parents and children. The other two are subsets, and aggregation can exist independently of each other, such as classes and students. Composition can exist independently of each other, such as house and room.

1685957816284

Sometimes inheritance cannot satisfy LSP (for example, a subclass that makes a square a rectangle), and clustering can be used to prevent LSP from being destroyed.

Interface-Segregation Principle (ISP)

Principle of interface isolation: First, the interface should be decomposed into small interfaces as much as possible. Each client class should not depend on methods it does not use. It is what the interface uses to implement what, don't implement too much.

Dependency-Inversion Principle (DIP)

Dependency Inversion Principle:

If the high-level module directly invokes the services provided by the low-level module, then it is a specific coupling relationship, so it is inevitable that the high-level module depends on the low-level module. However, if we use an abstract coupling relationship, an abstract interface is defined between the high-level module and the low-level module, the high-level module calls the method defined by the abstract interface, and the low-level module implements the interface. In this way, the direct dependencies between high-level modules and low-level modules are eliminated. Now, high-level modules don't depend on low-level modules, both depend on abstractions. At the same time, it also realizes that "abstraction should not depend on details, and details should depend on abstraction".

Object-oriented basic design principles: 4. Dependency inversion principle - Zhihu (zhihu.com)

img

Dependency Inversion Principle (Dependency Inversion Principle) - sangmado - Blog Park (cnblogs.com)

Design Patterns

Decorator Design pattern

Decorator patterns for extending system functionality.

For example, if we have a duck class, we can call its duck calling method. We have initialized a duck object, how to count how many times this object has called, that is, how many times its duck calling method has been called? Remember that OCP principles don't allow us to modify duck classes directly.

We can wrap the duck class with a count class.

image-20230605183433552

The decoration mode implements an interface, and the method in the interface calls the same method through the same parameter of the variable. For example, in this example, it is the count of ducks quacking, and ++ is called each time.

Adapter design patterns

1685983233527

1685983255642

This example includes several principles:

  1. First of all, the functions of different interfaces should be separated as much as possible. ISP, that is to say, duck calling and counting should not be written in one method.
  2. Classes cannot be modified directly, OCP.
  3. If you want to count duck calls at the same time, just call the wrapper class directly, DRY.
  4. GooseAdapter only has access to Goose's honk method and not its full access, DIP. If you change it to an inherited subclass here, you will have full access rights.

Wrapper design patterns

Wrapper mode includes decorator and adapter. The decorator mainly means that both the outer wrapper class and the inner class implement an interface, such as the duck quack in the above example. adapter is an inner class and does not need to be implemented.

Immutable View: The problem of java references was mentioned earlier. For example, two variables refer to the same object, and they will be changed once they are changed. This is equivalent to when there is a reference, the target object is completely exposed. In the wrapper, we can restrict the wrapper class: modifying the object is prohibited, and an exception is thrown if the modification is made.

1685986070602

Composite Design Pattern

Wraps a collection.

1685985869548

Observer Pattern

For example, when a car sees a green light, it knows it is time to leave. This kind of observer changes one variable and affects the realization of other variables.

Java provides an observable api, which triggers a function when the value of the corresponding variable changes.

1685986641156

1685986768769

1685986796502

However, this way of writing violates OCP, because we modified dogbot to let him actively implement the update of observer. We can take the decorator design approach.

1685989787205

If dogbots is an interface, dogwatcher can implement the counting function, and can also implement dogbots in files and gui, and implement dogbots in collections. The codes of the two are almost separated.

We first use an ObservableDogBot class to inherit Observable, and implement unfinished dogbots, and then write a dogreporter to implement observer. at lastrover.addObserver(reporter1);

Factory Methods

If we set a dog whose hunger value is greater than 6 to be constructed as greedyDogBot is a subclass of ordinary dog, then both PlainDogBot and greedyDogBot directly provide the construction method is not very good. You can use a construction class to determine what object needs to be returned.

image-20230606123312445

This constructor can return the interface class, but the actual method returns the concrete class that implements the interface class, so that the return class type can be hidden:

1686026157643

The factory class can even wrap the class itself and send back a wrapper class:

1686026296136

Of course, in addition to static factory methods, they can also be non-static factory objects. We can use different factory objects to wrap different wrapper classes, which can further hide some information of the returned object.

For example, in the next example, the spy dog ​​has one more watcher. We initialize two Dog Factories with polymorphic methods, but one is of the actual SpyDogFactory type, and the other is of the actual PlainDogFactory type, so when they call makeDogBot, different dogs will be returned.

1686026555327

For additional packaging functions such as counting, we can also wrap the counting content in the factory class instead of "wrapping the common class with a counting class and then wrapping the counting class with a factory class".

1686026955303

1686026838784

Singleton Design Pattern

The constructor does not necessarily return a newly created object, and the factory class can return an existing object.

1686027588395

Pay attention to the LSP principle.

Object Pool Design Pattern

The object pool pattern keeps a list of objects and returns a specific object when needed.

Strategy Design Pattern

Select a policy to enforce.

1686027938500

The picture above is a function of the dog performing several actions. We can also use the rewritten Comparator to realize the conditional structure, such as comparing how many times the two dogs bark, ab and ab, and make up for the difference if they bark less.

State Design Pattern

The state type of an object can be changed.

The following changed types are the implementation classes of the accountState abstract class, which are initialized in a polymorphic way.

image-20230606180142747

Bridge Design Pattern

Decouple thoughts. For example, if we need brushes of 12 colors, we can choose 12 crayons with fixed colors, or 1 brush and 12 kinds of paints. The brush example decouples brushes and colors well.

Example source: Handling multi-dimensional changes - bridge mode (1)_LoveLion's Blog-CSDN Blog

The following example: find the intersection of father and son.

image-20230606181219816

Flyweight Pattern

Sharing a large number of objects with a lot of internal state and little external state can be shared in a cache-like manner.

Concept source: Intensive reading of "Design Patterns - Flyweight Enjoyment Mode" - Zhihu (zhihu.com)

image-20230606181617881

Open Source Software

free of charge, free of legal restrictions on usage.

Agile development is also required, but the development method is slightly different, after all, it is not a stakeholder model. It emphasizes close personal interaction between individuals, and developers are also their own customers, so many people do testing, and the modified small version can be released quickly; usually there are many small modules, and everyone from all over the world develops separately.

People all over the world communicate with each other electronically.

The overall co-ordinator is usually a volunteer.

Commercial software and OSS are like the difference between a cathedral and a bazaar. The cathedral needs to have an overall construction goal, and everyone should work together. The bazaar may be managed by an overall coordinator like the urban management, but everyone is still more personal.

If your company develops projects by itself, of course it will require a lot of human and financial resources for development and later maintenance; if you choose closed-source software, you are bound to the supplier (monopoly technology), and we have to pay them for further fees. With open source software, you don’t have to worry about payment fees or supplier closures, but you can’t just use open source software, so pay attention to copyright issues.

Most open source software has a small group of people developing the core and new functions, and most of them are correcting defects. In most cases developers prefer to maintain existing forks instead of developing new ones.

Open source software also has a control structure. Usually, the person who first proposed the project has the final decision-making power of the software, and it is managed by some commercial companies rather than individuals (this can ensure better quality). For example, Android open source software is controlled by Google. For submitted Fork and patch have the right to finalize the content of the next version update.

  • Contributor: A person who contributes in OSS.
  • developer: A person who develops applications on a software platform.
  • verifier: A person who tests whether the change request is correct.
  • Approver: The person who decides whether these modifications should be merged into the large version, and the verifier need to review the interview screening.
  • Project leads: Oversee the engineering of individual projects.

software freedom

  • free run the program

  • Study how this program works, change it so it does your compute as you wish (provided you can access the source code, of course)

  • Free redistribute copies for distributing copies of software

  • Free distribute copies of your modified versions to others.

Copyright

Only the producer producer has the right to produce copies and create new work based on it, but can authorize others to make copies of the work and adapt it. Producers can give these powers to others by means of charging, or limit the scope of adaptation, because this is an obligation imposed on the producer, and it is normal to have some rewards.

Copyleft

However, the OSS copyright statement uses copyleft, a free software license, which does not limit the right of others to copy and adapt, but empowers others to do so. The content of the license includes: statement that the source code is available, and the scope of adaptation permission.

voting

Those who have the right to vote can have at most one vote; those who do not have the right to vote cannot vote; those who have the right to vote and choose to vote cannot be prevented from voting; they must have sufficient choices of full choice; their voting results must be counted correctly and cannot be Others tamper; the total number of votes is added correctly and cannot be tampered with; most of the time no one can know the choice of any voter.

Electronic voting has risks, such as data being easily tampered with and forged.

Software Development Tools

Software Craftsmanship and Clean Code

Pay attention to the cleanliness of the code, such as formatting, comments, etc.

Saying “No”

Don't always blindly agree to the needs of the boss and customers. Programmers are more familiar with the code and need to help the boss avoid possible mistakes.

Learning from Mistakes

Microsoft’s Best Practices

Revision Control System

version control.

roll-back: Version rollback.

check-out: The developer pulls down the code.

check-in: The developer submits his own revision.

conflict: The submissions of two people conflicted.

merge: Merge into the main branch.

Daily Build

Build the code once a day, compile and link the source code, and do some tests to ensure that everyone can use the latest version the next day.

Continuous Integration

The developer also recommends checking-in once a day.

Build Verification Tests

Assertions and unit tests.

Bug Database

Record previous bug records, solutions, severity, priority and other information.

War Team and Bug Triage

Prior to release, the operations team confirmed that the system was "good enough to release". Check for normal operation, remaining bug severities, etc.

Code reviews and coding guidelines

Teams conduct thorough reviews of each other's code.

Globalisation and Localisation

Differential handling for different languages ​​and scripts.

Documentation Generators

Document generation.

Guess you like

Origin blog.csdn.net/jtwqwq/article/details/131149566
Recommended