Former Ali P8 architect discusses how to design an excellent API

Source: Internet
Author: User

With the growing sophistication of Internet technologies such as big data and public platforms, API interfaces are becoming increasingly important, and from a corporate point of view, APIs can be counted as a huge asset for the company, and public APIs can capture users and make many contributions to the company. For individuals, as long as you are programming, you are an API designer, because good code is a module-each module is an API, and good modules are used multiple times. In addition, writing an API also helps developers improve code quality and improve their coding level.

Features of the excellent API:

    1. Simple and easy to learn;
    2. Easy to use, even without documentation;
    3. difficult to misuse;
    4. Easy to read, code easy to maintain;
    5. Strong enough to meet demand;
    6. Easy to expand;
    7. Suitable for users.
      Once you understand the features of a good API, take a look at how to design good APIs, what processes and rules to follow, and what developers need to be aware of when designing.
Considerations in the API design process

Solicit demand

Before you begin, you may receive solutions that are not necessarily better than the existing ones, and that your task is to extract real needs in the form of use cases and to develop a truly appropriate solution so that the things you build will be more valuable.

Start with a brief explanation

At this point, it is most appropriate to write a short explanation, and the factors to be considered when writing:

    • Flexibility is far more than completeness;
    • Jump out of the rules: listen to opinions and be ready;
    • Refining short is easy to modify;
    • After gaining trust, it is important to be programmed.

Write an API early

    • Save each implementation in case of loss;
    • Before you begin, make a list of some reasonable provisions to save the written instructions in case of loss;
    • Continue to write and enrich the API.

Writing SPI is especially important

    • Service Provider interface is the provider interface, plug-in services support a variety of implementations, such as Java Cryptography Extension (JCE);
    • Write multiple plugins before publishing;
    • "Three-Times Principle" ("the Rule of Threes"): Refers to "abstraction" when a function appears for the third time.

Maintenance of realistic expectations

    • Most API designs are too constrained;
    • Anticipate the mistakes that might be made, and write the APIs with a developmental mindset.

You can click to join the group: "Java Advanced Architecture Advance Group": 8541,80697 inside the Java senior Daniel Live explanation of the knowledge point is the high-end route, (if you want to change jobs but the technology is not enough or the work encountered a bottleneck, I have a free live Java program, Talk about the high-end knowledge point of the poor wrong into yo, as long as you have 1-5 years of development experience can add group to find me to the classroom link, note: Is free of development experience mistakenly into OH)

API Design Principles

Each API interface should focus on only one thing and do it well: if it's hard to name, then this may be a bad sign, a good name can drive development, and just split and merge modules

    • The API should be as light as possible: to meet the needs, to have doubts about the place can be temporarily unused (functions, classes, methods, parameters, etc., you can not add, but do not delete), the concept of something more important than volume, looking for a good dynamic volume ratio;
    • Implementation does not affect the API: focus on implementation details (do not confuse the user, do not arbitrarily change the implementation), aware of specific implementation details (do not have ultra vires method behavior, such as do not make hash functions, all tuning parameters are suspicious);
    • Do not let implementation details "leak" to APIs (such as On-disk and on-the-wire formats, etc.);
    • Minimized accessibility: Designers should try to make classes and members private, and public classes should not have public fields (including exception instances) to maximize information hiding, allowing modules to be used, understood, built, tested and independently debugged;
    • Naming problems: Should be known, avoid vague abbreviations, naming the same thing should have a consistent prefix (throughout the Platform API), symmetry, code should be easy to read. As shown below:

if (Car.speed () > 2 * speed_limit)
Generatealert ("Watch Out for cops!");

Attach importance to Documents

Be aware of the importance of documentation when developing APIs. Component reuse is not an armchair thing, both the need for good design, but also the need for excellent documentation, which is indispensable, even if we see a good design without documentation, then component reuse is inappropriate.

The document should contain each class, interface, method, constructor, parameter, and exception, and also be careful about the state space of the document.

