Get depth of call stack? - scala

I'm trying to check the stack safety of some very complex code, and would like a way to check the current depth of the call stack and get the result as an integer. I can kind of see how I'd stitch something together, but it involves imports and creating an exception... is there an easier or more elegant way?
For context, I have some very sophisticated, FP-heavy code that I suspect is not stack safe for arbitrary input. I have a lot of general ideas on how to check that, but I don't know that there isn't some black magic in play, so I'd like to check the actual stack depth.
EDIT: Someone suggested this as a duplicate, but:
When I try to use that method, it gives me inconsistent results - sometimes I get what looks like reasonable stack depth, others I get "10" for everything, including a test I wrote to intentionally stack overflow. I'm hoping there's an alternate method available.
Even if it is the best available, the question refers to Java, and it might be easier for future people investigating the Scala situation to find that it is in fact the same without having to ask.

Related

Perl SQLite error handling: taking different actions according to the error code

I'm new to Perl programming (and to SO too) so my question may be formulated in a bad way, but I really have read a lot of books and tutorials and I haven't found anything addressing (even mentioning) my problem.
I'm trying to use DBI and SQLite to write some code which retries an insertion query if a recoverable error occurs (DB full or locked, etc.), but dies if the error is unrecoverable (DB deleted or corrupted, etc.).
I've found that the SQLite C interface exports the error codes:
http://www.sqlite.org/c3ref/c_abort.html
but I haven't found anything similar for Perl. I really wish I don't have to use magic numbers in my very first Perl program! :-)
By the way, the documents and examples I saw online explain very well the manual vs. automatic (i.e. with exceptions) error handling in DBI, but none of them shows how to take different actions according to the error type. Isn't this a common use case?
Moreover, they all agree that DBI::err is not the correct variable to tell which error occurred. They more or less implicitly say that DBI::errstr is to be used, but I find it a bit awkward to rely on a string comparison against a human oriented, possibly multi-line error string...
Thanks for any suggestion!
My work with DBI has almost always been with mysql instead of sqlite3, so I can't speak from direct experience. However, don't feel too bad if you absolutely must check for magic strings and numbers. The key thing is how you do it. Whenever you have to rely on magic strings and/or numbers, put them in a constant or hash in the configuration portion of your script (or perhaps even a configuration file).
The bad thing about magic numbers/strings is that they are hard to manage if they change, or either no one quite remembers what generates that condition, etc. But this is mitigated if you do it correctly and document it.
BTW - if you're just getting started, I strongly recommend reading Damian Conway's, "Perl Best Practices". I checked, and he doesn't address handling magic strings/numbers, but it's still the best book I've read on Perl. Once you go through PBP, take a look at Perl Critic -- it's a wonderful tool that will make you cry. It will flag magic strings, and many, many other things :)

Key-Value-Observation -- Looking for a more elegant solution to respond to value changes

I've run into a frustrating feature of KVO: all notifications are funneled through a single method (observeValueForKeyPath:....), requiring a bunch of IF statements if the object is observing numerous properties.
The ideal solution would be to pass a method as an argument to the method that establishes the observing in the first place, but it seems this isn't possible. Does a solution exist to this problem? I initially considered using the keyPath argument (addObserver:forKeyPath:options:context:) to call a method via NSSelectorFromString, but then I came across the post KVO Dispatcher pattern with Method as context and the article it linked to which offers a different solution in order to pass arguments along as well (although I haven't gotten that working yet).
I know a lot of people have come up against this issue. Has a standard way of handling it emerged?
OP asks:
Has a standard way of handling it emerged?
No, not really. There are a lot of different approaches out there. Here are some:
https://github.com/sleroux/KVO-Blocks
http://pandamonia.github.io/BlocksKit
http://www.mikeash.com/pyblog/friday-qa-2012-03-02-key-value-observing-done-right-take-2.html
https://github.com/ReactiveCocoa/ReactiveCocoa
http://blog.andymatuschak.org/post/156229939/kvo-blocks-block-callbacks-for-cocoa-observers
Seriously, there are a ton of these... Google "KVO blocks"
I can't say that any of the options I've seen seem prevalent enough to earn the title "standard way". I suspect most folks who feel motivated to conquer this issue just pick one and go with it, or write their own -- it's not as if adapting KVO to use block based callbacks is rocket science. The Method-based approach you link to doesn't seem like a step forward for simplicity. I get that you're trying to take the uncertainty of the string-based-key-path <-> method conversion out of the equation, but that kind of falls down because not all observable keys/keyPaths are methods. (If nothing else, you can observe arbitrary keys on NSMutableDictionaries and get notifications.)
It sure would be nice if Apple would release a new blocks-based KVO API, but I'm not holding my breath. But in the meantime, like I said, just pick one you like and use it or write your own and use that.

