隨着大數據、公共平臺等互聯網技術的日益成熟,API接口的重要性日益凸顯,從公司的角度來看,API能夠算做是公司一筆巨大的資產,公共API能夠捕獲用戶、爲公司作出許多貢獻。對於我的來講,只要你編程,你就是一個API設計者,由於好的代碼便是模塊——每一個模塊即是一個API,而好的模塊會被屢次使用。此外,編寫API還有利於開發者提升代碼質量,提升自身的編碼水平。java
優秀API所具有的特徵:程序員
瞭解了一款優秀API所具有的特徵後,一塊兒再來看看如何設計優秀的API,有哪些流程和規則可循,開發者在設計時須要注意哪些事項。編程
徵集需求數組
在開始以前,你可能會收到一些解決方案,它們不必定會比現有的方案好,而你的任務是以用例的形式提取真實需求,並制定真正合適的解決方案,這樣構建出來的東西就會更加有價值。app
從簡短的說明開始dom
這時,編寫簡短的說明最爲合適,編寫時須要考慮的因素有:ide
儘早編寫API函數
編寫SPI尤其重要性能
維護切實可行的指望測試
每一個API接口應該只專一一件事,並作好:若是它很難命名,那麼這或許是個很差的徵兆,好的名稱能夠驅動開發、而且只需拆分與合併模塊便可
if (car.speed() > 2 * SPEED_LIMIT) generateAlert("Watch out for cops!");
重視文檔
開發API時要意識到文檔的重要性。組件重用不是紙上談兵的東西,既須要好的設計,也須要優秀的文檔,這兩者缺一不可,即便咱們看到了良好的設計而未見文檔,那麼組件重用也是不妥的。
文檔應包含每一個類、接口、方法、構造函數、參數和異常,此外,還要當心對待文檔的狀態空間。
API設計決策對性能的影響
API與平臺和平共處
最小化可變性
子類只存在有意義的地方
用於繼承的設計和文檔或者直接禁止繼承(Design and Document for Inheritance or Else Prohibit it)
模塊能作到的,客戶端就不要作減小模板代碼的使用:
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 an 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! } }
遵照最小驚訝原則
用戶API只需根據需求來設計便可,沒必要讓客戶感到驚訝,當心弄巧成拙:
public class Thread implements Runnable { // Tests whether current thread has been interrupted. // Clears the interrupted status of current thread. public static boolean interrupted(); }
故障快速報告應儘快生成
// 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 that are not strings public void save(OutputStream out, String comments); }
以String形式對全部可用數據提供編程式訪問
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();}
方法重載要細心
public TreeSet(Collection c); // Ignores orderpublic TreeSet(SortedSet s); // Respects order
使用合適的參數和返回類型
#include char *strcpy (char *dest, char *src); void bcopy (void *src, void *dst, int n);
ava.util.Collections – first parameter always collection to be modifiedor queriedjava.util.concurrent – time always specified as long delay, TimeUnitunit
避免使用長參數列表
最好避免這種狀況出現:
// Eleven parameters including four consecutive intsHWND CreateWindow(LPCTSTR lpClassName, LPCTSTR lpWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam);
返回值勿需進行異常處理
好比,返回零長度字符串或者空集合
package java.awt.image; public interface BufferedImageOp { // Returns the rendering hints for this operation, // or null if no hints have been set. public RenderingHints getRenderingHints(); }
拋出異常來講明異常情況;不要強迫客戶端使用異常來控制流。
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)
支持Unchecked Exceptions
try { Foo f = (Foo) super.clone(); ....} catch (CloneNotSupportedException e) { // This can't happen, since we’re Cloneable throw new AssertionError();}
異常中應該包含捕獲錯誤的(Failure-Capture)信息
在Vector中進行Sublist操做
public class Vector { public int indexOf(Object elem, int index); public int lastIndexOf(Object elem, int index); ...}
分析:
重構Sublist操做
public interface List { List subList(int fromIndex, int toIndex); ...}
分析:
線程局部變量
// 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); }
線程局部變量重構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); }
能夠運行,可是須要使用模板代碼。
static ThreadLocal.Key serialNumberKey = ThreadLocal.getKey(); ThreadLocal.set(serialNumberKey, nextSerialNumber()); System.out.println(ThreadLocal.get(serialNumberKey));
線程局部變量重構2
public class ThreadLocal { public ThreadLocal() { } public void set(Object value); public Object get(); }
從API和客戶端代碼中刪除了無用代碼。
static ThreadLocal serialNumber = new ThreadLocal(); serialNumber.set(nextSerialNumber()); System.out.println(serialNumber.get());
總結
API設計是一件很是高端大氣上檔次的工藝,對程序員、終端用戶和公司都會有所提高。不要盲目地去遵照文中所說起的規則、說明等,但也不要去侵犯他們,API設計不是件簡單的工藝,也不是一種能夠孤立行動的活。固然完美永遠沒法實現,但咱們要努力去追求完美。
寫在最後:歡迎留言討論,加關注,持續更新!!!