The impact of API design decisions on performance

    • The impact of API design decisions on performance is real and permanent;
    • Bad decisions can limit performance (variable type, constructor substitution for static factory, implementation type substitution interface);
    • Do not package APIs to improve performance (potential performance issues may be fixed, but saved for a moment, can not save a lifetime);
    • Good design is usually consistent with good performance.

API and Platform Peaceful coexistence

    • Develop good habits: adhere to standard naming conventions, avoid stale parameters and return types, core APIs, and language impersonation patterns;
    • Take advantage of the API's friendly features: generics, variable parameters, enumerations, default parameters;
    • Understand and avoid API traps and bugs: finalizers, public static final array.
Design of classes in API

Minimized variability

    • It is better not to change classes casually unless there is a very reasonable reason;
    • If it is a mutable class, it is best to keep a small state space, well-defined structure, timely to call the method.

Subclasses have only meaningful places.

    • Subclasses are replaceable (Liskov);
    • Public classes should not inherit from other public classes.

Design and documentation for inheritance or direct prohibition of inheritance (design and document for inheritance or Else prohibit it)

    • Inheritance Destruction Encapsulation
    • If you allow subclasses and documents to be used for your own use, consider how you call each other's methods
    • Conservative strategy: Set all classes to final
Method Design in the API

Module can do, the client will not do to reduce the use of template code:

Import Org.w3c.dom. ;
Import java.io.
;
Import Javax.xml.transform. ;
Import Javax.xml.transform.dom.
;
Import javax.xml.transform.stream.*;
DOM code to write the XML document to a specified output stream.
private static final void Writedoc (Document doc, outputstream out) throws ioexception{
try {
Transformer t = transformerfactory.newinstance (). Newtransformer ();
T.setoutputproperty (Outputkeys.doctype_system, Doc.getdoctype (). Getsystemid ());
T.transform (New Domsource (DOC), New Streamresult (out));
} catch (Transformerexception e) {
throw new Assertionerror (e); Can ' t happen!
}
}

Observe the principle of least astonishment

The user API needs to be designed just as needed, without the customer being surprised and self-defeating:

public class Thread implements Runnable {
Tests whether current thread has been interrupted.
Clears the interrupted status of current thread.
public static Boolean interrupted ();
}

Fast fault reporting should be generated as soon as possible

    • Compile-time preferably static type, generic;
    • The method should contain the error auto-commit mechanism.

A Properties Instance maps strings to strings
public class Properties extends Hashtable {
public object put (object key, object value);
Throws ClassCastException If this properties
Contains any keys or values is not strings
public void Save (OutputStream out, String comments);
}

Provides programmatic access to all available data in string form

public class Throwable {
public void Printstacktrace (PrintStream s);
Public stacktraceelement[] Getstacktrace (); Since 1.4
}
Public final class Stacktraceelement {
Public String GetFileName ();
public int getlinenumber ();
Public String getclassname ();
Public String getmethodname ();
public boolean isnativemethod ();
}

Method overloading should be carefully

    • Avoid ambiguous overloads, such as multiple overloads for the same physical
    • Even if you can tell, it's better not to do it, it's better to have a different name
    • If you do not want to define this overload, the same parameters ensure the same behavior

Public TreeSet (Collection c); Ignores order
Public TreeSet (SortedSet s); Respects order

Use the appropriate parameters and return type

    • Support for interface type input through classes
    • Use the most specific input parameter types as much as you can
    • If a better type exists, do not use the string type
    • Do not use floating-point types to modify currency values
    • Use double (64-bit) instead of float (32-bit)
      It is particularly important to have the same parameter order on the method, especially if the parameter type is the same.

#include
Char strcpy (char dest, char src);
void bcopy (void
src, void *dst, int n);

-

Ava.util.collections–first parameter always collection-be modified
or queried
Java.util.concurrent–time always specified as long delay, timeunit
Unit

