Is there ever a good reason to use eval()?

后端 未结 10 1047
清歌不尽
清歌不尽 2020-12-03 20:51

It seems to me that eval() is treated with the same disdain that goto is. And by eval, I mean a function for executing a string as code, as seen in

相关标签:
10条回答
  • 2020-12-03 21:13

    eval is often the most expedient solution in situations where you are dynamically generating code. Even in languages that do not officially support eval, such as Java, they support reflection and modification of classes at runtime which are similar. (See books such as Stu Halloway's Component Development for the Java Platform )

    0 讨论(0)
  • 2020-12-03 21:13

    For quick hacks, no problem because it's a handy quick-out.

    In production code, consider it a last resort—and even then, try something else—because eval is difficult to control and thus dangerous. For anything non-trivial, implement a sublanguage.

    0 讨论(0)
  • 2020-12-03 21:15

    For debugging/testing an idea before implementing it the proper way.

    For instance, you're making a toy calculator, and you want to work on the gui first, so you just use eval to do the "back-end" work in the background. Later, you come back to the back-end, scratch eval, and write a proper expression parser.

    0 讨论(0)
  • 2020-12-03 21:17

    One reasonable use is if you have an interpreted language that you've built on top of another language, but you still want to provide some sort of "escape hatch" to allow people to get back to functions that are provided by the underlying language. One example is implementing Prolog in Lisp and then defining a predicate that allows direct use of Lisp functions via EVAL.

    0 讨论(0)
  • 2020-12-03 21:19

    I used it once while pentesting a site - we wrote a small php script that decrypts and executes cryptographically signed payloads from non-logged HTTP data sources on the fly. This is the best use I've seen of eval() so far.

    (In other words: no, I've never seen a good use for eval)

    0 讨论(0)
  • 2020-12-03 21:19

    Offhand thought: eval is good for implementing a poor man's expression compiler, or things like that. It's also a dull, rusty substitute for hygienic macros.

    0 讨论(0)
提交回复
热议问题