Object-oriented design (Oo Design Recommendations for J2EE Applications) - Expertoneonnej2eedesignandDev

xiaoxiao2021-04-08  470

Object-oriented programming is important than any specific technique. But when using all kinds of patterns, it should also be prevented.

Excessive design, increasing unnecessary complexity, waste time and funding.

1. Use interface to reduce the coupling of the program (Achieving Loose Coupling with Interfaces)

Although interface-oriented programming is directly opposed to specific classes to increase a little bit of complexity, the benefits are huge.

1), you can change the implementation without changing the calling code. This allows us to re-implement a part of the program without having to modify other parts.

2), you can freely implement the interface and promote reuse.

3) If necessary, a simple test implementation can be written, or Stub is implemented.

2, try to use the combination, not inheritance (Prefer Object Composition to Concrete Inheritance)

Combined with greater flexibility, it can change the behavior of the program at runtime. Strategy and State mode are based on this theory.

3, template mode (The Template Method Design Pattern)

The template mode is a correct use of direct class inheritance. But you know some of the steps of algorithms, but you don't know how your specific operations can use the template mode, keeping the specific operation to the future implementation. Relying on reverse rotation is a use of template mode, which makes the frame code to call the user's own code, rather than normal user code to remove the code of the frame. The template pattern is especially suitable for frame design.

4, strategy mode (the Strategy Design Pattern)

The strategy mode is slightly complicated than the mode mode, but provides greater flexibility. However, the policy mode should be used when there is a situation:

1) When all the steps of the algorithm can be changed, not only a few times

2) When a class that implements the specific steps has a specific inheritance level

3) When the class needs to be related to the specific steps, it is related to other classes.

4) When these steps need to change during runtime

5) When the implementation of the specific step of the algorithm is continuously increased

5, use the callback increase scalability (Using Callback to Achieve EXTENSIBILITY)

The callback is a special use of the strategy mode. He can achieve special operations, and handle the error, the Logging is placed in the frame. Such as:

Public Interface RowCallbackHandler {Void ProcessRow (ResultSet RS) throws sqlexception;} public void query (string sql, rowerbackhandler callbackhandler) throws jdbcsqlexception {Try {

..... while (rs.next ()) {CallbackHandler.ProcessRow (RS);

....} catch (sqlexception ex) {....

} finally {

....

}

Advantages of callback:

1), you can focus on error handling and resource acquisition, release. This allows you to achieve more flexible, more powerful errors, and do not increase the workload.

2), the underlying implementation details are independent.

3) A workflow, can complete different work through different implementations. Fully realize the reuse of the code.

Disadvantages of callback:

1), this mode does not let you see the called code directly. This may make the code become less likely to understand and maintain. 2), you must create a callback accepting interface or class.

3), I don't know what to write again.

This mode is especially suitable for the callback interface. It is very simple. It is best to call only one way, which can be implemented in the form of the Inner class.

6, observer mode (The Observer Desing Pattern)

This mode is only needed when there is a loose COOSELY COOPLED LISTENER that needs to be understood in the system. If we use him excessive use, it will cause the business to be submerged by the code (Event). Only important workflows may need to implement him. Listener must be able to return quickly and thread security. The listener who can't put back in time may block this program.

7. Perfecting the parameters of the method (Consider Consolidating Method Parameters)

Sometimes, we need to compress a plurality of method parameters into an object, which simplifies the code. The biggest advantage is to change the parameters of the method, but do not have to change the calling code, and can pass the default parameters of the simple implementation method. Disadvantages is that small objects with a large number of parameters, these objects will consume spaces.

8. Exception Handling - Checked or Unchecked Exceptions

Java will be unusually divided into: checked exceptions, unchecked (runtime) Exceptoins. Checked Excetions inherits and java.lang.exception, not statement and capture; Runtime Exceptions inherits with java.lang.RuntimeException, no life, can not capture. (Abnormality in C , C # is equivalent to unchecked exceptions)

Although traditional views think try to use Checked Exception as much as possible without Runtime Exception. But the author is not much thought, the reasons are as follows:

1), too many code

2), difficult to read

3), endless packaging Exception

4), easy to become a statement

5), resulting in unnecessary associated underlying realization.

The author believes that when a function returns two options to return it, it is necessary to judge, it is best to make a compiler to enforce it. That is to use Checked Exception, other situations, the author thinks that Checked Exception is over-emphasized.

Note: Checked exceptions is better than using Return Codes, which can force users to capture exceptions. However, Checked Exception is not suitable for indicating fatal errors, and the caller does not need to capture an exception. The J2EE container has a responsibility to capture and record the Runtime Exception.

Whenever you need to decide which exception is used, you need to ask yourself a few questions:

1) Do you need to handle this error? Whether an exception is another return value as a method.

Example: ProcessInvoice ()

Answer: Using Checked Exception, let the compiler help us check it.

2) Is there only a few calvity to handle this error?

Example: JDO EXCEPTINOS

Answer: Use Runtime Exception. Let the user can capture or not capture. 3) Is it very serious? Is it unusually recovered?

Example: Due to the database, the business exception is caused

Answer: Use Runtime Exception. In addition to notifying users, the caller cannot do any other useful things.