Avoid using long parameter lists

    • Three or three parameters are the perfect one.
    • Long parameter lists are harmful, programmers are prone to errors, and programs do not perform well when compiling and running
    • Two ways to shorten parameters: Break up method, create parameter helper class

It is best to avoid this situation:

Eleven parameters including four consecutive ints
HWND CreateWindow (LPCTSTR lpclassname, LPCTSTR lpwindowname,
DWORD dwstyle, int x, int y, int nwidth, int nheight,
HWND hwndparent, HMENU HMENU, hinstance hinstance, lpvoid lpparam);

Return value do not need exception handling

For example, return a 0-length string or an empty collection

Package java.awt.image;
Public interface Bufferedimageop {
Returns The rendering hints for this operation,
or null if no hints has been set.
Public renderinghints getrenderinghints ();
}

Exception design in the API

Throws an exception to illustrate the exception condition; Do not force clients to use exceptions to control the flow.

Private byte[] A = new byte[buf_size];
void Processbuffer (Bytebuffer buf) {
try {
while (true) {
Buf.get (a);
Processbytes (TMP, buf_size);
}
} catch (Bufferunderflowexception e) {
int remaining = buf.remaining ();
Buf.get (A, 0, remaining);
Processbytes (Bufarray, remaining);
}
}

Conversely, don ' t fail silently

Threadgroup.enumerate (thread[] list)

Support Unchecked Exceptions

    • checked--client will definitely do some recovery measures
    • unchecked--Programming Error
    • Excessive use of checked exceptions will result in some template code

try {
Foo f = (foo) super.clone ();
....
} catch (Clonenotsupportedexception e) {
This can ' t happen, since we ' re cloneable
throw new Assertionerror ();
}

The exception should contain the (failure-capture) information that catches the error

    • Allow diagnostics and repair or recovery
    • For unchecked exceptions, there is an exception message.
    • For checked exceptions, provide accessors
Refactoring API Design

Perform sublist operations in vectors

public class Vector {
public int indexOf (Object elem, int index);
public int lastIndexOf (Object elem, int index);
...
}

Analysis :

    • Not strong on the search
    • No documentation is difficult to use

Refactoring sublist Operations

Public interface List {
List sublist (int fromIndex, int toindex);
...
}

Analysis :

    • Very powerful--all operations supported
    • Use interfaces to reduce concept weights: Higher power-to-weight (power-to-weight) ratio
    • No documentation and easy to use

Thread Local Variables

Broken-inappropriate use of String as capability.
Keys constitute a shared global namespace.
public class ThreadLocal {
Private ThreadLocal () {}//Non-instantiable
Sets current thread ' s value for named variable.
public static void Set (String key, Object value);
Returns Current thread ' s value for named variable.
public static Object get (String key);
}

Thread local variable refactoring 1

public class ThreadLocal {
Private ThreadLocal () {}//Noninstantiable
public static class Key {key () {}}
Generates a unique, unforgeable key
public static key GetKey () {return new key ();}
public static void Set (Key key, Object value);
public static Object get (key key);
}

Can run, but requires the use of template code.

static Threadlocal.key Serialnumberkey = Threadlocal.getkey ();
Threadlocal.set (Serialnumberkey, Nextserialnumber ());
System.out.println (Threadlocal.get (Serialnumberkey));

Thread local variable refactoring 2

public class ThreadLocal {
Public ThreadLocal () {}
public void Set (Object value);
Public Object get ();
}

unwanted code was removed from the API and client code .

static ThreadLocal serialnumber = new ThreadLocal ();
Serialnumber.set (Nextserialnumber ());
System.out.println (Serialnumber.get ());

Summarize

API design is a very high-end atmosphere on the level of technology, programmers, end users and companies will be improved. Do not blindly adhere to the text mentioned in the rules, instructions, etc., but also do not violate them, API design is not a simple process, is not a kind of work can be isolated action. Of course, perfection can never be achieved, but we must strive for perfection.

Write at the end: Welcome message discussion, add attention, continuous UPDATE!!!

Former Ali P8 architect discusses how to design an excellent API

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.