ym--Optimize your Java code (new)

Source: Internet
Author: User

Reprint Please indicate this article from CYM's blog (http://blog.csdn.net/cym492224103 ), thank you for your support!


1. Object-oriented 3 features.


2. 6 Principles for object-oriented development .

1. Single Responsibility Principle

There should be and only one cause for class changes.

2. The Richter replacement principle

Only where the parent class can appear, its subclasses should be able to appear.

That is, after the child class is replaced with the parent class. Ensure that the program is still executed.

3. Dependency Inversion principle

interface-oriented programming.

4. Interface Isolation principle

Interface refinement, that is, the interface of the method to be as small as possible.

5. Dimitri Law

Also known as the least-knowledge principle, which is defined as: An object should have a minimal understanding of other objects. That is, don't have too many other classes in a class.

6. Opening and closing principle

The core of the open and closed principle is: openness to expansion. Turn off the changes.


3. cyclomatic complexity (cyclomatic complexity,CC)

cyclomatic Complexity (hereinafter referred to AS CC ) is a measure that indicates the number of paths that are running in a method.

CC from 1 Start with each of the more conditional statements ( if . Else. switch...case. while, for)CC value plus 1;

a method of CC the larger the value, the more complex the method is.

CC The value indicates the test sample that is required to completely test a method.


4. Measurement of cyclomatic complexity

cc∈[0,5] : Good code quality;

cc∈[6,20] : There may be code that needs to be split, so try to refactor as much as possible.

cc∈[21,∞) : Refactoring is required. Suppose your code CC often reaches this level, please again to tidy up the idea of Coding;

please ensure as much as possible cc<10 .


5. Calculation of cyclomatic complexity

V (G) = E–n + 2;

V (G) : Cyclomatic Complexity

e : The number of sides in the program flowchart.

N : The number of nodes in the program flowchart;


6. Calculation of cyclomatic complexity

Code:

void Test () {     int cnt = 0;     for (int I = 0;i < 100;i++) {         cnt++;     }     if (cnt >) {          System.out.println ();     }     ...}

Corresponding Flowchart:



7. Reduce cyclomatic complexity

Method One

Refinement function, extraction method:

Before optimization:

Int  Getappkey (string user, String package) {    string userId = "";    String packageId = "";    System.out.println ("=============");    if (null = = user) {        System.out.println ("User ID is null.");    } else {        userId = "User_" + id1;        SYSTEM.OUT.PRINTLN ("userid is" + userid);    if (null = = package) {        System.out.println ("PackageId ID is null.");    } else {        packageId = "Package_" + id2;
   system.out.println ("PackageId is" + packageId);    }            System.out.println ("=============");    Return userId. Hashcode ()  ^ PackageId. hashcode ();}

After optimization:

Int  Getappkey (string user, String package) {    string userId = Geid ("User_", user);    String packageId = getId ("Package_", package);        Printid (UserId,  packageId);    Return userId. Hashcode ()  ^ PackageId. hashcode ();} String GetId (String head, string key) {    string id = "";    if (key = null) {        id=  head + user;    }     return ID;} String Getprintinfo (string name, String value) {    string info = name + "is" + value;    if ("". Equals (value)) {        info = name + "is null.";    }     return ID;} void Printid (String  userId, string packageId)  {    System.out.println ("=============");    System.out.println (Getprintinfo ("userid", UserID));    System.out.println (Getprintinfo ("PackageId", PackageId));    System.out.println ("=============");}


Method Two

Replace conditional with loop:

Before optimization:

String GetName (String id) {        string name = null;        if ("0000". Equals (ID)) {            name = "Xiao Wu";        }        if ("0001". Equals (ID)) {            name = "Xiao Wang";        }        if ("0002". Equals (ID)) {            name = "Lao Zhao";        }        if ("0003". Equals (ID)) {            name = "Xiao Li";        }        if ("0004". Equals (ID)) {            name = "Xiao Liu";        }        if ("0005". Equals (ID)) {            name = "Xiao Zhang";        }        return name;    

after optimization:

private static string GetName (String id) {        string name = null;        When the number of elements is large, replace the array with a map. Array objects can be passed in as parameters.

string[] IDArray = new string[]{"0000", "0001", "0002", "0003", "0004", "0005"}; string[] NameArray = new string[]{"Xiao Wu", "Xiao Wang", "Lao Zhao", "Xiao Li", "Xiao Liu", "Xiao Zhang"}; for (int i = 0;i < idarray.length;i++) { Object Peopleid = idarray[i]; if (Peopleid.equals (ID)) { name = Namearray[i]; break; } } return name;


Method Three

To reduce a conditional branch with an initial value:

Before optimization:

String GetCode (String id) {        string code = "";                if (NULL = = ID) {            code = "0000";        } else {            code = "XX" + ID;        }        return code;    }

After optimization:

String GetCode (String id) {                //initialization is set to the default value of        string code = "0000";                if (id! = NULL) {            code = "XX" + ID;        }        return code;    }

method Four

The function replaces the number of parameters:

before optimization:

String GetValue (string param) {                string value = null;                if ("Name". Equals (param)) {            value = mname;        } else if ("hight". Equals (param)) {            value = mhight;        } else if (" X ". Equals (param)) {            value = MX;        } else if (" Y ". Equals (param)) {            value = MY;        }                return value;    }

After optimization:

String GetName () {        return mname;    }        private static String Gethight () {        return mhight;    }        private static String GetX () {        return mX;    }        private static String GetY () {        return mY;    }


Method Five

To respond to changes with a number of parameters:

Before optimization:

private static int getwidth (int val) {                int width = 0;                if (val = =) {            width + = ((val << 2) ^ 0x10) *        GB;} else if (val = =) {            width + = (val << 2) ^ 0X1A) *;        }                return width;    }

After optimization:

private static int getwidth (int val) {                int width = ten;                width + = Getdeta (val, 0x10);        width + = Getdeta (val, 0x1a);                return width;    }        private static int Getdeta (int val, int trim) {        int deta = 0;        if (val = = range) {            Deta = ((val << 2) ^ trim) *;        return deta;    }

ym--Optimize your Java code (new)

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.