Class and long method

xiaoxiao2021-03-06  104

The big class and long method were a few times. I said that the code repeated was a hardenal injury of the OO system. Everyone will except. But what is the reason why the code is repeated? Code repeat What is the meaning of the system? How can I eliminate duplicate code? The problem like this is needed to discuss in-depth. Otherwise, even if we can invisibility to identify this odor, I don't know how to start, how to start, what kind The degree stops further tempering. Class and long method is an extremely important reason for generating code repetition, and also the inevitable consequences of repeating code. I tried to explore some of these temperament in this article. One reposibility? One reposibility? In the object-oriented programming language, the most important reuse method is the function library due to the lack of the OO language, the most important reuse method is the library. In order to facilitate customer code, the basic components of these function libraries - functions - usually need to process It belongs to a variety of different variants of the same type. This way, customer code can use different parameters to call these functions to achieve different functions, and when implementing these function libraries, you must choose specific behavior according to different parameter values. So doing The result is that these functions tend to have "powerful functions", and it makes these function libraries to be reused by a wide variety of different applications. Because of this, this is even the high realm of writing programs However, these "powerful features" is not free, it requires us to pay a higher price. When you need to modify this function that can handle a variety of different situations, such as one of them When the situation is handled, the terrible thing happens. You have to take this big quagmire full of switch, if, flag, and exit, which code is used to deal with this situation you are targeting, which It is handled in other cases, or some code is related to many cases. Even if you can find such a separate code block, the modification of these code blocks can affect the situation you don't care about. When you think it is done Modify, you tested the code you intend to modify, you think that all things are good. But it is very likely that you have made a mistake in the original correct situation. Take another step, even if your code is right, if that case modification needs You increase special parameters, then all code degrees that reference the function need to be re-modified, compile, tested, all these behaviors, may quickly expand to the entire system in the cascaded way, and finally, all the code needs to be recompiled. Test. The modifications, maintenance and test costs caused by this multi-duty, proven to be software expensive and even failed culprits. Bertrend Meyer presents the most object-oriented system in the famous "Object-Oriented Software Construction" book Widely known open-closed principle. He said: Modules Should Be Both Open and Closed. Meyer uses module to refer to system elements, methods, packages, and so on. He pointed out that a module, once delivered, it must be closed, that is, cannot be modified. At the same time, a module must also be Open, it can be expanded. The two seem to contradict, but it is indeed the essential characteristics of OO method incremental development. As mentioned above, a class or method having a lot of responsibility is inevitably difficult to close, it violates the second part of the OCP principle. How to oao and why? Recognizing the limitations of process-type ideas, we need to take a more step forward. I have talked in "Code Repeat", and Once and ONLY ONCE (OAOO) is the ultimate goal of exclusions.

But doing this is not as simple as we think, Ralph Johnson said: i've read this page dozens of time, ket. Reading it again Today Made my heart sink. It is hard to explain. Once and only overce is a profound concept, but difficult to apply. I've spent my entire professional life (25 years) learning how to apply it to programs. This page makes it seem so sterile, so dead. Since the last time I read it, it was rewritten to make OnceAndOnlyOnce seem like a simple rule to apply, instead of a prime principle. Once and Only Once is NOT easy! and it was wrong to refactor this page so that all hints of tension and disagreement are removed from it. categories It is often difficult to understand, maintain and reuse. To reach the realm of OAOO, you need to continuously eliminate repetition, exclude repetition, and the system will eventually have many duties clear small block code blocks, because good systems require: l Alternative objects. A good programming style produces an alternative object. In an ideal system, each time the user wants to complete a different thing, the developer should easily implement an object (often inherited), then insert it directly into the existing system. As the OCP tells us, you change the system behavior with new objects with new objects, without modifying the original code. To achieve such a goal, you have to have a small but also a clear class and method. L Adapt to different scenes. One of the important features of a good system is that their objects can be easily ported to a different context. When you move your object to a different context with your original development, you can fail. So, you separate the same abstraction and different abstractions. It turns out that the atom's duty is divided into several smaller responsibilities. Every time you transplanted into a different environment, your code abstraction level is smaller, but the adaptability Strong, so that you can reuse, the more you can adapt to the scenario that is now unpredictable. L Isolate different change rates: different states, even in the same class, there will be different rate of change. Object-oriented reusability is obtained by quarantine relative changes and relatively fast portions. This is usually the meaning of "abstract" we often say. How To Achieve Understanding? The ability to adapt to change is very important, and it is also important to have the understandability of the program. How do you read your own code, even if you write a few months or more years? How do you understand the code of others, and exchange ideas with others? How do you record your design and ensure that they don't overcome with the program's Evolution? The readers of computer programs are not just chips, but also a lot of programmers as you, including yourself. One of the most annoying programs is all about all API documents, and finally discovered or has no help to systematically understand and use.

