10 object-oriented design principles that Java programmers should know, java Object-Oriented Design

Source: Internet
Author: User

10 object-oriented design principles that Java programmers should know, java Object-Oriented Design

Object-Oriented Design principles are at the core of OOPS programming, but most Java programmers I have seen are enthusiastic about design patterns such as Singleton, Decorator, and Observer, instead of focusing enough on Learning Object-oriented analysis and design. It is important to learn basic knowledge about object-oriented programming, such as "abstraction", "encapsulation", "polymorphism", and "inheritance". However, in order to create a concise and modular design, understanding these design principles is equally important. I often see java programmers of different levels of experience. Some of them do not know these OOPS and SOLID design principles, and some do not know what benefits a specific design principle will bring, I don't even know how to use these design principles in coding.

(Design Principles) the bottom line is always the pursuit of high cohesion, low coupling coding or design. The open source code of Apache and Sun is a good example of learning Java and OOPS design principles. They show us how the design principles are used in Java programming. Java JDK uses some design principles: factory mode in the BorderFactory class, Singleton mode in the Runtime class, and decorator mode in the java. io class. By the way, if you are really interested in Java coding principles, read the objective Java of Joshua Bloch, which has written Java APIs. My personal favorite object-oriented Design patterns is Kathy sitle's Head First Design Pattern (deep dive into the Design patterns), and others on deep dive into object-oriented analysis and Design. These books are of great help to write better code and make full use of various object-oriented and SOLID design patterns.

Although the best way to learn design patterns (Principles) is to use examples in reality and understand the inconvenience caused by violations of design principles, the purpose of this article is to introduce object-oriented design principles to Java programmers who have never been involved or are in the learning stage. I personally think that the OOPS and SOLID design principles need to be clearly described in the article. I will do my best to do this here, but now you are ready to browse the following design patterns (Principles)

DRY-Don't repeat yourself

Our first object-oriented design principle is: DRY. From the name, we can see that DRY (don't repeat yourself) refers to abstracting code into reusable code blocks instead of repeating code. If you have more than two identical code blocks, consider abstracting them into a separate method. Or if you have used hard-coded values multiple times, set them to public constants. The advantage of this object-oriented design principle is that it is easy to maintain. It is important not to abuse this principle. repetition is not for code but for functionality. It means that if you use common code to verify OrderID and SSN, it does not mean they are the same or they will remain unchanged in the future. You can use common code to implement two different functions, or you can closely associate these two functions. When your OrderID format changes, your SSN verification code will be interrupted. So be careful with this coupling, and do not combine code similar to each other that has no relationship with each other.

Encapsulate frequently modified code

Encapsulate What Changes

What remains unchanged in the software field is "change", so encapsulate the code that you think or suspect will be modified in the future. The advantage of this object-oriented design model is that it is easy to test and maintain properly encapsulated code. If you are using Java programming, follow these principles: the access permissions for variables and methods are set to private by default, and their access permissions are gradually released, for example, from "private" to "protected" and "not public ". Some Design Patterns in Java use encapsulation. The factory design pattern is an example. It encapsulates the code for creating objects and provides the following flexibility: subsequent generation of new objects does not affect the existing code.

Design principles for opening/disabling

OpenClosed Design Principle

Classes, methods, and functions should be open to extensions (new functions) and closed to modifications. This is another elegant SOLID design principle to prevent someone from modifying the tested code. Ideally, if you have added new features, your code needs to be tested, which is the goal of enabling/disabling design principles. By the way, the "O" letter in SOLID refers to the principle of opening/closing the design.

Single Responsibility Principle

Single Responsibility Principle (SRP)

The single responsibility principle is another SOLID design principle. The SOLID letter "S" refers to it. According to SRP, there should be only one reason for modifying a class, or a class should always implement a single function. If you implement multiple functions in a class in Java, these functions are coupled. If you modify one of these functions, you may have broken this coupling relationship, so another round of testing is required to avoid new problems.

Dependency injection/inversion principle

Dependency Injection or Inversion principle

Do not ask what benefits the dependency injection function of the framework will bring to you. The dependency injection function has been well implemented in the spring framework. The elegance of this design principle lies in: any class injected by the DI framework is easy to test with simulated objects and easier to maintain, because the code for creating objects is centralized in the framework and isolated from the client code. There are multiple ways to implement dependency injection, such as using bytecode tools. Some of the AOP (cross-section programming) frameworks such as entry-point expressions or proxies used in spring. For more information about this SOLID design principle, see the examples in IOC and DI design patterns. The letter "D" in SOLID refers to this design principle.

Give priority to combination instead of Inheritance

Favor Composition over Inheritance

If possible, use combinations instead of inheritance. Some of you may argue about this, but I find that combinations are more flexible than inheritance. A combination allows you to modify the behavior of a class by setting attributes at run time. By using polymorphism, You can implement the composite relationship between classes in the form of interfaces, and provide flexibility for modifying the composite relationship. Even objective Java also recommends that you use combinations instead of inheritance.

Rys replacement principle

Liskov Substitution Principle LSP

According to the Rys replacement principle, child classes can be used to replace the parent class. For example, there should be no problem in replacing the parent class method or function quilt class object. LSP is closely related to the single responsibility principle and interface isolation principle. If a parent class has more functions than its child classes, it may not support this function and violates the LSP design principles. To comply with the lsp solid design principles, the derived class or subclass (compared with the parent class) must enhance the functionality, rather than reduce. The letter "L" in SOLID refers to the LSP design principle.

Interface isolation principle

The interface isolation principle means that if you do not need an interface function, do not implement this interface. Most of these occur in the following scenarios: An Interface contains multiple functions, and the Implementation class only needs one of them. Interface Design is a tricky task, because once an interface is released, you cannot modify it. Otherwise, the class that implements the interface will be affected. Another benefit of this design principle in Java is that an interface has a feature that all methods of this interface must be implemented before any class uses it, therefore, using a single interface means less implementation.

Programming is centered on interfaces rather than implementation objects.

Programming is always centered on interfaces (rather than implementation objects), which makes the code structure flexible and any new interface implementation object can be compatible with the existing code structure. Therefore, in Java, use interfaces for the Data Types of variables, method return values, and method parameters. This is the advice of many Java programmers, as is the advice of many books such as objective Java and head first design pattern.

Proxy principles

Do not expect a class to complete all the functions. You can assign some functions to the proxy class as appropriate. A typical example of proxy principles is the equals () and hashCode () methods in Java. To compare whether the content of two objects is the same, let the classes used for comparison complete the comparison, rather than their callers. The benefit of this design principle is that there is no repeated encoding and it is easy to modify the behavior of classes.

Summary

All of the above object-oriented design principles can help you write flexible and elegant code: code structure with high cohesion and low coupling. The theory is only the first step. More importantly, we need to learn the ability to discover when to use these design principles. Discover whether we violate design principles and affect code flexibility, but nothing in the world is perfect. When we solve problems, we cannot always use design patterns and design principles, most of them are used for large enterprise projects with long maintenance periods.

Java study and exchange QQ group: 523047986 chat prohibited, do not enter!

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.