API design guide [2]-class interface, apiinterface

Source: Internet
Author: User

API design guide [2]-class interface, apiinterface

* Return to the directory read other chapter: http://blog.csdn.net/cuibo1123/article/details/39894477


Class interface)

You can refer to the interface file of MGTileMenu.

We have discussed some interface details before. Here, we will illustrate some general rules:



Rule 1: Use the descriptive terms or architecture of the current platform

One of the most common API error designs is the use of external rules. APIs belong to a specific platform and related developer ecosystem. You cannot use descriptive terms or architectures on different platforms. This will pollute your current code library and undermine the efficiency of your peers.

Before coding, you must fully understand your target platform and code specifications. For example, in IOS and OSX, no exception mechanism is used to handle errors. Uniform Naming rules (the rules must be detailed but concise ).

Understand what protocol, delegate, and category are ). Always use the term in your code. Follow the naming schemes of constructor and destructor. Comply with local memory management rules.

Just as vocabulary and syntax are inseparable in natural languages, your style must conform to the specified platform.

 


Rule 2: Design decoupling

The component should not be associated with the project that created the component during design. If it is a GUI component or view, it should display some default content. Using the existing framework as a guide, we should try our best to keep the interaction such as the delegate protocol (delegateprotocols) loosely coupled, use notifications appropriately, and pay attention to good design and naming rules.

To do this, it is very effective to create a separate test project for each component. Force the component to only use its own API. Do not extract the commonalities between irrelevant classes.

Next let's take a look at the class interface. The initialization method is one of the most important parts of a class interface. It determines how users use your components. Your class needs to initialize some necessary configurations. Therefore, an obvious rule is as follows:



Rule 3: The required initialization conditions should be provided by Parameters 

If you have any required initialization settings, do not wait for them to be provided before they are needed, but be provided by the initialization parameters before they are needed. If the required conditions are not obtained during initialization, null (nil) is returned immediately ).

//Required parameter. It cannot beNil
-(Id)InitWithDelegate:(Id<MGTileMenuDelegate>) TheDelegate;



Rule 4: Allow access to initialization parameters

This is a continuation of the previous rule: Do not hide the parameters provided by the user during initialization within the module. You need to allow users to access them and check whether they can be modified in some way (clear or otherwise ).

//It must be specified through the initialization method
@ Property (nonatomic, weak, readonly) id<MGTileMenuDelegate>Delegate;

This is a common example of the above two rules.



Rule 5: Comment out your header file 

In fact, you will not always provide independent documents to describe code functions. If you do not provide independent documents, Your. h file (and demo program) Is your document. They should be commented out by "appropriate", and the appropriate here refers:

1: It is detailed enough, but the length should not be too long. Concise enough.

2: for professionals (languages and vocabulary ). All assumptions must be safe and cautious. Don't be confused.

In particular, you should briefly describe the functions and default values of parameters and attributes. This allows users to easily retrieve code functions in header files without looking at executable code.

//Tile background gradient(Default:Blue)
@ Property (nonatomic) CGGradientReftileGradient;
// Default: 5 pixels
@ Property (Nonatomic)NSIntegerselectionBorderWidth;
// Default:Black(Bottom)White(Top)Gradient
@ Property (nonatomic) CGGradientRefselectionGradient;



Rule 6: integrate to run up to three lines of code

Your class should be designed to be integrated into a project with only a small amount of code (excluding the delegated/Data Source protocols ). The delegate method is not included. You should use only three lines of code to perform the simplest test. These lines are:

1: instantiation

2: basic configuration.

3: display or activate it.

The following is a demo of code from MGTileMenu:

//Instantiation.
TileController=[[MGTileMenuControlleralloc] initWithDelegate: self];
//Configuration.
TileController. dismissAfterTileActivated=NO;// Make it easier to play
//Display.
[TileControllerdisplayMenuCenteredOnPoint: locinView: self. view];



Rule 7: A complicated demo usually means that the components are fragmented.

