开发者

Is it better to put Functions in Modules or Classes in VB.NET

I have a Module in VB.NET called Math.vb and in that module, I created a Function that displays returns the percentage of one number to another. I have a Sub that calls 开发者_JAVA技巧the Function and I call the Sub from my Form1 class. Is there an advantage/disadvantage to putting the function in the class or the module?


It all depends. Modules in VB.net are basically the same as static classes, but you don't have to preface method names in a module with the "module name".

This makes modules a nice place to put "Utility" functions that are of a very generic nature and that don't relate to any existing class. Your "Percentage" function would probably fit in this category.

On the other hand, if you were to create a class that represented those numbers you're calculating the percentage for, and one method of that class was going to be this "percentage" function, that would return the percentage based on the numbers that are defined within the class instance, then, yes, I'd put the function in a class.

And finally, if the Percentage function would only make sense to be called from the Form1 class, then I'd make it a PRIVATE function in that class.

For methods, you generally want to apply the most restrictive scope possible.


A module cannot implement an interface or inherit from another class.


I don't think there is any diffenrence. A module is in essence a class where each member is Shared.


The question is where you should put the CallPercentage.

First of all, is it a good question? Yes, it is very good question because it is important where you put a piece of code in. I think the OOP design is actually about “how to get it organized”.

To your specific question, I guess, most likely, you want to put it with the Form1 if it is purely serve the Form1’s functioning. But if you think it would be as general as the Function of Percentage, and it would be called in many cases, you may want to put it in the Module. Usually, you want to keep a Module from frequent changes.

One more advice, since VB.Net already has “Math”, you’d better call the module with a specific name, like “XiaMath”.


While I mostly agree with drventure's answer. I just wanted to add that it's been my experience, on ever project I've ever been on for any length of time, sooner or later someone's going to say "I know, lets's do threads!" or "Lets move this dll to a web service!" And after you do it you will want to build a time machine and go back in time and strangle the guy who wrote the math.vb module because every once in a while, it spits out the wrong answer and you can't figure out why.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