Exception Handling....in Xcode/Obj-C

Is there a feature in Xcode to do something like this:
Select a section of source code, chose a refactoring or similar type menu option and the IDE would then wrap the source code in a try/catch block with all the exceptions that could be thrown based on the Class API's used in the selected code?
As a second question, I'm more familar with OO languages where a significant portion of the code is wrapped in try/catch blocks in a production applciation. For example; if an attempt is made to access an array with an invalid index then an "ArrayOutOfBoundsException" would be thrown at runtime, and would be handled by the try/catch block surrounding the code. Is there a similar mechanism is Objective-C? Although I do see that Objective C supports try/catch blocks and expection handling with NSException, I just donot see it used much in the code of the sample projects, or in general which exceptions a given class may throw in the Class References. However I have not yet been thru to many of the class references.
Thank you...
For your first question: No. Consider filing an enhancement request with Apple.
For your second question: It has already been covered by other questions on Stack Overflow like here, here, here, or here. The search box is your friend.

Is it best to use if statements or switch statements in cellForRowAtIndexPath? - UITableView

When setting up cells in UITableView, is it best to use if statements or switch statements as a general practice?
I'm talking specifically about cellForRowAtIndexPath here and other UITableView methods, not as a general programming question.
Because I am so old that I worry about performance, I would probably do it this way ............ but wait: modern compilers, quite simply, "take over" and optimize/compile how they want.
So in my opinion, it truly and profoundly makes no difference, for that reason:
You have no clue what modern compilers are doing, so it's pointless worrying about writing it one way or the other way.
I tend to prefer "if" rather than complicated modern switches, purely as a stylistic matter and to wave the flag for old-fashionedness.
You could possibly say: try to "return" from the routine as early as possible on each path so it doesn't pointlessly traverse stuff at the end. I lose sleep over things like this, it's a great question.
One point .. in iOS programming there is tremendous value in doing things the same way others do them. I hate that fact, but, it's true! So in the specific question at hand, if you can gleam an Apple idiom -- do it that way, for sure.
It makes no difference whatsoever.
You should ensure that you try and reuse a "compatible" cell via the dequeueReusableCellWithIdentifier method on the provided UITableView instance, but other than that you just need to return a valid UITableViewCell - how you get to that end-point is completely irrelevant.
That said, as a bit of advice I'd try and keep things as "light" as possible to ensure that the user interface remains responsive. (i.e.: Don't try and interrogate complex data structures within this method - do all that beforehand and simply grab the results from the relevant data source within the cellForRowAtIndexPath.)
There are probably dozens good reasons for each method, plus a lot of other solutions. Here's my opinion on that:
If you set up a fixed number of elements (enumerated), name them with an enum type and use switch statements. It is very structured, easily readable, and with some compiler settings you'll get a warning if you miss a case.
In case of open/unlimited/not-so-well-structured choices, use if. Sometimes, more than one cell comes from the same code block, sometimes a helper object is used, etc.
As with every code: Keep it simple, readable and easy to maintain. if or switch is not a performance-critical decision here.

