Question

I am wonder what is best to do. I have main function with iteration loop. For each item in the list I need to get data from the db by using NHibernate. There are sub functions which are called in the iteration loop body. In each sub function I need to use data from the item association tables. for ex. If the Item is Teacher, each func need the Teacher.Students and etc. In my case the record list include many items. So my question what is better: 1 - To send the Teacher.Students to each sub func. or 2 - Declare a class variable that all the func know it and it will initialized on each iteration.

Thank in advance!

Was it helpful?

Solution 2

You should avoid using any kind of global variables and always store your data in the smallest possible scope. This is one of the principles of good design.

The code is so clearer easier to understand, maintain, reuse and change. Dependencies are kept low.

Imagine you need to change this code in the future. If you touch a global variable, you might possibly break some code on the other side (as other methods can use the same variable). If it is localizes, you just need to analyse the impact inside of the method.

Besides, the method with parameters is nicelly encapsulated and its signature is self-explanatory. YOu can even possibly reuse it in the future!

UPDATE

There are a lots of resources on internet, here is a good start: http://www.oodesign.com/design-principles.html

In your case the use of global variables clearly breaks the Open-closed Principle:

Software entities like classes, modules and functions should be open for extension but closed for modifications.

If you use the global variable instead of sending parameter (Teacher.Students), your method is obviously not closed for modifications, as any change to this global variable (not part of the method!) cause potential crash in the method. With the parameter, your method is closed and protected.

OTHER TIPS

Imagine you would maintain the code, but somebody else wrote it. It would be much easier for you to understand what a function does if you see what it is receiving as input. So you know what kind of data a function processes. You should not use a class variable if you can just call your function with this data as input.

You can read about good programming style at Elements of Programming Style

From there you get:

Use variables at the smallest possible level of scope. One implication of this rule is that you should minimize the use of global variables. There is a place in good programming style for global variables, and that is for a body of knowledge that will be acted on by many sections of the program, and which is in some sense the major essence of that program. Don't use global variables as a convenient means to communicate between two subroutines.

I too think on the line of using functions instead class level variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top