[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: Defining APIs, best practices.
- From: "Thijs Schreijer" <thijs@...>
- Date: Fri, 14 Dec 2012 19:41:58 +0100
> From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org] On
> Behalf Of Jorge
> Sent: vrijdag 14 december 2012 17:42
> To: Lua mailing list
> Subject: Defining APIs, best practices.
>
> Here comes a couple related questions:
>
> 1. when defining an API for a enable/disable type call, is nil supposed to
> be accepted as false, or not? In other words, is better to force to
> provide true/false, or just anything and then evaluate it to true or
> false?
> This is:
>
> ----------------------
> function M.feature_enable(p)
> if p then
> --enable
> else
> --disable
> end
>
> end
> ----------------------
>
> or
>
> ----------------------
> function M.feature_enable(p)
> if p==true then
> --enable
> elseif p==false then
> --disable
> end
> end
> ----------------------
Generally I would take the first approach, based on "if it hurts, don't do
it", it's the callers responsibility. But if the overall way your code is
structured, contains a lot of type checking, then I suppose the second
approach is the best fit.
> 2. What is the opinion on a API call defined as follows:
> * If a parameter is provided, it is applied
> * If no parameter or nil is provided, nothing is changed
> * The current value (as set or kept) are returned.
>
> So, a "setter" would be M.feature_enable(true), and a "getter" would be
> M.feature_enable()
I have used this as well, but again, it depends on the remainder of your
API. It's a code convention whether you want explicit setter/getters, or
implicit like your example.
Whatever you do, try to be as consistent as possible.
Thijs