Skip to content

Commit

Permalink
Merge pull request #7 from inaka/elbrujohalcon.7.suggestion__use_macr…
Browse files Browse the repository at this point in the history
…os_appropr

Suggestion: Use Macros appropriately
  • Loading branch information
igaray committed Sep 15, 2014
2 parents de489f7 + dd04d41 commit 45af036
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 6 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Table of Contents:
* [Strings](#strings)
* [IOLists over string concatenation](#iolists-over-string-concatenation)
* [Macros](#macros)
* [No Macros](#no-macros)
* [Uppercase Macros](#uppercase-macros)
* [No module or function name macros](#no-module-or-function-name-macros)
* [Misc](#misc)
Expand Down Expand Up @@ -235,6 +236,16 @@ Erlang syntax is horrible amirite? So you might as well make the best of it, rig

### Macros

***
##### No Macros
> Don't use macros, except for very specific cases, that include
> * Predefined ones: ``?MODULE``, ``?MODULE_STRING`` and ``?LINE``
> * Magic numbers: ``?DEFAULT_TIMEOUT``
*Examples*: [macros](src/macros.erl)

*Reasoning*: Macros make code harder to debug. If you're trying to use them to avoid repeating the same block of code over and over, you can use functions for that.

***
##### Uppercase macros
> Macros should be named in ALL_UPPER_CASE:
Expand Down
12 changes: 6 additions & 6 deletions src/macro_names.erl
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
-module(macro_names).

-define(bad, bad).
-define(BADMACRONAME, bad).
-define(Bad_Macro_Name, bad).
-define(Bad_L33t_M@Cr0, bad).
-define(bad, 1).
-define(BADMACRONAME, 2).
-define(Bad_Macro_Name, 3).
-define(Bad_L33t_M@Cr0, 4).

-define(GOOD, good).
-define(GOOD_MACRO_NAME, good).
-define(GOOD, 5).
-define(GOOD_MACRO_NAME, 6).
32 changes: 32 additions & 0 deletions src/macros.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
-module(macros).

-define(OTHER_MODULE, other_module).
-define(LOG_ERROR(Error),
error_logger:error_msg(
"~p:~p >> Error: ~p~n\tStack: ~p",
[?MODULE, ?LINE, Error, erlang:get_stacktrace()])).

-define(HTTP_CREATED, 201).

-export([bad/0, good/0]).

bad() ->
try
?OTHER_MODULE:some_function(that, may, fail, 201)
catch
_:Error ->
?LOG_ERROR(Error)
end.

good() ->
try
other_module:some_function(that, may, fail, ?HTTP_CREATED)
catch
_:Error ->
log_error(?LINE, Error)
end.

log_error(Line, Error) ->
error_logger:error_msg(
"~p:~p >> Error: ~p~n\tStack: ~p",
[?MODULE, Line, Error, erlang:get_stacktrace()]).

0 comments on commit 45af036

Please sign in to comment.