开发者

Replacing All References to a Variable By C++ #define

开发者 https://www.devze.com 2023-03-13 15:19 出处:网络
Not sure if anyone has this experience in maintaining old codes. In some old codes, I have a global variable referenced in many places.I want to replace all those references to my global variable to s

Not sure if anyone has this experience in maintaining old codes. In some old codes, I have a global variable referenced in many places. I want to replace all those references to my global variable to something else, say a function call. Can I do it by a simple #define in every source file? e.g.

#define legacyGlobalVariable func1("legacyGlobalVariable")

My func1() will accept th开发者_运维知识库e name of the old variable and return something same type as the legacyGlobalVariable.

I know #define can replace legacyGlobalVariable that forms a token. But I am not sure if there are any special cases that this simple technique cannot handle. For example, I know I need to prevent this:

legacyGlobalVariable(23);// a badly named function same name as my global var

becoming

func1("legacyGlobalVariable")(23);//but at least, it cannot compile

Are there any other possible issues with this simple technique? Did anyone ever try using it? I know to verify all the possible cases really require familiarity with C++ which is beyond my grasp for the time being.


The primary issue with it is that #define is evil. This will not improve the readability of your code, so I'd recommend just biting the bullet and use your editor's find/replace function instead.


Are there any other possible issues with this simple technique?
Yes! What about parameter type checking?
For a function arguments are checked for type and compilers return errors if type mismatch. With macros there is no such type checking.

Also, macros often leave you with lot of unimaginable side effects.

You are far better off replacing it with a function rather than mapping the function through macro.


IMHO, if the code is old enough and is working fine then better not change anything. Follow the software industry rule of, "Don't touch anything until it's needed."

Why you want to waste your time/effort to change a legacy code and testing it in various scenarios, rather than learning to develop something new. In case if something is broken due to the change, then you will end up spending more time on fixing that rather than actual maintenance.


You can use some scripting language e.g. perl and automate your find and replace, That'd give you more control

e.g. you can easily avoid instances like this from being modified

func1("legacyGlobalVariable")(23)

it saves you a lot of time also.

0

精彩评论

暂无评论...
验证码 换一张
取 消