Good practice class line count [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I know that there is no right answer to this question, I'm just asking for your opinions.
I know that creating HUGE class files with thousand lines of code is not a good practice since it's hard to maintain and also it usually means that you should probably review your program logic.
In your opinion what is an average line count for a class let's say in Java (i don't know if the choice of language has anything to do with it but just in case...)
Yes, I'd say it does have to do with the language, if only because some languages are more verbose than others.
In general, I use these rules of thumb:
< 300 lines: fine
300 - 500 lines: reasonable
500 - 1000 lines: maybe ok, but plan on refactoring
> 1000 lines: definitely refactor
Of course, it really depends more on the nature and complexity of the code than on LOC, but I've found these reasonable.
In general, number of lines is not the issue - a slightly better metric is number of public methods. But there is no correct figure. For example, a utility string class might correctly have hundreds of methods, whereas a business level class might have only a couple.
If you are interested in LOC, cyclomatic and other complexity measurements, I can strongly recommend Source Monitor from http://www.campwoodsw.com, which is free, works with major languages such as Java & C++, and is all round great.
From Eric Raymond's "The Art Of Unix Programming"
In nonmathematical terms, Hatton's empirical results imply a sweet spot between 200 and 400 logical lines of code that minimizes probable defect density, all other factors (such as programmer skill) being equal. This size is independent of the language being used — an observation which strongly reinforces the advice given elsewhere in this book to program with the most powerful languages and tools you can. Beware of taking these numbers too literally however. Methods for counting lines of code vary considerably according to what the analyst considers a logical line, and other biases (such as whether comments are stripped). Hatton himself suggests as a rule of thumb a 2x conversion between logical and physical lines, suggesting an optimal range of 400–800 physical lines.
Taken from here
Better to measure something like cyclomatic complexity and use that as a gauge. You could even stick it in your build script/ant file/etc.
It's too easy, even with a standardized code format, for lines of code to be disconnected from the real complexity of the class.
Edit: See this question for a list of cyclomatic complexity tools.
I focus on methods and (try to) keep them below 20 lines of code. Class length is in general dictated by the single responsibility principle. But I believe that this is no absolute measure because it depends on the level of abstraction, hence somewhere between 300 and 500 lines I start looking over the code for a new responsibility or abstraction to extract.
Small enough to do only the task it is charged with.
Large enough to do only the task it is charged with.
No more, no less.
In my experience any source file over 1000 text lines I will start wanting to break up. Ideally methods should fit on a single screen, if possible.
Lately I've started to realise that removing unhelpful comments can help greatly with this. I comment far more sparingly now than I did 20 years ago when I first started programming.
The short answer: less than 250 lines.
The shorter answer: Mu.
The longer answer: Is the code readable and concise? Does the class have a single responsibility? Does the code repeat itself?
For me, the issue isn't LOC. What I look at is several factors. First, I check my If-Else-If statements. If a lot of them have the same conditions, or result in similar code being run, I try to refactor that. Then I look at my methods and variables. In any single class, that class should have one primary function and only that function. If it has variables and methods for a different area, consider putting those into their own class. Either way, avoid counting LOC for two reasons:
1) It's a bad metric. If you count LOC you're counting not just long lines, but also lines which are whitespace and used for comments as though they are the same. You can avoid this, but at the same time, you're still counting small lines and long lines equally.
2) It's misleading. Readability isn't purely a function of LOC. A class can be perfectly readable but if you have a LOC count which it violates, you're gonna find yourself working hard to squeeze as many lines out of it as you can. You may even end up making the code LESS readable. If you take the LOC to assign variables and then use them in a method call, it's more readable than calling the assignments of those variables directly in the method call itself. It's better to have 5 lines of readable code than to condense it into 1 line of unreadable code.
Instead, I'd look at depth of code and line length. These are better metrics because they tell you two things. First, the nested depth tells you if you're logic needs to be refactored. If you are looking at If statements or loops nested more than 2 deep, seriously consider refactoring. Consider refactoring if you have more than one level of nesting. Second, if a line is long, it is generally very unreadable. Try separating out that line onto several more readable lines. This might break your LOC limit if you have one, but it does actually improve readability.
line counting == bean counting.
The moment you start employing tools to find out just how many lines of code a certain file or function has, you're screwed, IMHO, because you stopped worrying about managebility of the code and started bureaucratically making rules and placing blame.
Have a look at the file / function, and consider if it is still comfortable to work with, or starts getting unwieldly. If in doubt, call in a co-developer (or, if you are running a one-man-show, some developer unrelated to the project) to have a look, and have a quick chat about it.
It's really just that: a look. Does someone else immediately get the drift of the code, or is it a closed book to the uninitiated? This quick look tells you more about the readability of a piece of code than any line metrics ever devised. It is depending on so many things. Language, problem domain, code structure, working environment, experience. What's OK for one function in one project might be all out of proportion for another.
If you are in a team / project situation, and can't readily agree by this "one quick look" approach, you have a social problem, not a technical one. (Differing quality standards, and possibly a communication failure.) Having rules on file / function lengths is not going to solve your problem. Sitting down and talking about it over a cool drink (or a coffee, depending...) is a better choice.
You're right... there is no answer to this. You cannot put a "best practice" down as a number of lines of code.
However, as a guideline, I often go by what I can see on one page. As soon as a method doesn't fit on one page, I start thinking I'm doing something wrong. As far as the whole class is concerned, if I can't see all the method/property headers on one page then maybe I need to start splitting that out as well.
Again though, there really isn't an answer, some things just have to get big and complex. The fact that you know this is bad and you're thinking about it now, probably means that you'll know when to stop when things get out of hand.
Lines of code is much more about verbosity than any other thing. In the project I'm currently working we have some files with over 1000 LOC. But, if you strip the comments, it will probably remain about 300 or even less. If you change declarations like
int someInt;
int someOtherInt;
to one line, the file will be even shorter.
However, if you're not verbose and you still have a big file, you'll probably need to think about refactoring.