What are the pros to using "option explict"? - vb.net

All it really does is make me have to dim each variable, making it compile badly if I forget to dim a variable.
Are there ANY pros to using it?

Yes, it will prevent some types of mistakes.
One of the most obvious ones is if you make a typo and spell the variable name incorrectly, it will flag that the mistyped variable doesn't exist.

If you do not use the Option Explicit statement, all undeclared
variables are of Object type.
ref: http://msdn.microsoft.com/en-us/library/y9341s4f(v=vs.80).aspx
Think about how this will affect the GC, all your value types that should be stored on the thread stack are now stored on the managed heap and subject to garbage collection. This may not sound huge but the GC would have to check if value types have root references as well as all the reference types. It would have a significant perf impact on the GC as all your value types would be getting promoted up the generations 0,1,2 not just referenced types.

I see having to dim each variable as a big pro. I can't tell you how many times I tried to run down a bug to find out that I incorrectly spelled a variable that would have been found if "Option Explicit" had been turned on.
P.S. Always use Option Explicit.

Related

how efficient is Object type in vb.net?

I have dynamic item attributes in a dictionary that could hold either a single or a string or 2 other custom classes.
Right now i store the value in a class that has uninitialized variables for all of these and another variable to say which type to get upon request. I don't like it because it's rather clunky and seems to waste memory (since most of the time the value stored is a single).
I figured i could hold any of these in a single object variable type but i don't know what kind of penalties to expect from this, if any. Should i continue with managing the types myself or let vb figure it out?
The main thing you should worry about with the Object type in VB.NET is late-binding. If you call a method on an Object variable (except for those methods that are part of the Object type, such as ToString), the vb runtime has to use reflection to find and call the correct methods on the exact type when they're executed. If you use a specific type for your variable, that lookup will only occur once, when your code is JIT-compiled. I would say that the overhead of late-binding is significant enough that you should avoid it when possible.
However, that doesn't apply to checking the object's type and assigning to a variable with a more specific type. So if you figure out what type of object you have and assign it to the right type of variable before calling methods on it, you should be ok. There is a little bit of overhead to doing that, but it's probably no worse than what you're already doing.
Another reason to avoid late-binding is that it prevents the compiler from doing type checking.

Requesting a check in my understanding of Objective-C

I have been learning Objective-C as my first language and understand Classes, Objects, instances, methods, OOP in general, etc enough to use the language and make simple applications work, but I wanted to check on a few fundamental questions that have never been explained in examples I followed.
I think the questions are so simple that they will confuse a lot of people, but I hope it will make sense to someone out there.
(While learning Objective-C the authors are assuming I have a basic computer programming background, yet I have found that a basic computer programming background is hard to come by since everyone teaching computer programming assumes you already have one to start teaching you something else. Hence the help with the fundamentals)
Passing and Returning:
When declaring methods with parameters how is the parameter stuff actually working if the arguments being passed into the parameters can have different names then the parameter names? I hope that makes sense. I know parameter names are variables for that very reason, but...
are the arguments themselves getting mapped to a look up table or something?
Second the argument "types" (int for example) have to match the parameter return types in order for them to be passed into the method, and you always have to make your arguments values equal the parameter names somewhere else in your code listing before passing them into the method?
Is the following correct: After a method gets executed it returns a particular value (if it is not void) to the class or instances that is calling the method in the first place.
Is object oriented programming really just passing "your" Objects instance methods around with the system generated classes and methods to produce a result? If we are passing things to methods so they can do some work to them and then return something back why not do the work in the first place eliminating the need to pass anything? Theoretical question I guess? I assume the answer would be: Because that would be a crazy big tangled mess of a method with everything happening all at once, but I wanted to ask anyway.
Thank you for your time.
Variables are just places where values are stored. When you pass a variable as an argument, you aren't actually passing the variable itself — you're passing the value of the variable, which is copied into the argument. There's no mapping table or anything — it just takes the value of the variable and sticks it in the argument.
In the case of objects, the variable is a pointer to an object that exists somewhere in the program's memory space. In this case, the value of the pointer is copied just like any other variable, but it still points to the same object.
(the argument "types" … have to match the parameter return types…) It isn't technically true that the types have to be the same, though they usually should be. Some types can be automatically converted to another type. For example, a char or short will be promoted to an int if you pass them to a function or method that takes an int. There's a complicated set of rules around type conversions. One thing you usually should not do is use casts to shut up compiler warnings about incompatible types — the compiler takes that to mean, "It's OK, I know what I'm doing," even if you really don't. Also, object types cannot ever be converted this way, since the variables are just pointers and the objects themselves live somewhere else. If you assign the value of an NSString*variable to an NSArray* variable, you're just lying to the compiler about what the pointer is pointing to, not turning the string into an array.
Non-void functions and methods return a value to the place where they're called, yes.
(Is object-oriented programming…) Object-oriented programming is a way of structuring your program so that it can be conceptually described as a collection of objects sending messages to each other and doing things in response to those messages.
(why not do the work in the first place eliminating the need to pass anything) The primary problem in computer programming is writing code that humans can understand and improve later. Functions and methods allow us to break our code into manageable chunks that we can reason about. They also allow us to write code once and reuse it all over the place. If we didn't factor repeated code into functions, then we'd have to repeat the code every time it is needed, which both makes the program code much longer and introduces thousands of new opportunities for bugs to creep in. 50,000-line programs would become 500 million-line programs. Not only would the program be horrendously bug-ridden, but it would be such a huge ball of spaghetti that finding the bugs would be a Herculean task.
By the way, I think you might like Uli Kusterer's Masters of the Void. It's a programming tutorial for Mac users who don't know anything about programming.
"If we are passing things to methods so they can do some work to them and then return something back why not do the work in the first place eliminating the need to pass anything?"
In the beginning, that's how it was done.
But then smart programers noticed that they were repeating copies of some work and also running out of memory, so they decided to put that chunk of work in one central place to save memory, and then call it by passing in the data from where it was before.
They gave the locations, where the data was stuffed, names, because the programs were big enough that nobody memorized all the numerical address for every bit of data any more.
Then really really big computers finally got more 16k of memory, and the programs started to become big unmanageable messes, so they codified the practice as part of structured programming. It's now a religious tenet.
But it's still done, by compilers when the inline flag is set, and also sometimes by hand on code that has to be really really fast on some very constrained processors by programmers who know when and where to make targeted trade-offs.
A little reading on the History of Computers is quite informative about how we got to where we are today, and why we do such strange things.
All that type checks used (at most) only during compilation stage, to fix errors in code.
Actually, during execution, all variables are just a block of memory, which is sent somewhere. For example, 'id' type and 'int' are both represented as 4-byte raw value, and you can write (int)id and (id)int to convert those type one to another.
And, about parameters names - they are used by compiler only to let it know, to which memory area send some data.
That's easy explanation, actually all that stuff is complicated, but I think you'll get the main idea - during execution there are no variable names/types, everything is done via operations over memory blocks.

