The foundation is the top priority ~ At this time, we should use the generic method.

Source: Internet
Author: User

The foundation is the top priority ~ At this time, we should use the generic method.

Back to directory

Generic method: it is an abstract concept that abstracts batch operations that have common characteristics. generic types are used to represent this method. Methods of these types share the same logic, the only difference is that their type, that is, the type is a variable in the generic method, which is expressed in the lung!

During Development today, I encountered this problem and finally reconstructed my code. After the reconstruction, I used the generic method and felt that the code was much more beautiful.

Before using the generic Method
/// <Summary> /// update the relationship between the instructor and the student /// </summary> /// <param name = "list"> list of links to be inserted </ param> // <param name = "isAll"> whether it is all, if all, you do not need to insert a </param> // <param name = "teacherId"> current instructor ID </param> // <param name = "type"> type to the relational table: 0 video, 1 job, 3 Documents </param> public void AddUser_Source_R (List <User_Source_R> list, bool isAll, int teacherId, int objId, int objType) {switch (objType) {case 0: var respository1 = LoadRepository <Classroom_Info> (); var entity1 = LoadRepository <Classroom_Info> (). find (objId); if (isAll) {entity1.AccessStatus = 0; respository1.Update (entity1);} else {entity1.AccessStatus = 1; entity (entity1); LoadRepository <User_Source_R> (). insert (list);} break; case 1: var respository2 = LoadRepository <Courseware_Info> (); var entity2 = LoadRepository <Courseware_Info> (). find (objId); if (isAll) {entity2.AccessStatus = 0; respository2.Update (entity2);} else {entity2.AccessStatus = 1; entity (entity2); LoadRepository <User_Source_R> (). insert (list);} break; case 2: var respository3 = LoadRepository <Task_Info> (); var entity3 = LoadRepository <Task_Info> (). find (objId); if (isAll) {entity3.AccessStatus = 0; respository3.Update (entity3);} else {entity3.AccessStatus = 1; entity (entity3); LoadRepository <User_Source_R> (). insert (list);} break; case 3: var respository4 = LoadRepository <Substance_Info> (); var entity4 = LoadRepository <Substance_Info> (). find (objId); if (isAll) {entity4.AccessStatus = 0; respository4.Update (entity4);} else {entity4.AccessStatus = 1; entity (entity4); LoadRepository <User_Source_R> (). insert (list) ;}break; default: throw new ArgumentException ();}}
After using the generic method
/// <Summary> /// update the relationship between the instructor and the student /// </summary> /// <param name = "list"> list of links to be inserted </ param> // <param name = "isAll"> whether it is all, if all, you do not need to insert </param> /// <param name = "teacherId"> current instructor ID </param> /// <param name = "type"> resource Type 0 course, 1 video, 2 job, 3 Documentation </param> public void AddUser_Source_R (List <User_Source_R> list, bool isAll, int objId, int objType) {switch (objType) {case 0: updateSource_R <Classroom_Info> (list, isAll, objId); break; case 1: UpdateSource_R <Courseware_Info> (list, isAll, objId); break; case 2: updateSource_R <Task_Info> (list, isAll, objId); break; case 3: UpdateSource_R <Substance_Info> (list, isAll, objId); break; default: throw new ArgumentException () ;}/// <summary> /// generic method, only different types of things: // </summary> /// <typeparam name = "TEntity"> </typeparam> /// <param name = "list"> </ param> /// <param name = "isAll"> </param> // <param name = "teacherId"> </param> // <param name =" objId "> </param> // <param name =" objType "> </param> void UpdateSource_R <TEntity> (List <User_Source_R> list, bool isAll, int objId) where TEntity: class, IAccess {var entity = LoadRepository <TEntity> (). find (objId); if (isAll) {entity. accessStatus = 0; LoadRepository <TEntity> (). update (entity);} else {entity. accessStatus = 1; LoadRepository <TEntity> (). update (entity); LoadRepository <User_Source_R> (). insert (list );}}

