Acceptable answers for an interview question [closed] - exception

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
What kind of answers would you accept to the following question
"Describe the process and/or pitfall of throwing exceptions from constructor and destructors" (C++/C#/java)
What amount of knowledge about this would you consider essential, for a candidate claiming to have several years of experience in any of these languages (if he misses this, you almost certainly don't want him).

If someone said they had 2 years of experience in C++ but didn't understand the ins and outs of constructors / destructors and exceptions, it would not prevent me from hiring them. This is the type of knowledge that can be easily learned and consists of a few simple rules.
I would certainly like them to have that knowledge but not having it does not make them a bad or lazy programmer. I've worked with excellent C++ programmers that spent the majority of their time in old school COM and HRESULT land. This makes heavy use of C++ but virtually eliminates C++ exceptions. There is no need or reason for them to have learned it. Once we introduced exceptions into the code base, it took about 15 minutes to get everyone on board with the constructor / destructor problem.
I would much rather use an interview to test a persons problem solving skills than to see if they knew the ins and outs of a particular part of C++. It is so easy to teach that, but so hard to teach problem solving.

He must know that in C++ the destructor is only called for fully constructed objects. So that the following class is leaky in C++:
class Leaky {
public:
Leaky() { a = new char[100]; b = new char[100]; }
~Leaky() { delete a; delete b; }
private:
char* a;
char* b;
};
If exception is thrown while executing b = new char[100] then the Leaky::~Leaky() is not called and you've got a memory leak.

How about this (I am referring to C++): If an object throws within its constructor, the object may be left at an undefined state. The destructor will not run. This may lead to memory and handle leaks possibly even deadlocks.

Also, in C++, if an exception is unwinding the stack, and another exception is thrown from a destructor, the program will terminate (or, to be exact, call the terminate_handler).

Can't you put the constructor code in try-catch-finally block in C#? This way, if something goes wrong, the code in finally-section will free the resources.

This is kind of an edge question. For example, a competent developer will probably have figured out it's a bad idea somewhere along the line, and just avoids them. Frankly, the best I would've done on this is something like, well, it may leave the object in a partially constructed state, so it's generally best to avoid it." I would prefer to have them elaborate on what they do that's a good practice, and why.

Related

Which is framework is better for RAD - Corona, Actionscript, HTML5, Unity or Marmalade? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Before you condemn this as subjective, consider that there are differences between different frameworks. Writing something with PHP, I assume, is probably a lot less verbose and thus time consuming and expensive than writing it in binary. While the differences may not be as pronounced between the title options, I think there probably are significant differences which can result in, for example, a DoodleJump-type app taking more or less time to code in each.
Although there are other factors involved in choosing a framework, I'm just asking which one requires the least amount of coding and thus time and expense for equally skilled developers to accomplish the same thing (conjuring DoodleJump physics, a basic TicTacToe game, creating a UI, whatever). I'd appreciate links to sources if you have them, as well as direct experience comparing the verbosity of one or more in accomplishing the same task.
I'd most like to get an idea of how Flash and HTML5 compare to Corona (in terms of development time), but I'm also curious about the others.
Well you should seriously rephrase the question. It looks like subjective.
I'll just give my experience with all these tools.
Disclaimer:- The following review is my own personal opinion and involves my personal experience. You might have different opinion.
Marmalade
While I've used marmalade for most of my deployed projects, I've never used their RAD tool quick for any serious development. I was asked to try it out by remaking one of our deployed game. I was really impressed with it's quickness and less-verbosity. Although it was only for 2D and I recommended it's use over normal marmalade for all our 2D games. Unfortunately, we never made any 2D games after that. The benefit was that it comes preloaded with box2D and Cocos-2Dx and still supports C++ libraries. Didn't try EDK with it yet, but it should support that too. The con (for me) was I had to learn luascript for that.
Flash
Well I am not a flash expert here, but I tried it on two of our deployed game and it was a good one. Although it was too limited in what it seemed to have. We had to Re-code one of these games in marmlade, just to support some 3D elements, which were not possible to do in flash(at least for me). Flash was too verbose and too confusing for me, since we don't know where the actual script is attached. I guess it must have happened with all programmers who tried flash after trying any other tool, like marmalade. It just confuse you.
Unity
Well it was much much better than Flash, and is actually a well written game engine. Although it might cost a fortune for Indie developers, but still it's worth it. I've been using it for almost 4-5 months and I already started liking it over any other engine. It's easy to learn and too less verbose. You just need to drag and drop and attach the script to the gameobjects.(Not really that simple actually). No need to worry about Physics engine, no worries about plugins(since most of the plugins are already avaialable). And you can do 3D in that too.
Never tried Corona and HTML5 for any development project, so can't have a say in that.

Techniques or essentials skills required to read other persons code [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Currently I have started on very large Legacy Project and am in a situation which I always feared Reading and Understanding Other People's code, I have known that this is an essential skill which is required but haven't developed it as till date it was not required and now its like necessity to develop this skill rather than hobby and so I would like to know from SO Readers about:
How you have overcome the hurdle of reading other people's code ?
What techniques or skill have you developed to polish your art of reading and understanding other people code ?
Are there any books or articles which you have referred to or in general how did you developed the skill of reading and understanding other people's code ?
I would highly appreciate useful answers to this questions as now I can understand how one would feel while trying to understand my code.
Practice. Practice. Practice.
I overcame the hurdle by interacting with people on open-source projects. Discussing my contributions with others, and seeing their suggestions and ways of looking at things really opened my eyes.
I suggest you find a project that fits you, check out the source and contribute what you can (no matter how small to begin with). Over time the skill of reading code should just come naturally. Some projects even offer mentors specifically for helping out new contributors.
Michael Feathers' Working Effectively with Legacy Code is a great resource that contains a large number of techniques for working with older code.
Practice, Practice, Practice.
If you can, talk to whoever wrote the code or has an idea about it. Draw lots of pictures and have them explain big things to you while YOU write comments.
The quickest way to find your way around is to get lost. Dive into the code and break stuff. See if you can change an int into to a string or something.
Patience: Understand that reading code is more difficult than writing new code. Then you need to respect the code, even if it is not very readable, for it does its job and in many cases pretty efficiently. You need to give the code time and effort to understand it.
Understand the Architecture: It is best if there is any documentation on this. Try talking to people who know more about it if they are available.
Test it: You need to spend some time testing and debugging the code so you know what it does.
For those parts you understand, write some unit tests if possible so you can use them later.
Be Unassuming: Many times the names of the patterns are misused. The classes have names which do not indicate their purpose. So don't assume anything about them.
Learn Refactoring: The best book I found on this topic is Refactoring: Improving the Design of Existing Code - By Martin Fowler. Working Effectively with Legacy Code is another awesome one.
I don't know of any way to do it, i have participated in several proyects, where i have to undertand by my own, how do they think in and achieve that solution, so i can undertand it too.
That's why every time i can, i recommend, if you are a developer, try comment the code, all you can, because, you don't know if someone will find it useful (i think i make my point)
If you're not a developer, you should find someone to support you.
How do you learn to read what other people have written? You get really good at writing yourself and try to make sure the person is as good a writer as possible (suggest things they could do better, like adding some darn comments) Sadly, code is almost always read by someone else other than the author. Practice, and familiarity with some of the person's other code can help. But whenever you spend over 5 minutes figuring out what a particular line means, note how they could have done it better, and make sure you never make the same mistake.
good luck. :D
When I'm approaching an unfamiliar code base, I like to start at the beginning. Find main(), and write out a summary of what main() does. Create a list of the functions/methods called in main(). If you're visual, create a flowchart of main().
Once you have a list of the methods called directly from main(), look up those methods and repeat the process. As you figure out what each of those methods is doing, write it up in JavaDoc format and paste it into its corresponding box in the flowchart. If it's an API call, document which API it is using and put a link to the relevant API documentation.
Working recursively, you will create a map of the application and figure out what the program actually does. Once you know what it actually does, you will be able to find inconsistencies between what it does and what it's supposed to do.
The answer varies depending on the tools and documentation available.
If any documentation is available, I try to understand the high level overview of the system - the different modules, interfaces and subsystem interaction. This helps to divide and conquer the code into sizable pieces as you go along reading the code. If any design patterns are commonly used across the code try to build up your knowledge on that.
Also depending on the tools available I may use any of the popular source code browsers (Source Navigator/Source Insight) to quickly view the dependencies (class hierarchy etc). This speeds up code understanding. Also if I have some handy unit testing framework try playing with the code- different inputs and expected output. I also recommend using debugger to step through selected complex functions to get a hang of the code flow.

Has using an acknowledged anti-pattern ever been proven to actually solve a problem, or be beneficial in any other way? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Has using an acknowledged anti-pattern ever been proven to actually work in a certain specific case? Did you ever solve a problem or gain any kind of benefit in one of your projects by using an anti-pattern?
My understanding of the "anti-pattern" concept is that it encompasses solutions that have drawbacks that only reveal themselves over the long term. Indeed, the primary danger associated with a lot of them---like writing spaghetti code with loads of global variables and gotos every which way, or tossing exceptions into the black hole of an empty catch block---is that they're seductive because they provide an expedient solution to an immediate problem.
EDIT to add: Because of that, sometimes you do derive benefit from these anti-patterns. Sometimes your calculation that you're writing throwaway code that no one will touch again is dead wrong and you wind up with maintenance programmers slandering your heritage and sexual hygiene, but other times you're right and that crummy shell script that's held together with baling wire and spit does the job you intended it to do and is then blessedly forgotten, saving you the considerable time and effort of putting together something decent.
Anti-Patterns are still so widely around just because they solve a particular problem (while creating 10 new ones). Also known as workaround. But how do they say? Nothing lasts longer than a makeshift.
In fact I believe we'd all be jobless if things had been done right from the beginning.
The biggest problem that it has solved in my experience is launching a new application.
When the dev team has scoped the new application thouroughly, the timeline to implement the correct solution is usually too much for management to bear. Therefore, oftentimes, you code to meet the timeline, rather than "correctness" of the solution to get to the launch date, (but have others coding the "correct" solution for the next rev), making it essentially "throw-away" code.
One software anti-pattern is Softcoding, also defined at the daily WTF. Softcoding happens when programmers put material that "should be" inside code into external resources.
I'm working with software that some might say is suffering from softcoding. External files drive the software. Those external files are a micro-language: they must be compiled to XML before the software can use them. This micro-language has its own tools.
But softcoding is always in the mind of the beholder.
Having the material in a micro-language with its own parser has made my life easier. One data source can generate many different outputs: In addition to the version that the main program uses, I am able to extract information into HTML, .csv, and other formats that our customers want. Other programs can generate code in the micro-language, making automation easier.
In our case, softcoding has been a useful pattern, not an anti-pattern.
There is a reason for calling it a pattern rather than a law.
I would surmise that almost everyone has at least one example of a place in code where exactly the wrong thing was done, and it turned out better in the long term than the "right" thing would have.
And a far longer list of examples of anti-patterns causing trouble.
I have used magic pushbuttons a number of times, out of ignorance or laziness, and sometimes it actually worked out just fine, and it turned out that I did not need the extra abstraction of proper MVC.
Duff's Device utilizes the Loop-Switch Sequence (AKA For-Case Paradigm) anti-pattern.

How can I keep up with new technologies? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 13 years ago.
Duplicate:
Learning implementing design patterns for newbies
I have been a developer for years and have my way of developing and have always kept up with the latest techologies. I want to start using a design pattern in the hope it will improve my development speed but I need to find one to apply and I need to find a full open source sample that demonstrates it.
I use and have an application that uses LINQ to SQL and .net 3.5 I tried to apply the repository pattern but found the structure complex and having to hack my way through it.
Any advice for someone who wants to better their programming style?
Read blogs (RSS Feeds are prime). Read magazines. Read random MSDN entries. Write little trial applications. The only way to keep up is to discover it and practice it.
Patterns aren't really "tech" in the traditional sense. Using patterns means applying your specific knowledge of a domain to a problem keeping in mind the patterns which apply to that domain. They are useful to exactly the extent that you have a base of experience to put them in context.
The repository pattern, for example, is maybe not the best starting place for constructing a database architecture based on a pattern. Have you got a simpler pattern implemented such as Table Module or (in the specific case of data access) Active Record? If not then perhaps you should start there. These patterns focus on a fairly limited, basic way of organizing data and operations. Repository is more like a meta-pattern that then builds on top of these patterns, organizing a complex domain-data boundary into a simpler collection-like interface.
Two books that I would suggest reading are:
Refactoring: Improving the Design of Existing Code (ISBN: 0-201-48567-2)
and
Refactoring To Patterns (ISBN: 0-321-21335-1)
Both are great books that will help you, at a high level, understand the when's and why's to applying patterns to your code. In addition, they are great reference material for some of the most commonly used patterns out there.
To be clear, these books are by no means the "complete library" of design patterns.
My simple advice for bettering your programming style:
Pick a technology that you find productive and "fun" and keep with it to learn how to fully explore it's potential.
Don't try to learn all the new technologies all the time - just keep yourself oriented.
Seek advice and solutions where and when you actually need them - don't waste time learning solutions to problems you don't (yet) have.
Regarding design patterns... Well... I'll probably get shot for this, but I don't really like the idea of cramming them all into my head "just in case". They are really a cooking book of "good solutions" for common problems. My advice here is: Whenever you run into problems that you can't come up with an obvious/immediate solution for - use them as reference.
Learn from your mistakes (you'll make them).
Don't marry your code. Throw away and rewrite is an excellent way of bettering the style.
I would sincerely recommend dofactory.com
which also offers code examples in vb.net + c# for all the design patterns

Does Design By Contract Work For You? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach?
I came across the Design by Contract approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd.
I can't recommend it highly enough. It's particularly nice if you have a suite that takes inline documentation contract specifications, like so:
// #returns null iff x = 0
public foo(int x) {
...
}
and turns them into generated unit tests, like so:
public test_foo_returns_null_iff_x_equals_0() {
assertNull foo(0);
}
That way, you can actually see the tests you're running, but they're auto-generated. Generated tests shouldn't be checked into source control, by the way.
You really get to appreciate design by contract when you have an interface between to applications that have to talk to each other.
Without contracts this situation quickly becomes a game of blame tennis. The teams keep knocking accusations back and forth and huge amounts of time get wasted.
With a contract, the blame is clear.
Did the caller satisfy the preconditions? If not the client team need to fix it.
Given a valid request, did the receiver satisfy the post conditions? If not the server team need to fix that.
Did both parties adhere to the contract, but the result is unsatisfactory? The contract is insufficient and the issue needs to be escalated.
For this you don't need to have the contracts implemented in the form of assertions, you just need to make sure they are documented and agreed on by all parties.
If you look into STL, boost, MFC, ATL and many open source projects, you can see there are so many ASSERTION statements and that makes project going further more safely.
Design-By-Contract! It really works in real product.
Frank Krueger writes:
Gaius: A Null Pointer exception gets thrown for you automatically by the runtime, there is no benefit to testing that stuff in the function prologue.
I have two responses to this:
Null was just an example. For square(x), I'd want to test that the square root of the result is (approximately) the value of the parameter. For setters, I'd want to test that the value actually changed. For atomic operations, I'd want to check that all component operations succeeded or all failed (really one test for success and n tests for failure). For factory methods in weakly-typed languages, I want to check that the right kind of object is returned. The list goes on and on. Basically, anything that can be tested in one line of code is a very good candidate for a code contract in a prologue comment.
I disagree that you shouldn't test things because they generate runtime exceptions. If anything, you should test things that might generate runtime exceptions. I like runtime exceptions because they make the system fail fast, which helps debugging. But the null in the example was a result value for some possible input. There's an argument to be made for never returning null, but if you're going to, you should test it.
It's absolutely foolish to not design by contract when doing anything in an SOA realm, and it's always helpful if you're working on any sort of modular work, where bits & pieces might be swapped out later on, especially if any black boxen are involved.
In lieu of more expressive type systems, I would absolutely use design by contract on military grade projects.
For weakly typed languages or languages with dynamic scope (PHP, JavaScript), functional contracts are also very handy.
For everything else, I would toss it aside an rely upon beta testers and unit tests.
Gaius: A Null Pointer exception gets thrown for you automatically by the runtime, there is no benefit to testing that stuff in the function prologue. If you are more interested in documentation, then I would use annotations that can be used with static analyzers and the like (to make sure the code isn't breaking your annotations for example).
A stronger type system coupled with Design by Contract seems to be the way to go. Take a look at Spec# for an example:
The Spec# programming language. Spec#
is an extension of the object-oriented
language C#. It extends the type
system to include non-null types and
checked exceptions. It provides
method contracts in the form of pre-
and postconditions as well as object
invariants.
Both Unit testing and Design by Contract are valuable test approaches in my experince.
I have tried using Design by Contract in a System Automatic Testing framework and my experience is that is gives a flexibility and possibilities not easily obtained by unit testing. For example its possible to run longer sequence and verify that
the respons times are within limits every time an action is executed.
Looking at the presentations at InfoQ it appears that Design by contract is a valuable addition to the conventional Unit tests in the integration phase of components.
For example it possible to create a mock interface first and then use the component after-
or when a new version of a component is released.
I have not found a toolkit covering all my design requirement to design by contract testing
in the .Net/Microsoft platform.
I find it telling that Go programming language has no constructs that make design by contract possible. panic/defer/recover aren't exactly that as defer and recover logic make it possible to ignore panic, IOW to ignore broken contract. What's needed at very least is some form of unrecoverable panic, which is assert really. Or, at best, direct language support of design by contract constructs (pre and post-conditions, implementation and class invariants). But given strong-headedness of language purists at the helm of Go ship, I give little change of any of this done.
One can implement assert-like behaviour by checking for special assert error in last defer function in panicking function and calling runtime.Breakpoint() to dump stack during recovery. To be assert-like that behaviour needs to be conditional. Of course this approach fells apart when new defer function is added after the one doing assert. Which will happen in large project exactly at the wrong time, resulting in missed bugs.
My point is that is that assert is useful in so many ways that having to dance around it may be a headache.
I don't actually use Design by Contract, on a daily basis. I do, however know that it has been incorporated into the D language, as part of the language.
Yes, it does! Actually a few years ago, I designed a little framework for Argument Validation. I was doing a SOA project, in which the different back-end system, did all kind of validation and checking. But to increase response times (in cases where the input was invalid, and to reduce to load those back-end systems), we started to validate the input parameters of the provided services. Not only for Not Null, but also for String patterns. Or values from within sets. And also the cases where parameters had dependencies between them.
Now I realize we implemented at that time a small design by contract framework :)
Here is the link for those who are interested in the small Java Argument Validation framework. Which is implemented as plain Java solution.