Programmers also hate some of the large number of comments, because the modification of the program code requires simultaneous modification of the comment, and the result is that comments are often inconsistent with your programs, and it is better than not watching. The more annoying thing is to write a lot of detailed design documents, but the results discover that these design documents to the last and program implementations are very different. All of these require the program that itself has a function of document, just like a literary work, although countless annotation, analysis, reviews. But understanding it the most important basis or itself. Any other things will only help you understand some, even introduce you to astray. And understanding is the origin of everything, there is no understanding, there is no everything. To make your program to be faithful to record your intentions and design, you must make the classes and methods, especially methods, and every way, using an intent Revealing Name (revealing the name of the intent), that is, what is it doing? Instead of how it completes one thing. When the long method passes such a resolution, it will finally become a natural English, of which each phrase (object name method name plus parameter) tells you what to do on what objects do. At this time, the comments have become redundant, the code is design. I often use JREFActory's statistical tools to measure their code. In general, the entire system averages the number of lines of each method 3-7 lines, and the number of parameters per method is about 1-2. Of course, this is not absolute, some of the long code only contains an intent, such as a large number of properties of the object (not using O / R mapping) from the database field, then the length of these code may greatly increase. Is the method of measuring too long is that it completes one thing, you can use a verb phrase or assert that it takes it. There is also a lot of refactoring in the Refactoring Martin Fowler "Refactoring" in the big class and long method. The most important thing is Extract Method (110). But I think Kent Beck's composed method is more intended. Using Extract Method, you can usually involve temporary variables, you can use Replace Temp with Query. Method is too long, you can use Introduce Parameter Object and Preserve Whole Object. Temporary variables are really too many Kent Beck's Method Object. Extract conditions and cycles are also very reused, usually you might use Decompose Conditional to handle conditional expressions. Classical processing includes Extract Class, Extract Subclass, and Extract Interface, and more.

The original code below is from Data Structure in Java for the PrinciNe A. Bailey, I will show how to perform Refactoring, let it meet my own aesthetic, good taste, good performance: [code ] class Vector ... protected Object elementData []; protected int elementCount; protected int capacityIncrement; public Vector (int initialCapacity, int capacityIncrement) {elementData = new Object [initialCapacity]; elementCount = 0; this.capacityIncrement = capacitIncrement;} [/ CODE ] This is a vector class, and the vector is implemented inside an object array. When accommodating, an array size is required.

Duane A. Bailey's addElement achieve the following: [CODE] public void addElement (Object obj) {ensureCapacity (elementCount 1); elementData [elementCount] = obj; elementCount ;} [/ CODE] Here ensureCapacity is to ensure that the array large enough to contain Newly added elements can also be reused into insertelementat: [code] public void insertelementat (Object obj, int index) {INT i; ENSURECAPACITY (ElementCount 1); for (i = elementcount; i> index; i-- ) {ElementData [i] = ElementData [i-1];} ElementData [index] = Obj; ElementCount ;} [/ code] Can you directly understand it, I don't want, so, in the original article in the For loop Previous Note: // NB Must Copy from Right To Left To Avoid Destroying Data This code requires a comment reason is that the circular statement makes people don't know how to be cloud, in fact it has made two things, let us use extract method, and Give it a good name: [code] protected void moveeachtonext (int startex, int endindex) {for (int i = endindex 1; i> startData [i] = elementdata [i-1] }} public void insertElementAt (int index, Object anObject) {ensureCapacity (elementCount 1); moveEachToNext (index, elementCount-1); elementData [index] = obj; elementCount ;} [/ CODE] should I do not need any explanation.

The above refacotering give you a little feel, let us look at Duane A. Bailey original ensureCapacity: [CODE] public void ensureCapacity {int newLength = elementData.length (int minCapacity) {if (elementData.length

[CODE] protected boolean isLongEnough (int expectedCapacity) {return elementData.length> = expectedCapacity;} [/ CODE] look down: [CODE] int newLength = elementData.length; if (capacityIncrement == 0) {if (newLength = = 0) Newlength = 1; While (Newlength

} [/ Code] The problem here is to involve local variables in the original code, in the original code, Newlength is re-assigned, so we use it as a return value, the original code is now transferred: [ CODE] protected int getNewLength (int expectedCapacity) {int newLength = elementData.length; if (capacityIncrement == 0) {if (newLength == 0) newLength = 1; while (newLength

The final result of gradually evolving makes getNewlength becomes as follows (I save the specific steps, there is a detailed source code for my JavabLock, used to test block: [code] protected int getNewlength (int expectedcapacity) {if (ShouldDouboard () {Return Doubleit ();} else {return doincrement (ExpectedCapacity);}} [/ code] look down: [Code] Object newElementData [] = new object [newLength]; int i; for (i = 0; I

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

New Post(0)