英文:
Golang Static vs dynamic binding for objects
问题
我有一个应用程序,根据结构体中的字符串对请求进行过滤,并执行不同的函数。
我的方法是使用一个映射(Map),将字符串映射到函数指针并执行它们。然而,我的一个队友想要通过反射来进行过滤。我们正在使用Go语言,并且这是用于监控我们网站活动的。
队友的方法:使用反射根据字符串切换对象,将字符串传递给函数,然后让函数调用相关的函数。
我的方法:简单地使用字符串到函数的映射。
任何帮助都将不胜感激。
英文:
I have this application where requests are filtered based on the string in the struct and made to execute different functions.
My approach is to have a Map which maps the strings to the function pointers and execute them. However this approach is being contended by a teammate who wants to do this filtering by reflection. We are using Go and it is for monitoring the activity of our site.
Teammates approach: Use reflection to switch the object based on the string, pass the string to the function and let the function call the relevant function.
My approach: Simple map from string to functions
Any help is appreciated.
答案1
得分: 3
基于反射的自动发现的缺点是,你必须永远小心添加到系统中的内容,因为它可能会被自动捕捉到。
相比之下,使用映射方法,你需要明确地公开每个函数。
反射确实更酷和自动化,但自动化并不适合安全性或长期可维护性。
此外,如果你尝试注册一个不匹配的函数,map[string]func(具有特定签名)将无法编译。
当你使用反射找到东西,然后思考为什么它在运行时失败时,你会发现这个问题。
英文:
Downside of reflection based auto-discovery is that you forever have to be careful on what you add to the system because it can be automatically picked up.
vs map approach where you would need to explicitly expose each function.
Reflection is more cool and auto-magical, for sure. But auto-magical doesn't lend it self very well to security or long term maintainability.
Plus, a map[string]func(with specific signature) won't compile if you attempt register a non-matching function.
Where you will find stuff with reflection and then ponder why it's a runtime fail.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论