We can see that generic methods abstract unchanged logic together, which facilitates code extension and maintenance. This is the object-oriented code!

Back to directory


[Basic Java syntax] How does one specify its generics when using static methods? Thank you very much.

For example:
Public void f (int I, char ch, String s ){}
This method has three parameters: int type I, char type ch, and String type s. The types of these three parameters have been specified. If the actual parameter type is different from the corresponding parameter type, the compiler will see an error.
How can we set the parameter type as needed? In this case, you can use the generic method. For example:
Public <A, B, C> void f (A a A, B B, C c ){}
This is a so-called generic method. When a parameter is passed to the method, the compiler will automatically infer the parameter type, for example:
F (1, "hello", 123.123 );
The first parameter is of the Integer type, the second is of the String type, and the third is of the Double type (the automatic packaging mechanism automatically wraps the basic type into the corresponding packaging class ).
The feature of the generic method is that there is a pair of angle brackets before the method. The angle brackets contain type parameters, that is, the type is a variable, which must be inferred from the actual parameters.
The method in Java is to obtain the generic capability in this way, and there are other methods. However, the static method is special. To make the static method have the ability to reflect, you must use the above method.
Hope to solve your problem.

Please give me a detailed introduction to the benefits of using generics in JAVA. Can I create objects without using generics?

1. generics are very useful. If they can be used with reflection, the amount of code used by common enterprise applications can be greatly reduced.
2. type inference languages such as python are more suitable for this template abstraction than java.

For example, most of the programs in an enterprise program are managed by entity information and only a very small part of transactions involved in liquidation.
For all real-object management functions, such as adding, deleting, modifying, viewing, and searching
I have used several frameworks. The classic combination method is webwork + spring + hibernate. The analysis is as follows:

Hibernate O/R Mapping has nothing to do with. You need to write a ing Class for each object management. Generally, it is similar to the number of objects. Sometimes, to avoid Association, multiple views will be mapped to each other. but, this can be generated using a tool written by hibernate itself, maintain a java class file, and get the meta description in it.
Or you can write a program to generate it yourself (for a given data source, to output a java-class file, and an hbm. xml file). You only need to maintain the SQL statement. I usually do this.

1. No generic type, no reflection
The spring layer needs to write five services (assuming that an object corresponds to a service) to implement read entities, add entities, delete entities, and search for object lists based on conditions.

Write 5 different actions for entity classes, and then implement the verification, add, modify, delete, and list functions in the Action. The same is true for each class.

There is not much refactoring to reflect, but the benefits are not obvious. There are very few public code that can be proposed.

2. Use reflection instead of generics
On the basis of the first service, you can reconstruct and extract a public service, and kill the public code scattered in the five services. one more public class is operated according to the object class parameters, but the number of classes is increased by one.

You can also propose a baseaction for the same Action.

Reconstruction removes part of the Code. The Code for each service still has repeated code, but this can also be combined into a service through reflection, but the user must call it through reflection.

For actions that need to be configured, it is difficult to eliminate them unless webwork supports injection of types.
If webwork spring supports object type injection, it can end up writing only one set of logic and the code is not repeated. Due to limited energy, I have not studied the inteceptor mechanism of spring AOP and webwork in depth.

3. Generic and reflection
Introduce generics on the basis of 1, write a generic service, and write a generic webwork action. I have never studied how to configure generic objects in xwork. If configuration is supported, you only need to write an action. If not, you need to write a webwork action for each object class.

The same is true for the page.

However, java uses a wildcard, not to mention the poor support for many things. In terms of writing, it is still a lot consistent with C ++ template <>, this allows beginners to vomit blood and become a good player. compared with the type inference mechanism of a dynamic type security language such as python, java generics still have a long way to go. However, when static languages come up with type inference, the benefit of checking the compilation type is gone, so java is never possible ~~~
Through the above considerations, I think python is more suitable for web management programs. For many entity management programs, you can write a service, only O? Rmapping cannot be saved. I don't know if python has a reflection similar to java. If so, ...... the rest of the text>

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.