Another inference: the size of your demo depends on the component quality. The smaller the demo, the better. The Code required for the demo should be as simple as possible (but you must also properly demonstrate the customized services or functions of the components in the demo ).

To use an empty Xcode template, you only need to add a small amount of code to create an application with the core functions of your components. It is not enough to provide only one demo program. You must also make sure that you can copy and paste the sample program you provided.



Rule 8: set a plan

The standard rule for developing applications is to choose a reasonable default value instead of providing configuration options for most users. Good software is always stubborn.

In this regard, components and applications are different, because the application scenarios of components are unclear. Of course, you can make the component only apply to a specific situation, but we usually prefer the flexibility of the component. You never know how other developers will use your components. Therefore, you must make them universal.

It is important to carefully consider the functions supported by components. In particular, we need to consider the dependency relationship-not the dependency during compilation/link, but the dependency between the logical functions and interfaces. My approach is not to think about this issue at the instance variable (member) level, but to think about it at the "custom solution" level. Find out what custom solutions you want your components to have? Then, based on these customized schemes, you can select which attributes are exposed to users.

An easy mistake is that the public configuration items (interfaces) are insufficient to weaken a certain function, for example, the following example:

1: width and height settings are exposed, but rounded corners are not considered.

2: the background color settings are made public, but the background color settings are not taken into account when highlighting.

3: The size setting is made public, but the spacing is not considered.

This error usually depends on the specific component. Try to consider the relationship between attributes from the perspective of Display Effect and function. Consider the problem from the user's perspective. Flexible and easy to use, but do not discard the features of components.

//After the menu is removed, the tile is activated.(YES;Default)
@ Property (nonatomic) BOOLdismissAfterTileActivated;
//Right hand mode(YES;Default)Or left-hand mode(NO)
@ Property (nonatomic) BOOLrightHanded;
//Width and height of each Tile,Unit:Pixels(Default72Pixels)
@ Property (nonatomic) NSIntegertileSide;
//Tile spacing,Unit:Pixels(Default: 20Pixels)
@ Property (nonatomic) NSIntegertileGap;
//Radius of the tile rounded corner,Unit:Pixels(Default12.0Pixels)
@ Property (nonatomic) CGFloatcornerRadius;

Let common sense guide you. Find the options that will be used in 70% and provide them to users.

 


Rule 9: more features and fewer operations 

Among my favorite components (some of them are standard frameworks, some are open-source components from third parties, and I also write them myself), there is a frequently-seen feature. The functions implemented by components (all functions, from initialization to status update) have a certain proportional relationship with public interfaces (accessors or custom methods.

These components almost always use fewer operations (not interface operations, but interfaces) to implement more features. MGTileMenu has one initialization method and four functional methods (one of which is the simplification of another interface). In terms of its features and operations, MGTileMenu is proportional to four times. I think this is a good proportion. It can be customized flexibly while having simple and practical functions.

 //The parameter cannot beNil
-(Id)InitWithDelegate:(Id<MGTileMenuDelegate>) TheDelegate;
//Slave0Start
-(CGPoint)DisplayMenuPage:(NSInteger) pageNumCenteredOnPoint:(CGPoint) centerPtInView:(UIView*) ParentView;
-(Void)DismissMenu;
//Slave0Start
-(Void)SwitchToPage:(NSInteger) pageNum;

 


Rule 10: use controls in your controls

A good way to simplify APIS is to use existing components in your components. Unified component style does not mean that you cannot use existing components to construct new components (in fact, this is a good basic principle of software engineering ).

For example, the APIs of UITableViewCell and UIButton are so simple that they use sub-controls UILabels and UIImageViews. If appropriate, you can also do this-and expose sub-controls to make your current class interfaces more concise and consistent.

For example, in MGTileMenu, tiles are extended by UIButtons. This is much easier than drawing, tracking, and providing access interfaces in a custom view.



Rule 11: your convenience method may also be suitable for users

You will certainly add some convenient methods during the creation of components, and instinctively set them to private ). In fact, you can consider whether the user will use these methods when integrating your components to determine whether to publish them.

