---
title: "如何设计API？"
author: "cherami"
date: "2007-04-03T09:38:35Z"
tags: []
slug: "api"
draft: false
lastmod: "2007-04-03T09:38:35Z"
id: 67780
url: "https://cherami.iteye.com/blog/67780"
---

每个人设计API的思路可能都不一样，而我们公司的一些代码的API的设计很有意思，一个例子：  
    public AppGroupConfigValueObj get(UserSession \_userSession, AppGroupConfigValueObj invo) throws DataException  
    {  
        long start = System.currentTimeMillis();  
        try  
        {  
            Long id = (Long) invo.getId();  
            if (isDebug() )  
                SessionLogManager.getInstance().getLogger(this.getClass()).debug("get group" + id);  
            AppGroupConfig eb = this.appGroupHome().findByPrimaryKey(id);  
            if (isDebug() )  
                SessionLogManager.getInstance().getLogger( this.getClass() ).debug("Get( UserSession \_userSession, AppGroupConfigValueObj invo) elapsed time = "+ (System.currentTimeMillis()-start));  
            return get(eb, invo);  
        }  
        catch (Exception e)  
        {  
            throwException(e);  
        }  
        return null;  
    }

    private AppGroupConfigValueObj get(AppGroupConfig eb, AppGroupConfigValueObj invo)  
            throws Exception  
    {  
        AppGroupConfigValueObj vo = (AppGroupConfigValueObj) ServerUtil.getValueObj(eb);

        if (invo.getApps() != null)  
        {  
            Collection collection = eb.getApplications();  
            if (invo.getApps().getCount() == 0)  
                vo.setApps(new ValueObjList(collection.size()));  
            else  
            {  
                Iterator it = collection.iterator();  
                while (it.hasNext())  
                {  
                    AppConfig a = (AppConfig) it.next();  
                    vo.addApp((AppConfigValueObj) ServerUtil.getValueObj(a));  
                }  
            }  
        }  
        return vo;  
    }

解释一下，这个API的功能是这样的，主要参数AppGroupConfigValueObj 是一个Map结构的对象，另外包含一些父子关系，如果你需要的是一个轻量级的结果，那么传入的对象只需要设置ID就可以，典型的用法是这样的：  
get(cuSession, new AppGroupConfigValueObj(appGroupId))  
如果你需要一个重量级的结果，也就是需要它的一些子表的数据，那么就要设置子表的关系，并添加一个空的对象：  
                    AppGroupConfigValueObj appVo = new AppGroupConfigValueObj(appGroupId);  
                    appVo.addApp(new AppConfigValueObj());  
                    get(cuSession,appVo);  
还有第三种用法，就是你希望那些子表数据不填充，但是需要知道子表数据有几个，那么你的调用代码就是：  
                    AppGroupConfigValueObj appVo = new AppGroupConfigValueObj(appGroupId);  
                    appVo.setApps(new ValueObjList());  
                    get(cuSession,appVo);

我不知道这种做法源自何处，但是很明显是原来的某位高人，而比我资历更老的一些同事沿用了这个做法并且没有在文档中记录这种方法，当我苦苦寻找一个简单的get(cuSession, appGroupId)方法时没有任何结果，最后看其它部分的代码才知道了这个诀窍。![](/FCKeditor/editor/images/smiley/msn/confused_smile.gif)