What are pros & cons of Passed Arrays vs Global Arrays in Excel VBA

Ok, 2nd attempt at writing a Stack Overflow Question, so forgive me if this seems familiar.
I am rewriting an Excel Macro that was built over a 2 1/2 year period, frankenstein style (added to piecemeal). One of the things I need to do is load the data into an array once and only once for data accuracy and speed. For my skill level I am going to stick with the Array methodology.
My two approaches are:
Use Global dimmed dynamic Arrays
Dim the dynamic arrays in my Main procedure and pass them to the called procedures
So, what is Stack Overflow's take on the Pros vs Cons of these two methods?
Thanks,
Craig...
First, to answer the question you specifically didn't ask: Set up a custom class and load the data in that. Seriously, you'll thank me later.
OK, on to your question. I start by limiting the scope as much as possible. That means that I'm passing variables between procedures. When all your variables have the most restrictive scope possible, you run into the fewest problems down the line.
Once a variable passes two levels deep (calling procedure to 1st tier, 1st tier to 2nd tier), then I start taking a critical look at my structure. Usually (but not always) if all three procedures are in the same module, I'll create a module-level variable (use the Private keyword instead of Dim). If you separate your modules correctly (not arbitrarily) you can have module-level variables without much risk.
There are some variables that are always global right from the start: the variable that holds the app name and app version; the top-level class module that should never lose scope as long as the app is running; the constants (I know they're not variables) that hold things like commandbar names. I know I want these global, so they start that way.
I'm going to go out on a limb and say that module-level variables never migrate to global variables. Global variables start out that way because of their nature. If using a module-level variable seems cumbersome, it's probably because I've split a module up for no good reason or I need to rethink my whole framework.
That's not to say I've never cheated and used a global when I shouldn't have. We've all done it and you shouldn't lose any sleep if you do it too.
So to properly book-end this post: I quit using arrays unless I'm forced to. I use custom classes because
ActiveCell.Value = Invoice.LocalSalesTaxAmount
is so much nicer to debug than
ActiveCell.Value = aInvoice(35,2)
Just in case you think you need more skill to work with custom classes - so did I. I bit the bullet and so can anyone else.
You need to be careful with globals in Excel VBA, because if your application hits any kind of bug, and does some kind of soft reset (but the app still functions), then the globals will have been erased.
I had to give up on globals, since I don't write perfect apps.

What is the alternative to excessive use of the dot operator in Obj-C?

See what you think of this line of code:
if ([pickerViewController.picker.bvc.currentResolve.name isEqualToString:message])
...
Would you consider this to be excessive use of the dot operator?
If not, I can leave it as-is.
But if so, what's the preferred alternative?
This is more of a Law of Demeter violation than a problem with the dot operator. The "cleaner" way to do this would be to give the object the logic to figure this out itself, so you could do something like
if ([pickerViewController hasPickedName:message])
I don't think there is excessive use of the property notation. If an object has a property, access it as such; it demonstrates to the reader what the programmer means.
Oh, and pre-empting the "looks like a struct" brigade; if you can't tell a struc from an object in your code, refactor your code.
So long as each use of the dot operator there really is fetching a property (i.e. not a method which is chiefly concerned with doing work for purposes other than returning a value), then that's fine. In fact, if you check Wil Shipley's blog, he's actually a fan of chaining as many function calls together into a single line as is necessary (he dislikes excessive use of local variables).
I find that debugging this sort of thing is always more trouble than it's worth, so I tend to create intermediate variables for each of the property accesses. Or, as others suggested, refactor this so it looks simpler at the usage site (by putting the smarts in a method).
I agree with Chuck and commenters. Your method is dependent on too many other objects, but putting hasPickedName: on pickerViewController means pickerViewController still has to do [picker.bvc.currentResolve.name isEqualToString:message] somehow.
Instead, you could put hasPickedName: on bvc and inject bvc as a delegate (typed id<NamePickerDelegate> maybe) into your top-level object using Interface Builder. To be truly Demeter-compliant, make currentResolve grow a method nameMatches: that shortcuts [currentResolve.name isEqualToString:message].
You should look carefully at the complexity caused by the problem verses the complexity that would be introduced by each solution. If you judge that the original code is simpler and easier to maintain than the alternatives, keep it.

Understanding Variables in Visual Basic

What's the main problem if I don't declare the type of a variable? Like, Dim var1 versus Dim var1 as Integer.
The main reason to declare variable types in languages which allow you to use variant types is as a check on yourself. If you have a variable that you're using to hold a string, and then by accident you pass it to a function that expects an integer, the compiler can't tell you that you messed up unless you told it that that variable was supposed to always be a string. Instead, you're stuck with your string being reinterpreted as an integer, which is pretty much never going to give you what you want and the results will likely be confusing, and it will be hard to track down the bug.
In pretty much all languages there are a lot of constructs where you could leave it out and your program would work, but exist as a check on the programmer. The first job of a compiler is to make your code into an executable. But the second job of the compiler is to try as much as possible to make sure that the programmer didn't make a mistake. Especially when your program gets large, it's easier to let the compiler find mistakes like this as opposed to trusting that you typed everything exactly right.
Additionally, there is usually some processing overhead associated with variants, but this is a more minor concern.
There are a few reasons:
Vastly improved type safety.
Lower cognitive overhead; the compiler and Intellisense can help you.
Lower performance overhead; transforming things to and from Variant types has a small but nontrivial cost.
Eliminates need for naming warts (e.g., lblTitle to tell you that something is supposed to hold a Label).
Moves some kinds of runtime errors to compile-time errors, which is a big productivity win.
Someone else already mentioned Intellisense, but but it's worth repeating.
Additionally, when you declare an explicit type for your variable you make it possible for the compiler to do all kinds of extra type checking and validation on your code that would not otherwise be possible. What happens is that now certain kinds of very common error are caught and fixed at compile time rather than run time. The user never sees them. You don't want to leave errors for run-time.
You say "it could be anything" — and that is true. But you then go on to say "so it must be good". That doesn't necessarily follow, and it's very dangerous. Not everything can be assigned or combined with everything else. It could be anything — but it is something, or rather some specific thing. Without an explicit type, the compiler has no way to know what and can't help you avoid errors.
Superficially, if you don't declare the type, Intellisense can't help you with it because it doesn't know what type it is.
Contrast this to Python's typing system. Python allows a developer to use a variable without declaring type in advance but once a variable is used, the type is fixed. A variant, by contrast, can be assigned any type of value initially and a different type can be stored later on without any warning or complaint. So you can put a string into a variable that previously held a numeric.
Dim myvar1
myvar1 = 1
'A whole lot more code
myvar1 = "this string"
If you ever have to maintain someone else's code, you'll start to understand why this sort of thing (changing a variable type silently) can be extra tough to maintain. Especially if you're using a module level variable this could lead to some really interesting problems. This is along the same lines as using Option Explicit in VB code. Without Option Explicit you can do this sort of thing without realizing it:
myvar1 = 1
'A whole lot more code here too
myvarl = 2
In some fonts those two variable names would be impossible to distinguish and this could lead to some tough to find bugs.