4), isn't it clear?

Answer: Use Runtime Exception. Let the caller determine if it is captured.

Note: It is best to declare anomalies when using Runtime Exception.

Good abnormal capture practice: Save the original exception, override the getMessage () and printstacktrace () methods.

Let the exception contain more information:

1) If the program needs to respond to different exceptions, it is necessary to define an exception of a series of uniform interfaces, and in each class as a special process.

2) For the exception of the user, it is best to define a getRrorcode () method, put the actual exception message in Properties, so that it is convenient for future processing.

3), exception information must be as detailed as possible! [WebApplicationContext failed to load config] is not a good message, the message should be written as [WebApplicationContext failed to load config from file /WEB-INF/applicationContext.xml ': can not instantiate class' com.foo.bar.Magic' attempting To load bean element with name 'Too' - Check That this class has a public no arg constructor. The difficulty seems to be very large.

Nine, use reflection (use reflection)

Reflection allows the program to load, instantiate, and operate at runtime. Reflection can also enhance many design patterns, such as factory mode, there is no need to write class names in the program and can be directly configured to file.

Reflection and Swithches (Reflection and Switches)

public void vetoableChange (PropertyChangeEvent e) throws PropertyVetoException {if (e.getPropertyName () .equals ( "email")) {String email = (String) e.getNewValue (); validateEmail (email, e);} ...} Else if (E.GetPropertyName () .Equals ("age)) {Int Age = ((Integer) E.GetNewValue ()). INTVALUE (); Validateage (AGE, E);}

...}

It is a normal attribute check code, but if we need to increase or delete an attribute, we need to modify these judgments, which means we need to retest. But if we use reflection, you can solve it very elegant solution.

public AbstractVetoableChangeListener () throws SecurityException {Method [] methods = getClass () .getMethods (); for (int i = 0; i

public final void vetoableChange (PropertyChangeEvent e) throws PropertyVetoException {Method m = (Method) validationMethodHash.get (e.getPropertyName ()); if (! m = null) {try {Object val = e.getNewValue (); m.invoke (This, New Object [] {VAL, E});} catch (illegalaccessException ex) {system.out.println ("Warning: can't validate." "Validation Method" M "'ISN't accessible ");} catch (InvocationTargetException ex) {// We do not need to catch runtime exceptions if (ex.getTargetException () instanceof RuntimeException) throw (RuntimeException) ex.getTargetException (); // Must be a PropertyVetoException if it's a checked exception print gxtOcetoException () EX.GETTARGETEXCEPTION () EX.GETTARGETEXCEPTION (); thring PEX;}}} Although the use of reflection code is complicated than normal code, but he only needs to test it, it can deal with possible modifications. This will be said to be a framework code! Reflection is the core API of Java, so you must master it.

Reflection and factory modes (Reflection and the factory design pattern)

public Object getObject (String classname, Class requiredType) throws FactoryException {try {Class clazz = Class.forName (classname); Object o = clazz.newInstance (); (! requiredType.isAssignableFrom (clazz)) if throw new FactoryException ( "Class "' ClassName "' Not of Required Type " RequiredType); // Configure the Object ... Return O; Catch (ClassNotFoundException EX) {

throw new FactoryException ( "Could not load class" ' classname ""', ex);} catch (IllegalAccessException ex) {throw new FactoryException ( "Could not construct class" ' classname "': is the no Arg Constructor PUBLIC? ", EX); (InstantiationException EX) {Throw New FactoryException (" COULDN't Construct Class "' ClassName "': Does It Have a no arg constructor ", EX);}} Myinterface Mo = (MyInterface) Beanfactory.GetObject ("com.mycompany.mypackage.myimplement); when using reflection, usually cause us to determine if code can be properly executed, this is required to provide more Detailed error message to make it easy for future processing.

Dynamic Agent (Java 1.3 Dynamic Proxies)

Chapter 11 (Infrastructure and Application Implement) will be described in detail, and it is a thing related to AOP (Aspect Oriented Programming).

Ten, use JavaBean to achieve flexibility (Using JavaBeans to Achieve flexibility)

Using JavaBeans allows objects to use the configuration outside the code. But it is best to use these classes below:

PropertyEditor PropertyChangeListener VetoableChangeListener Introspector

11. Avoid a proLiferation of singletons by using an application deteriotons by Using an Application REGITONS BY Using An Application Registry

Traditional single-case models have a lot of disadvantages, such as single case classes will be hardcoded in the code, single-case classes must be formulated, complex programs may require a lot of singletons, single-size classes do not support interfaces, single-size categories cannot Inherited, it cannot be updated in time. All these are greatly limited to the use of single examples.

However, the program context can solve these problems well, first it can be a normal Java class, which avoids all the above problems. As long as it is initialized when the program is initialized, then it is then used directly in the other places of the program. Even can be configured directly into JNDI.

I feel that the biggest advantage is that his dynamic configuration, this is much better than the hard writing of him in the code.

Twelve, refactoring

Reconstruction should not be limited to the reconstruction of code, error messages, logs, and documents should be reconstructed objects.

转载请注明原文地址:https://www.9cbs.com/read-132897.html

New Post(0)