10 Object-oriented design principles that Java programmers should know

Source: Internet
Author: User

Object-oriented design principles are at the heart of oops programming, but most of the Java programmers I've seen are enthusiastic about design patterns like Singleton (singleton), Decorator (adorner), OBSERVER (Observer), Instead of focusing enough attention on learning object-oriented analysis and design. It is important to learn the basics of object-oriented programming like "abstraction", "encapsulation", "polymorphism", and "inheritance", but it is equally important to understand these design principles in order to create concise, modular designs. I often see Java programmers of different levels of experience, some of whom do not know these oops and solid design principles, and some simply do not know how a particular design principle will benefit, or even how to use these design principles in coding.

(Design principles) The bottom line is always to pursue high cohesion, low-coupling coding or design. Apache and Sun's Open source code is a good example of learning Java and Oops design principles. They show us how design principles are used in Java programming. The Java JDK uses some design principles: the factory pattern in the Borderfactory class, the singleton pattern in the runtime class, and the adorner pattern in the Java.io class. By the way, if you're really interested in Java coding principles, read Joshua Bloch's effective Java, who has written Java APIs. My personal favorite about object-oriented design patterns is Kathy Sierra's head first design pattern, and other aspects of object-oriented analysis and design in layman's. These books are a great help in writing better code, taking advantage of the various object-oriented and solid design patterns.

Although the best way to learn design patterns (principles) is to present real-world examples and understand the inconvenience caused by violating design principles, the purpose of this article is to introduce object-oriented design principles to Java programmers who have not been exposed to or are at the learning stage. Personally, oops and solid design principles need to be clearly described in this article, we must try to do this, but now please prepare to browse the following design patterns (principles).

Dry–don ' t Repeat yourself

Our first object-oriented design principle is: DRY, from the name you can see that DRY (don ' t repeat yourself) means not to write duplicate code, but to abstract it into reusable blocks of code. If you have two or more blocks of the same code, consider abstracting them into a single method, or you use hard-coded values several times, set them as public constants. The advantages of this object-oriented design principle are ease of maintenance. It is important not to misuse this principle, and repetition is not for the code but for functionality. It means that if you use generic code to verify OrderID and SSN, that doesn't mean they are the same or they will remain the same in the future. By using the generic code to implement two different functions, or you are closely linking the two different functions, your SSN verification code will be interrupted when your OrderID format changes. So be careful with this coupling, and don't put together code that doesn't have any relationship with each other but similar.

Encapsulate code that is frequently modified

Encapsulate what changes

In the realm of software, the constant is "change", so encapsulate the code you think or suspect will be modified in the future. The advantage of this object-oriented design pattern is that it is easy to test and maintain properly encapsulated code. If you are programming in Java, follow these guidelines: Access to variables and methods is set to private by default, and access to them is gradually released, such as from private to protected, not to public. Some design patterns in Java use encapsulation, and the factory design pattern is an example that encapsulates the code for creating objects and provides the following flexibility: Subsequent generation of new objects does not affect existing code.

Open/Close design principles

openclosed Design Principle

classes, methods/functions should be open to extensions (new features), closed to modifications. This is another elegant solid design principle to prevent someone from modifying the code that passes the test. Ideally, if you add a new feature, your code will be tested, which is the goal of opening/closing the design principles. By the way, the letter "O" in solid refers to the principle of open/close design.

Single principle of responsibility

Single Responsibility Principle (SRP)

The single principle of responsibility is another solid design principle, and the letter "S" in solid refers to it. According to the SRP, the reason for a class modification should be one or the other, or a class should always implement a single function. If you implement multiple functions in one of the classes in Java, there is a coupling between these features, and if you modify one of these features, you might break the coupling, and another round of testing is necessary to avoid creating new problems.

Dependency Injection/Reversal principle

Dependency injection or inversion principle

Instead of asking what the framework's dependency injection function will do for you, the dependency injection function has been well implemented in the spring framework, and the elegance of this design principle is that any class injected by the DI framework is easy to test with mock objects and easier to maintain. Because the code that creates the object is centralized in the framework and is isolated from the client code. There are several ways to implement dependency injection, such as using bytecode tools, some of which are AOP (aspect-oriented programming) frameworks such as pointcut expressions or proxies used in spring. To learn more about this solid design principle, see examples in the IOC and di design patterns. The letter "D" in solid refers to this design principle.

Prioritize using combinations rather than inheritance

Favor composition over inheritance

If possible, use the combination rather than the inheritance as a priority. Some of you may argue about this, but I find the combination more flexible than inheritance. A combination allows you to modify the behavior of a class at run time by setting properties, implementing a composite relationship between classes as an interface by using polymorphism, and providing flexibility for modifying the composition relationship. Even effective Java recommends using combinations rather than inheritance.

The principle of the Richter replacement

Liskov Substitution Principle LSP

According to the principle of the Richter substitution, the place where the parent class appears can be replaced with subclasses, such as the parent class's methods or functions. The quilt class object substitution should have no problem. LSP is closely related to the principle of single responsibility and interface isolation. If a parent class has more functionality than its subclasses, it may not support this feature, and it violates the LSP design principle. In order to follow the LSP solid design principle, a derived class or subclass (compared to a parent class) must enhance functionality rather than decrease it. The letter "L" in solid refers to the LSP design principle.

Interface Isolation principle

The principle of interface isolation is that you do not implement this interface if you do not need the functionality of an interface. Most of this occurs when an interface contains multiple functions, and the implementation class requires only one of these features. Interface design is a tricky task because once the interface is published, you cannot modify it otherwise it will affect the class that implements the interface. Another benefit of this design principle in Java is that the interface has a feature that any class uses it before all the methods of the interface are implemented, so using a single interface means implementing fewer methods.

Programming is centered on interfaces rather than implementing objects

Programming is always centered on interfaces (rather than implementing objects), which makes the code more flexible, and any new interface implementation object can be compatible with the existing code structure. So in Java, the data type of the variable, method return value, method parameter, use the interface. This is the advice of many Java programmers, such as effective Java and head first design pattern.

Agent principle

Do not expect a class to complete all the functions, you can properly put some functions to the proxy class implementation. The example of the proxy principle is the Equals () and Hashcode () methods in Java. To compare the contents of two objects, let's compare the classes themselves to do the comparison work rather than their callers. The advantage of this design principle is that there is no duplication of coding and it is easy to modify the behavior of the class.


All of these object-oriented design principles can help you write flexible, elegant code: A code structure with high cohesion and low coupling. Theory is only the first step, and more importantly, we have to acquire the ability to discover when to use these design principles. To find out if we violate the design principles and the flexibility of the code, but nothing in the world is perfect, we can't always use design patterns and design principles when solving problems, mostly for large enterprise projects with longer maintenance cycles.

10 Object-oriented design principles that Java programmers should know

Related Article

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.