For example, I created these convenient features in MGTileMenu:

CGRectMGMinimallyOverlapRects(CGRectinner, CGRectouter, CGFloatpadding );
// RGBColor gradient
CGGradientRefMGCreateGradientWithColors(UIColor*TopColorRGB, UIColor*BottomColorRGB );

The first is the structure of the storage location, which is used to move the menu so that it can be fully visible in its parent view (so that other developers can create menus that match their own UI ). The second is to store the gradient structure, which is used to set the image gradient for the menu background (when the background changes, the caller will be notified through delegation ).

 


Rule 12: The Magic effect is good. The magic number is not

Sooner or later, you will put something strange in the component. And hope to give more amazing and amazing features like Steve Jobs. But I want to talk about numbers with special meanings in your code. The most common example is-1, which is usually used to indicate a special set of things or special cases.

It is correct to use a specific value to represent a type of situation. So what is incorrect? Obviously, you cannot directly use this mysterious primitive value in your code, especially you cannot expose it to the API. If you must expose it, wrap it up. For example, use # defines to define a name that is understandable.


Read the next chapter: http://blog.csdn.net/cuibo1123/article/details/39894477

-------------------------

API Design
Author: Matt Gemmell
Original Name: http://mattgemmell.com/api-design/

Translated by xoneday
Welcome to the translator's blog: http://blog.xoneday.com
Sina Weibo: @ xoneday one day

If this translation helps you, I hope you can download my APP to support me:
Douban reading: https://itunes.apple.com/cn/app/id695492935
Portable clamp: https://itunes.apple.com/cn/app/id580552733

Notebooks, Douban, and reading


* Reprinted statement:Do not delete the author/translator Information and Support content. If you do not accept this provision, do not reprint it.



What is an api?

API: Application Interface (API: Application Program Interface)
An application interface (API: application programming interface) is a set of definitions, programs, and Protocols. Through API interfaces, computer software can communicate with each other. One of the main functions of APIS is to provide a general set of functions. By using API functions to develop applications, programmers can avoid writing useless programs and reduce programming tasks.
API is also a middleware that provides data sharing for different platforms. Based on the data sharing performance between different software applications on a single or distributed platform, APIs can be divided into four types:

Remote Procedure Call (RPC): communication between programs is implemented through the process (or task) that acts on the shared data cache.
Standard Query Language (SQL): a standard query language for accessing data. It shares data between applications through a common database.
File Transfer: Transfers formatted files to share data between applications.
Information Delivery: refers to the small formatting information between loosely coupled or tightly coupled applications, and data sharing through direct communication between programs.
The standards currently used in Apis include ANSI standard SQL APIs. There are also some standards still being developed for other types. APIS can be applied to all computer platforms and operating systems. These APIs connect data in different formats (such as shared data caches, database structures, and file frameworks ). Each data format requires correct data communication with different data commands and parameters, but it also produces different types of errors. Therefore, in addition to the knowledge required to execute data sharing tasks, these types of APIs must also solve many network parameter problems and possible error conditions, that is, each application must know whether it has powerful performance to support inter-program communication. On the contrary, because this API only processes one information format, the information delivery API in this case only provides a small subset of commands, network parameters, and error conditions. Because of this, the API delivery method greatly reduces system complexity. Therefore, it is ideal to use the information delivery API type when an application needs to share data through multiple platforms.

There is a clear difference between APIs and graphical user interfaces (GUI) or command interfaces: an API is an operating system or program interface, and the other two are both direct user interfaces.

Sometimes companies use APIs as their public open systems. That is to say, the company develops its own system interface standards. When system integration, customization, and application operations are required, all members of the company can use this interface to call the source code, this API standard is called an open API.

How to provide interfaces (APIS) for other programs

This COM technology can be made into gui exe, such as Word, Excel, or Service.
From CoRegisterClassObject (...), COM is a pillar of Windows, but once you understand it, you can become the boss.

Related Article

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.