5

String #define or const *

 3 years ago
source link: https://www.codesd.com/item/string-define-or-const.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

String #define or const *

advertisements

I know this question has been asked several times, but mine is slightly different. Before closing this as duplicate, please read it fully. There are many posts on stack overflow that says, "Personally, I hate MACROS, Don't use that shit". I've read all those and my case is different. I'm trying to define URLs used in a software (iOS app) using #define macros.

I agree that using const strings is a better practice than #define macros. But in an increasingly REST based API world that accepts query parameters as a part of URL, how can you still use const strings to represent a URL that changes?

Instead of http://api.myblog.com/posts?entryid=%@ a API Server that following REST principles would have http://api.blog.com/posts/entries/[entryid]

In the former type, URL is http://api.myblog.com/posts for all entries and they don't change. A const string was possible.

In the latter type, URL changes with every entry and I use a Macro that expands to a full URL like this.

#define GET_ENTRY_URL(__MY_ENTRY_ID__) [NSString stringWithFormat:@"http://api.myblog.com/posts/entries/%@", __MY_ENTRY_ID__];

Are there any design flaws in my method? Would like to know your inputs.

Thanks.


Looking from the perspective of the compiler, #define is a preprocessor directive (refer to the definition in c, http://en.wikipedia.org/wiki/C_preprocessor).

In this case, compiler might be doing the whole text replacement before compiling your codes.

e.g.: if you define:

#define GET_ENTRY_URL(__MY_ENTRY_ID__) [NSString stringWithFormat:@"http://api.myblog.com/posts/entries/%@", __MY_ENTRY_ID__];

it could be replacing every occurrences of GET_ENTRY_URL(x) with [NSString ..., x] in your codes. Potentially, instances might be created everywhere we use the macro if the implementation of objective-c is following this.

static const/variable seems to be a better way.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK