答:
Just leave as soon as you can (maybe don't leave too soon as you don't want to look like a job hopper). The fact that they code is a mess and people are staying there means you are likely working with poor developers. Any decent developer who cares about their work wouldn't stay long working on such crap.

The chance of a rewrite occurring a pretty low unless you can very clearly demonstrate it will be worth the investment $$$ wise.

Title: What is the/Is there a right way to tell management that our code sucks?

Body:
Our code is bad. It might not have always been considered bad, but it is bad and is only going downhill. I started fresh out of college less than a year ago, and many of the things in our code puzzle me beyond belief. At first I figured that as the new guy I should keep my mouth shut until I learned a little more about our code base, but I've seen plenty to know that it's bad.

Some of the highlights:

We still use frames (try getting something out of a querystring, almost impossible)

VBScript

Source Safe

We 'use' .NET - by that I mean we have .net wrappers that call COM DLLs making it almost impossible to debug easily

Everything is basically one giant function

Code is not maintainable. Each page has multiple files that are created every time a new page is made. The main page basically does Response.Write() a bunch of times to render the HTML (runat="server"? no way). After that there can be a lot of logic on the client side (VBScript), and finally the page submits to itself (often time storing many things in hidden fields) where it then posts to a processing page which can do things such as save the data to the database.

The specifications we get are laughable. Often times they call for things like "auto-populate field X with either field Y or field Z" with no indication of when to choose field Y or field Z.

I'm sure some of this is a result of not being employed at a software company, but I feel as if people writing software should at least care about the quality of their code. I can't even imagine that if I were to bring something up that anything would be done soon, as there is a large deadline looming, but we are continuing to write bad code and use bad practices.

What can I do? How do I even bring these issues up? 75% of my team agree with me and have brought up these issues in the past, yet nothing gets changed.


问:
LINQ vs Data Access Layer
I've taught myself always to handle any data access code in a completely separate 'layer' to my business logic and UI code. This has always been a very good architecture for me and any 'rules' or best practices I see, still manage to fit into this style of coding, especially Single Responsibility Principle.

For most of my home projects, I'd use my own ORM I created, which I always intended to make open-source. However since then, LINQ became available, which was very similar to the way my ORM worked (but.. better).

There's nothing that I could previously do with my own ORM that I can't now do with LINQ (except bits of the REST integration). So my question is; is LINQ my new Data Access Layer? Do I need this layer at all anymore? Should my BLL just talk directly to LINQ? Or is this bad practice still?

Edit:

The original question was referring to LINQ to Entities, but there are many interesting answers regarding LINQ to SQL. What are peoples thoughts on both of them? I gather than LINQ to SQL can't really replace a DAL, but could the Entity Framework?

答: You could still have a DAL, only it could use LINQ to SQL instead of what you had previously used. That's how I do it anyway. Don't make your BLL directly use LINQ to SQL to access data.</p>

OwnerDisplayName: Connell Watkins

ContentLicense: CC BY-SA 3.0

Title: LINQ vs Data Access Layer

OwnerDisplayName: Niko Drašković


答:
Although you can just put LINQ queries in your BLL this may lead to code duplication. I would still create repositories that will be a wrapper to LINQ queries. This will separate Database code from BLL code and will be useful when you decide to modify your data access code (ie. move to Dapper, or to precompiled queries).

It will also help with unit testing, as repositories can be easily mocked.

Title: LINQ vs Data Access Layer

Body:
I've taught myself always to handle any data access code in a completely separate 'layer' to my business logic and UI code. This has always been a very good architecture for me and any 'rules' or best practices I see, still manage to fit into this style of coding, especially Single Responsibility Principle.

For most of my home projects, I'd use my own ORM I created, which I always intended to make open-source. However since then, LINQ became available, which was very similar to the way my ORM worked (but.. better).

There's nothing that I could previously do with my own ORM that I can't now do with LINQ (except bits of the REST integration). So my question is; is LINQ my new Data Access Layer? Do I need this layer at all anymore? Should my BLL just talk directly to LINQ? Or is this bad practice still?

Edit:

The original question was referring to LINQ to Entities, but there are many interesting answers regarding LINQ to SQL. What are peoples thoughts on both of them? I gather than LINQ to SQL can't really replace a DAL, but could the Entity Framework?

OwnerDisplayName: Jakub Konecki


答:
Linq is not about data access, you can use linq towards any IEnumerable.

Have you tried to design your application without thinking about the database at first? That is, implement your application and use some kind of repository. Then you use whatever technique to implement those repositories. That way you have a totally decoupled solution where you can plugin whatever data access layer you want.

In that data access layer you could use your own ORM or you could use Linq to sql, it doesn't matter as long as the data access layer implements the repositories you have defined.

Title: LINQ vs Data Access Layer

OwnerDisplayName: Tomas Jansson


答:
Unless you want your "business logic layer" to address transactions and query performance, there is still a need for a DAL.

LINQ makes query declaration a design-time (aka, compiler checked) process.

LINQ query providers (such as LinqToSql and LinqToEntities) still do run-time conversion of those declared queries to sql text.  Then the DBMS still does run-time query interpretation, run-time query plan generation etc.

These are just a small part of the DAL.

Title: LINQ vs Data Access Layer

OwnerDisplayName: David B


问:
Is Perl still a useful, viable language?
I know it may have been asked before, but here goes nothing...

Is Perl still something that would be considered useful? If someone was a new programmer (either completely new to programming or just a few month/years of experience) would Perl be something to be considered worthwhile to learn?

Is Perl still used with frequency? Is it still popular?

Or is Perl dying out compared to languages like Python, Ruby, PHP, ASP.NET, etc.?

Basically it boils down to this:

Is it still used/is it still used frequently? If yes, is it dying? If no, will it make a come back?

Is it something that would be worth learning?

How does it compare in demand to languages like Python in both popularity and usability/viability? Could languages like Python or Ruby be considered replacements for Perl?

Also, will newer versions of Perl really bring a large improvement to the Perl community, and perhaps bring Perl back to centerstage compared to other languages?

EDIT:

Okay, I suppose here's a better, reworded question:

Is Perl still growing, or is it "dying"? Is it still a language worth learning and using? What projects does it really "shine" in compared to other languages? What makes Perl a language to choose? Essentially: is Perl growing obsolete compared to other languages, and if so, do you expect that to change, or to continue?

And thank you to everyone who has answered so far, the discussion has been really interesting!

答:
Perl is THE language to write disposable tools. There are various other applications where Perl is more or less persistent and useful, but if you lack a shell command to do an odd thing, if you need a stub to grab some data from an odd socket, if you have a log file or a database and need to extract some content in a way that is outside of reach of SQL, if you need to pull a couple images from the server, or if your webpage templates all contain the same type of mistake and want to fix them all - whipping out a 10-minute Perl script is the way to go.

Writing the same thing in Shell would be likely possible but due to weird caveats of shell syntax, it will take longer and can be much harder. Writing this in any "professional" language like C++, C#, Java etc will take roughly a hour by comparison. Writing this in a competing scripting language like Python, Ruby or PHP is a viable alternative and will likely take up to 20% longer to write.

Yes, programs in other languages will be more maintainable and easier to read. But if you need a solution NOW, Perl is the way to go.


问:
What are combinators and how are they applied to programming projects? (practical explanation)
What are combinators?

I'm looking for:

a practical explanation

examples of how they are used

examples of how combinators improve the quality/generality of code

I'm not looking for:

explanations of combinators that don't help me get work done (such as the Y-combinator)

答:
It is wrong to brand Y-combinator as something that won't "help to get the work done". I've found it very useful in a number of occasions. The most obvious case is when you have to quickly bootstrap some embedded interpreted language. If you provide a minimal set of primitives, namely sequence, select, call, const and a closure allocation, it is already sufficient for building up a complete, arbitrary complex language. No special support for recursion is needed - it can be added via a fixed point combinator. Otherwise you'll need much more complicated primitives.

Another obvious case for combinators is obfuscation. A code translated into the SKI calculus is practically unreadable. If you really have to obfuscate an implementation of an algorithm, consider using combinators, here is an example.

And, of course, combinators are an important tool for implementing functional languages. The easiest approach (as in the example above) is via SKI or equivalent calculus. Supercombinators are used in some other implementations. This book talks about it in depth.

This is a joke, but a joke worth a very careful reading, since many arcane programming techniques and theories are covered there.


问:
Are there any studies on the relationship between software testing practices and developer productivity?
Are there any studies on the relationship between software testing practices (unit and/or integration tests) and developer productivity?</p>

答: Making Software: What Really Works, and Why We Believe It has a chapter on TDD (now TDD is not what you were asking for, but this is the only credible book I know of to mention unit-testing in any shape or form).


问:
How can I design test cases to cover code based on random events?
For example, if the code generates a random int from 0-10, and takes a different branch on each outcome, how can one design a test suite to guarantee 100% statement coverage in such code?

In Java, the code might be something like:

```<code>int i = new Random().nextInt(10);
switch(i)
{
    //11 case statements
}
</code>```

答: You can (should) wrap the random generation code in a class or method and then mock/override it during tests to set the value you want, so that your tests are predictable.</p>


问:
University teaches DOS-style C++, how to deal with it
I had been programming for many years but wanted a diploma to make myself more employable. Having already been through university once, I didn't choose a full 5 year computer science major but a shorter, more practically-oriented software engineering program.

I expected that it might focus more on concrete skills than on theory, but still had this idea that universities and professors like things to be correct, formal, academic. It's still science, right? Wrong - I was surprised by how sloppy many IT courses were.

In an introductory course on C++ we were tested on clichés like "why are globals bad" and "why are constants good", after just writing 1-2 programs. Random anecdotes without proper context. Handouts contained system(pause/cls), getch and headers like conio.h and iodos.h. One of the tasks was to print "ASCII characters" from 32 to 255, with a screenshot showing such a table printed using the Windows-1252 code page, but without mentioning encoding at all.

Question: when a university/professor seems to be using inferior and/or outdated tools and methods, and the content being taught is borderline incorrect, how do you deal with it constructively and respectfully, if at all?

Some answers point out that you should look beyond the programming since it is just a tool for learning about topics such as data structures and algorithms. I agree with this idea, but in this case there wasn't really any such plan behind the poor style. Most courses would simply teach another "tool" without much background theory or any "big picture". It often felt like they were quickly put together just for the sake of offering such a course.

I stuck with it and finally graduated. Quality remained pretty low throughout (with a few great exceptions), and several other students have been complaining about it. As expected I have learned much more from personal projects and part-time jobs than from school, however the process of finishing school and the label "software student" seem mysteriously useful in themselves!

答:
The universities are giving the foundations. Once it's strong, you can build skyscrapers on top of it.I have learned BASIC, C and C++ during my college days. Later when I did project in Visual C++, I believed it's an entirely different world. Later I realized the difference between Framework and Languages.

Choose a right university where they give the focused development of your desired computing field. Which can help you later in your career.

OwnerDisplayName: gaidal


答:
Math and programming are totally different things. Math is science, programming is technique. In academic world, programming is something you have to know so that you could deal with the real stuff, the one that's actually interesting and matters - algorithms.

Who cares if the compiler is ancient and you use system calls? Who cares if you have Linux and not Windows? Well, the professors don't, that's for sure. And they shouldn't, really. Don't expect to become a professional programmer from courses in the academic institution. That's not what you go there for.

That's true that the compiler he's expecting you to use is ancient, and the assumption about the OS is anachronistic, and its problematic. You can raise it, and maybe it will be dealt with. But not because the course is incompatible with the industry, but rather because it causes an immediate difficulty to the students. Go find that old compiler now and have it running on your MacBook...

In general, academic studies shouldn't be wasted on learning C++ and Android, you should be learning the actual Computer Science stuff there. You won't get another chance for that. Android? Download Eclipse with the ADT and start working on it at home, like I do. Don't need school for that.

I think that it is not OK to expect technique development from the universities. Especially not the research universities. You can say that a place that only offers bachelors should be more industry-targeted, but research universities - want researchers. The professors are looking for prospective graduate students and PhD candidates, not excellent programmers. So I think you should set your level of expectations accordingly.

Title: University teaches DOS-style C++, how to deal with it

Body:
I had been programming for many years but wanted a diploma to make myself more employable. Having already been through university once, I didn't choose a full 5 year computer science major but a shorter, more practically-oriented software engineering program.

I expected that it might focus more on concrete skills than on theory, but still had this idea that universities and professors like things to be correct, formal, academic. It's still science, right? Wrong - I was surprised by how sloppy many IT courses were.

In an introductory course on C++ we were tested on clichés like "why are globals bad" and "why are constants good", after just writing 1-2 programs. Random anecdotes without proper context. Handouts contained system(pause/cls), getch and headers like conio.h and iodos.h. One of the tasks was to print "ASCII characters" from 32 to 255, with a screenshot showing such a table printed using the Windows-1252 code page, but without mentioning encoding at all.

Question: when a university/professor seems to be using inferior and/or outdated tools and methods, and the content being taught is borderline incorrect, how do you deal with it constructively and respectfully, if at all?

Some answers point out that you should look beyond the programming since it is just a tool for learning about topics such as data structures and algorithms. I agree with this idea, but in this case there wasn't really any such plan behind the poor style. Most courses would simply teach another "tool" without much background theory or any "big picture". It often felt like they were quickly put together just for the sake of offering such a course.

I stuck with it and finally graduated. Quality remained pretty low throughout (with a few great exceptions), and several other students have been complaining about it. As expected I have learned much more from personal projects and part-time jobs than from school, however the process of finishing school and the label "software student" seem mysteriously useful in themselves!


答:
Well lot of universities have crappy programming professors. I went to one of the top grad schools in my country and pretty much learned squat in programming. I guess most unis are like that cause the really good programmers opt for better paying jobs(not teaching).
You should take up a small project and try to code it yourself. You can get tips from a lot of forums such as this one. That might be a better way to learn in the long run.</p>


答:
I would ask (and then insist) to return your assignments in standard c++.  This is entirely reasonable since you are unable to complete the assignments otherwise.

As for the bad style; there will inevitably be some of this to begin with.  Learning to use the standard io library properly requires quite a few advanced c++ features, in particular templates and iterators.  I can see why a lecturer would get you using very simple io functions to start with.  I wouldn't be afraid to ask about this though, it shows enthusiasm and a bit of light in your eyes.  Your lecturer should be able to weave your question into a future lecture where you (hopefully) put right your early exercises.

I would leave it at that though.  Even though c++ can be a platform independent language, it frequently isn't.  Learning some Windows system functions is not a bad thing, particularly if you then train yourself into doing it by the standard.  You will at some point come across conio.h when looking at other peoples code - and its good to know what it does.


问:
Joomla or development from scratch?
As someone who has very little experience in it, I would like to know what makes you think that Joomla can fulfill all you requirements?. What makes you choose it over development from scratch (or using a framework like Yii or Kohana).

What are the most common or crucial problem that you are facing when using Joomla? Since I don't have much experience in it, I would pressume that one of the biggest problem is flexibility. You can't scale or customize the behaviour of your app, and even if you could, you need to break some rule in Joomla, or wait for the next release. Is this true?.

Currently I am building a long term project, there might be a lot of specific functions and behaviours in it. I would like to build it from scratch or with help from some PHP frameworks. But I've seen so many websites (and some of them are great in terms of complexity) are using Joomla. This gave me some doubts about choosing the right tech.

I would like to know is there any, one or two ultimate reasons to choose Joomla/other.

答:
I was often asked about the big three CMS's and felt bad not having any answers, having never used any of them at all. Until about 1.5 years ago when I suddenly had no choice but to dive into Joomla 1.5.x.

Forget learning Joomla extension development by any other means than reading the source. I promise, if you stray from that rule then many moons will be lost.

Joomla doesn't help you with much (yes I'm aware of 1.7+, only talking about 1.5.x here). Don't expect any RAD features from Joomla, in fact you'll be writing all the HTML by hand, forms, tables, grids, filters, searches, yes all of it.

Joomla has 1 relational ORM type ability, JModel's canDelete method which can be specifically told what tables to check for records to return boolean "canDelete", that's all, you'll have to write all your ORM queries by hand.

Use JxExtractor (I think) to generate the required table schema files or manually modify the table files after any db schema change.

Joomla 1.5's ACL's are a lie, read that source code and you'll get it. Only wasted about a month assuming they were gonna be there once I needed them.

VirtueMart. Oh boy, umm. Quick, duck!  Whew. Close call.

JInstaller's purpose in life is failure and passing the buck, it complains about things unrelated to what's causing the failure, or at least complains in terms as cryptic as any girlfriend I've had. It's NEVER to be trusted, it lies, you're the fool if you lend it any credence!

Configuration over convention, or just general inconsistency throughout. GetVar(), get(),  getValue(), getConfig(),  getCfg(),  getParam(). Forget about guessing anything, ever, everything requires looking at the source/api.

There's at least 4 "ways" to build for Joomla, and they have nothing in common, save yourself the pain a just copy the com_weblinks component.

Joomla's a very sparse codebase. On one hand I like this about it, it's source is short and functional (albeit inept). If your coming from a framework, don't make the mistake of expecting anything like what frameworks offer, pretend your going back in time about 8 years, because you are.

Code generators. A must, Jacc in the extension directory is pretty nice.

Don't expect much help from the web, maybe I'm retarded but it appears that there's such a volume of cruft online for joomla that finding useful tutorials/guides/references is just another waste of time, read that source code friend.

Joomla isn't interested in documentation for developers, which sadly, makes sense in the end, since the codebase in so plain.

All in all, don't use Joomla CMS if your already familiar with higher order tools, or you may become suicidal and have 10 places high enough to jump from pinned on Google maps like I do.

P.s. Joomla 1.6 (1.7) improves on many of these short comings but it won't matter because getting client web stores (VM's) migrated to the 1.7 is a pipe dream, no matter how much I beg.

ContentLicense: CC BY-SA 2.5

Title: Joomla or development from scratch?


问:
Is C++ suitable as a first language?
A local college is teaching C++ to first year college students (16 years old) with no prior programming experience.

As first programming language, is C++ suitable?

答: Beginners need to appreciate 'programming' first. In my experience in training a class of beginners, they appreciated first what they understand the most.  Like Python vs. C# they appreciate Python because its very high level and does not use symbols like C# does, meaning very near to human language, its very English. So I would recommend to learn programming from high level to low level.</p>

Title: Is C++ suitable as a first language?


答:
Computer science is to programming what physics is to carpentry.

If you want to become a carpenter, studying physics is not going to make it happen. It will teach you a lot of interesting things, that you might be able to apply to your work, but it won't teach you how to be a good carpenter. For that, you will have to learn the craft of carpentry.

Similarly, if you want to become a good programmer, you will have to learn the craft of programming. Unfortunately, there's no institution to issue certification of any sorts. So basically, this is something you will have to do on your own, with whatever helping people you might be able to find. For you this means repetition and reflection. Write a lot of code and then come back to look at it. Also take time to read other people's code. Consider participating in open source projects.

Universities don't care much for programming and even less for details that will change within the next few years. What you see at your school is that they have picked some programming environment (a bad one, but that's not so important) and now show it to you, so that they will have a reference frame wherein they can teach you various programming techniques. One can argue, that the reference frame is poor and that even the language is a weird choice. From their perspective it probably doesn't matter, because it's quite arbitrarily chosen.


答: You've got a specified range (0-10), and a specified granularity (whole numbers). So when testing, you don't test with the random numbers. You test within a loop that hits each case in turn. I'd advise passing the random number into a sub-function containing the case statement, which allows you to just test the sub-function.</p>

Title: How can I design test cases to cover code based on random events?

Body:
For example, if the code generates a random int from 0-10, and takes a different branch on each outcome, how can one design a test suite to guarantee 100% statement coverage in such code?

In Java, the code might be something like:

```<code>int i = new Random().nextInt(10);
switch(i)
{
    //11 case statements
}
</code>```


问:
Where should I put my utility methods?
I am very new to Visual Studio and C# and am wondering how best to create a repository of sorts for utility methods.

For instance, we need a method that returns the current fiscal year and other company specific values.

Would it be best to create utility class file that is imported into every project? Or, create a new project with the these methods and add it to the current solution?

In python, for instance, I created an egg that has all the utility methods that I then install into the site-packages.

答: Don't forget its a Anti-Pattern. Therefore better to rethink about your solution http://lostechies.com/chrismissal/2009/06/01/anti-patterns-and-worst-practices-utils-class/</p>

Title: Where should I put my utility methods?


问:
How does a movie theater seat booking system prevent multiple users from reserving the same seats?
In the movie theatre I go to they have ticket kiosks that allow you to select the seats you want; they also have a website that does the same (the website also has a countdown timer of like 30 secs in which you must choose a seat).

While I understand things such as database transactions and other techniques for handling multiple simultaneous users, I just can't get my head around how multiple people can be allowed to select a seat at the same time; is it as simple as the first one to press BUY gets the seats and the other person will get an error message, or am I missing something?

答:
There are at least 2 business processes involved here.

Process one:

Show available seats.

Process two:

Book a selected seat.

Since these processes don't follow one another immoderately, and since 2 people may select the same seat the concurrency issue arises.

If your database design assigns the correct uniqueness constraint so that the combination of:

-TheaterID

-SeatID

-EventID

are unique, then the database will prevent duplicates.

The following scenario is also possible but will be taken care of by the above suggested implementation:

Assuming a grid view of available for a given theater and a given event can be displayed:

User1 displays available seats (and gets seats 1 and 2)

User2 displays available seats (and gets seats 1 and 2)

User1 talks a bit with the customer on the phone

User2 goes and books seat 2 for his customer

User1 tries to book seat 2 for his customer (because it shows as available on his screen)

The unique index prevents step 5 from commuting the data.

So all what you need to do may be nothing more correct database design and proper choice on constraints.

Other more complex approaches are possible if you want, using transaction queues. In this case, requests are written first to a queue then fires a process every n seconds but that is hardly necessary or practical in your case.

The really interesting part is what should the list grid for user 1 show?


答: How you can deal with it? Download programming e-books or streaming videos, try the examples by yourself. Do not depend on your professors. Programming is highly learned on your own.


问:
Is this a correct way to use nested classes to keep track of data?
I have some instruments. Each instrument should have a name (string) and description (string).

Each instrument can have some setups, which these setups are each a series of commands(string[] or List).

I want this class to be flexible so I can easily add or remove a whole instrument, or add or remove setups for any instrument that is existing in the class.

At the end, I want to save this class in properties of my assembly so each time the program starts it can be loaded. I am also thinking about serializing it and save it on disk for moving to another copy of the software.

So please let me know what you think about this approach and if you think this can be improved or even I should consider going with another way please let me know!

```<code>namespace MeasurementSuite
{
    /// <summary>
    /// Setups for all instruments
    /// </summary>
    public class Setups
    {
        /// <summary>
        /// An instrument
        /// </summary>
        public class Instrument
        {
            /// <summary>
            /// Name of the instrument
            /// </summary>
            public string Name { get; set; }
            /// <summary>
            /// Info about the instrument
            /// </summary>
            public string Info { get; set; }
            /// <summary>
            /// List of existing setups
            /// </summary>
            public List<Setup> SetupList { get; set; }

            /// <summary>
            /// Adds a setup to the instrument
            /// </summary>
            /// <param name="name"></param>
            /// <param name="commands"></param>
            private void AddSetup(string name, string[] commands)
            {
                this.SetupList.Add(new Setup(name, commands));
            }

            /// <summary>
            /// Removes a setup from the instrument
            /// </summary>
            /// <param name="name">Name of the setup</param>
            public void RemoveSetup(string name)
            {
                foreach (Setup setup in SetupList)
                {
                    if (setup.Name == name)
                    {
                        SetupList.Remove(setup);
                    }
                }
            }
        }

        /// <summary>
        /// Setup for a instrument
        /// </summary>
        public class Setup
        {
            /// <summary>
            /// Name of the setup
            /// </summary>
            public string Name { get; set; }
            /// <summary>
            /// Command sets for setup
            /// </summary>
            public string[] CommandSet { get; set; }

            /// <summary>
            /// Constructor
            /// </summary>
            /// <param name="name">Setup Name</param>
            /// <param name="commands">Setup Command sets</param>
            public Setup(string name, string[] commands)
            {
                this.Name = name;
                this.CommandSet = commands;
            }
        }
    }
}
</code>```

答:
Here's the harsh truth: It is probably not the right way to store it.

On the bright side: Nobody knows how to get it right until he has seen all possible use cases of that class. It looks ok, but you would have to see it 'in action' to judge it properly.

For now just go with it and refactor if you need to. The right design will probably emerge if you stick to the SOLID principles and constantly try to improve it. Keep this copy as a reference point, then come back in a couple of weeks and see which changes you made and if you could have predicted them.

The closest you'll ever get to getting it right is designing the whole system upfront, which raises a lot of other problems. This class itself without any context could be right, but also could be terribly wrong.

This is the programmers.stackexchange answer. If you want more details try codereview.stackexchange.


答:
The classic method to do this is to use a transactional database (so there's no clashes) and to do a tentative allocation of the seat to you that expires after some length of time (e.g., 10 minutes for kiosks) that gives you enough time to pay. If the (customer-visible) transaction falls through or times out, the seat allocation can be released back into the pool. (All state changes are processed via the transactional database, and one customer-visible transaction might require many database-level transactions.)

Airlines will use a similar system (though much more complex due to the need to handle multiple flight legs!) for booking seats online. I would imagine that the timeout would be considerably longer; airline tickets are usually booked further ahead than movie tickets, and are more expensive as well.

Title: How does a movie theater seat booking system prevent multiple users from reserving the same seats?

Body:
In the movie theatre I go to they have ticket kiosks that allow you to select the seats you want; they also have a website that does the same (the website also has a countdown timer of like 30 secs in which you must choose a seat).

While I understand things such as database transactions and other techniques for handling multiple simultaneous users, I just can't get my head around how multiple people can be allowed to select a seat at the same time; is it as simple as the first one to press BUY gets the seats and the other person will get an error message, or am I missing something?


问:
Why are wrapper classes not suited for use in callback frameworks?
I just read the question what are callback frameworks?, where the asker cites the following from Effective Java:

The disadvantages of wrapper classes are few. One caveat is that
  wrapper classes are not suited for use in callback frameworks, wherein
  objects pass selfreferences to other objects for subsequent
  invocations (“callbacks”).

So I am curious, why are wrapper classes not suited for use in callback frameworks? And can you provide an example of what the problem is?

答:
The next line of Effective Java is helpful in clarifying the issue:

"Because a wrapped object doesn't know of its wrapper, it passes a
  reference to itself(this) and callbacks elude the wrapper.  This is
  known as the SELF problem [Lieberman86]."

It seems like a trivial thing to make sure that all references to an object are via its wrapper, but wrappers are generally injected when a need arises and their design (their entire purpose of being) is to provide a low friction way to add more functionality to an existing class.  This leads to subtle bugs, like the wrapper missing the event.  Or the wrapper and wrapped object both registering for the same events - leading to duplicate processing and potential concurrency issues as well.  If you don't know (don't have the source code) where callbacks are registered, it may be impossible to work around this problem.  Additionally, wrappers are based on "pure" composition principles and callback frameworks force a "dirty" wrapper design.


问:
Does a time estimate equal a promise in Scrum?
If an estimate is not a promise then as a product owner how can I deliver my projects without knowing how long it will take?

Does a Scrum team work more efficiently if we treat time estimates as a promise?

How much research (preparation, effort to understand the problem) in a story is enough to come up the right estimate?

What about unexpected technical problems (problems that can really mess your initial estimates) that come up after you estimate your work?

答:
No.

The sum of all estimates on each completed task in a sprint is called velocity. Velocity is defined as "number of completed points per sprint" where 'point' is the unit your team estimates in.

So the velocity lets you know how much your team can produce in the next sprint, assuming they use the same method to estimate and the team is stable etc.

And that is how you can be quite sure what the team can deliver without having to make any random promises.

OwnerDisplayName: Preyash


答:
No, C++ is not suitable as a first language. As shown here, many professional programmers share this opinion, but this is also an opinion that professional teachers have.

Here is what a report from the dean of Carnegie Mellon University has to say about using C++ for an introductory course to programming for freshmen:

Standard languages such as C or C++ are not suitable for this course because their complexity and deficiencies impede both informal and mechanized reasoning techniques.

CMU offers two introductory courses, an imperative one and a functional one. SML was chosen for the functional programming. I don't know what was chosen for the imperative course, but the report mentions using a subset of C.

Title: Is C++ suitable as a first language?

Body:
A local college is teaching C++ to first year college students (16 years old) with no prior programming experience.

As first programming language, is C++ suitable?


答:
It goes with the database ACID property - Isolation. The database uses locks on the data to avoid concurrent modification of the data.

http://en.wikipedia.org/wiki/Isolation_%28database_systems%29


答:
Expanding David's answer whom I totally agree with that you should create a wrapper for Random. I wrote pretty much the same answer about it earlier in a similar question so here is a "Cliff's notes version" of it.

What you should do is to first create the wrapper as an interface (or abstract class):

```<code>public interface IRandomWrapper {
    int getInt();
}
</code>```

And the concrete class for this would look like this:

```<code>public RandomWrapper implements IRandomWrapper {

    private Random random;

    public RandomWrapper() {
        random = new Random();
    }

    public int getInt() {
        return random.nextInt(10);
    }

}
</code>```

Say your class is the following:

```<code>class MyClass {

    public void doSomething() {
        int i=new Random().nextInt(10)
        switch(i)
        {
            //11 case statements
        }
    }

}
</code>```

In order to use the IRandomWrapper correctly you need to modify your class to take it as a member (through constructor or a setter):

```<code>public class MyClass {

    private IRandomWrapper random = new RandomWrapper(); // default implementation

    public setRandomWrapper(IRandomWrapper random) {
        this.random = random;
    }

    public void doSomething() {
        int i = random.getInt();
        switch(i)
        {
            //11 case statements
        }
    }

}
</code>```

You can now test your class's behaviour with the wrapper, by mocking the wrapper. You can do this with a mocking framework, but this is easy to do by yourself as well:

```<code>public class MockedRandomWrapper implements IRandomWrapper {

   private int theInt;

   public MockedRandomWrapper(int theInt) {
       this.theInt = theInt;
   }

   public int getInt() {
       return theInt;
   }

}
</code>```

Since your class expects something that looks like an IRandomWrapper you can now use the mocked one to force the behaviour in your test. Here are some examples of JUnit tests:

```<code>@Test
public void testFirstSwitchStatement() {
    MyClass mc = new MyClass();
    IRandomWrapper random = new MockedRandomWrapper(0);
    mc.setRandomWrapper(random);

    mc.doSomething();

    // verify the behaviour for when random spits out zero
}

@Test
public void testFirstSwitchStatement() {
    MyClass mc = new MyClass();
    IRandomWrapper random = new MockedRandomWrapper(1);
    mc.setRandomWrapper(random);

    mc.doSomething();

    // verify the behaviour for when random spits out one
}
</code>```

Hope this helps.

Body:
Expanding David's answer whom I totally agree with that you should create a wrapper for Random. I wrote pretty much the same answer about it earlier in a similar question so here is a "Cliff's notes version" of it.

What you should do is to first create the wrapper as an interface (or abstract class):

public interface IRandomWrapper {
    int getInt();
}

And the concrete class for this would look like this:

public RandomWrapper implements IRandomWrapper {

    private Random random;

    public RandomWrapper() {
        random = new Random();
    }

    public int getInt() {
        return random.nextInt(10);
    }

}

Say your class is the following:

class MyClass {

    public void doSomething() {
        int i=new Random().nextInt(10)
        switch(i)
        {
            //11 case statements
        }
    }

}

In order to use the IRandomWrapper correctly you need to modify your class to take it as a member (through constructor or a setter):

public class MyClass {

    private IRandomWrapper random = new RandomWrapper(); // default implementation

    public setRandomWrapper(IRandomWrapper random) {
        this.random = random;
    }

    public void doSomething() {
        int i = random.getInt();
        switch(i)
        {
            //11 case statements
        }
    }

}

You can now test your class's behaviour with the wrapper, by mocking the wrapper. You can do this with a mocking framework, but this is easy to do by yourself as well:

public class MockedRandomWrapper implements IRandomWrapper {

   private int theInt;

   public MockedRandomWrapper(int theInt) {
       this.theInt = theInt;
   }

   public int getInt() {
       return theInt;
   }

}

Since your class expects something that looks like an IRandomWrapper you can now use the mocked one to force the behaviour in your test. Here are some examples of JUnit tests:

@Test
public void testFirstSwitchStatement() {
    MyClass mc = new MyClass();
    IRandomWrapper random = new MockedRandomWrapper(0);
    mc.setRandomWrapper(random);

    mc.doSomething();

    // verify the behaviour for when random spits out zero
}

@Test
public void testFirstSwitchStatement() {
    MyClass mc = new MyClass();
    IRandomWrapper random = new MockedRandomWrapper(1);
    mc.setRandomWrapper(random);

    mc.doSomething();

    // verify the behaviour for when random spits out one
}

Hope this helps.


问:
whole project of consuming web services with php
We are in the middle of a strange situation. We and a partner firm have to put up a web portal. They have a lot of functionality already done on their other portal and we are the managing firm on the project. But there are also some new development needed on their side which is designed by us. Strange thing is, we are going to do the GUI on the project and they will provide us some web services to gather data.

They are using .NET and we will be using PHP for the frontend project.

So what do you think that the best approach is to avoid communication and integration problems? For example

We provide them with just the view files and they do the rest all by themselves?

We develop a PHP project where we gather the required data using SOAP/REST web services?

Thanks in advance guys.

答:
I think you over simplified the descriptions of your ideas and thus, it is hard for me to understand what you actually meant by them. That being said, this is how I seem this all coming together.

You draft a communication api for their service. What the actual
transfer protocol is less important, focus on what the calls are and
the data structures needed.

Present the api to your partner. Come to an agreement and finalize the api and transfer protocol.

They are in charge of implementing the api and you are in charge of all the display work to present the data.

The benefit of the clearly defined api is that you can do your work before they deliver the service implementation. You can write tests that utilize a mock implementation to ensure that you are handling data correctly based on the defined api.

There are always going to be something that makes integration more interesting than you had hoped, but the clear division line and defined ways to cross that line allow you develop and test your code in an attempt to minimize the issues with integration.


问:
Licensing for a web based desktop application?
I have created a desktop application(winfoms) using C#.net 3.5, the application is an SEO application, so it has to be connected to the internet, i implemented a simple licensing routine where every time the application is started it will query the web service on my server with the key and machine hash to validate.

But recently i have noticed that some "crackers" have disabled the license verification (simply removed the lines of code that does that) of the application which i have obfuscated, and the sad thing is that they are selling it at a cost that is only 10% of what i am selling for, they didn't even bother to remove my website address and company details from the about box. The application is having an auto-update feature, which they so-called crackers have intentionally left it on in the cracked version

I was just trying to figure out a way out of this, i can release an update and disable all the versions that are brought from the crackers, but without a proper licensing it will broken again and the next time, i don't have the guarantee that they will keep the auto update feature on.

答:
There is no sure way of preventing this. What you really want to aim for is to make it take longer or be more hassle to "hack" your software than it is to just buy it from you.

Or, seeing as your application always has to be connected to the web you could implement a user login system, whereby everyone who purchases your software gets a username and a password that verifies itself to your server every time the application loads.

You can make it so that a particular username and password combination can only be logged in in one place at any particular time.

If you have ever used Steam, this is basically what it does.

It won't prevent someone distributing their username and password but if they are continually kicked off whenever someone else is using the same one it'll get annoying.

That being said, I am no lawyer and I am not sure if there are legal issues around calling home with a username and password every time the application launches. I assume you'd have to clearly tell your user that they must agree to this else the software doesn't work, but it's best looking into that. (You're probably fine given that you already query a web service every time the application loads).

As for forcing an update, I am not sure. You may just have to cut your losses and release all future versions with a new system.

OwnerDisplayName: Vamsi Krishna

OwnerDisplayName: AndyC


答:
Use QuickCheck! I just started playing with this recently and it is amazing. Like most cool ideas it comes from Haskell but the basic idea is that instead of giving your test pre canned test cases you let your random number generator build them for you. That way instead of the 4-6 cases that you would probably come up with in xUnit you can have the computer try hundreds or thousands of inputs and see which ones don't conform to the rules you have set.

Also QuickCheck will when it finds a failing case try to simplify it so that it can find the simplest possible case that does fail. (And of course when you do find a failing case you can then build it into a xUnit test as well)

There appear to be at least two versions for Java so that part should not be a problem.


问:
Age of Design Patterns
When did these design patterns originate? Balking, Builder, Delegation, Facade, Memento. I have looked for days across the net, so if someone points me to a simple google search I may shoot myself. The real question I have is only which is the oldest and which is the youngest, so the specific dates for each are not important.

I have already found that the Balking pattern originated in 2002.

答:
All but the Balking pattern are all GoF (Gang of Four) Patterns that were released in a single book.

Design Patterns: Elements of Reusable Object-Oriented Software

Title: Age of Design Patterns

OwnerDisplayName: Justin Niessner


答: Patterns originated as an architectural concept by Christopher Alexander (1977/79). See history section of the article about Design Patterns in Wikipedia.</p>

Title: Age of Design Patterns

Body:
When did these design patterns originate? Balking, Builder, Delegation, Facade, Memento. I have looked for days across the net, so if someone points me to a simple google search I may shoot myself. The real question I have is only which is the oldest and which is the youngest, so the specific dates for each are not important.

I have already found that the Balking pattern originated in 2002.


答:
Unfortunately, as long as it is a client application, you will probably have to spend considerable time trying to stay ahead of the 'crackers'.

To get around this, one method would be to move some of the 'business logic' of the application on to your own servers. So for some functionality, it has to call your server (with licensing details) to calculate the result. This would help stop them from being able to circumvent licensing.

Obviously that means it is more expensive running costs for you per user.

If they is completely out of the option, try the following approach:

Have core parameters used in your application stored server side. The each time the application is opened, as part of the licensing check, return these core parameters used by the system.

I'm sure you get the idea here. You have to have something on your servers that the application needs to run to stop crackers from simply disabling authorization.

Title: Licensing for a web based desktop application?

Body:
I have created a desktop application(winfoms) using C#.net 3.5, the application is an SEO application, so it has to be connected to the internet, i implemented a simple licensing routine where every time the application is started it will query the web service on my server with the key and machine hash to validate.

But recently i have noticed that some "crackers" have disabled the license verification (simply removed the lines of code that does that) of the application which i have obfuscated, and the sad thing is that they are selling it at a cost that is only 10% of what i am selling for, they didn't even bother to remove my website address and company details from the about box. The application is having an auto-update feature, which they so-called crackers have intentionally left it on in the cracked version

I was just trying to figure out a way out of this, i can release an update and disable all the versions that are brought from the crackers, but without a proper licensing it will broken again and the next time, i don't have the guarantee that they will keep the auto update feature on.


问:
How many are too many interfaces on a class?
I would probably consider it a code smell or even an anti-pattern to have a class that implements 23 interfaces. If it is indeed an anti-pattern, what would you call it? Or is it simply just not following the Single responsibility principle?</p>

答: I submit that this anti-pattern be named Jack of All Trades, or perhaps Too Many Hats.</p>


问:
Can freelancers ask their client to sponsor an iPad for project needs?
I do freelance web projects for a client.  The client has been asking me to buy an iPad for testing purposes. Should I ask him to get me an iPad ?

I otherwise don't have any need for the iPad. Is it ethical to ask for sponsorship when you are getting paid for the projects ? Should I try it out ?

答: I'd say that it is 100% ethical, and yes, I would ask my client to supply me with any non-standard tools that are required for a project. I would also say that the client has every right to ask for the tools to be returned to them at the conclusion of the project.</p>


答:
It's doubtful. Would you return the iPad to the client after the project is complete? Is it only for this client and this client only, and you do not see a future use for the iPad? If so, you might have a case, because this is a special request from a single client.

However, if you plan to keep the iPad or use it for other clients, you should not ask for one. Because then it is a tool of the trade, and as Craige points out, you wouldn't ask them to buy you a new computer.

Title: Can freelancers ask their client to sponsor an iPad for project needs?

Body:
I do freelance web projects for a client.  The client has been asking me to buy an iPad for testing purposes. Should I ask him to get me an iPad ?

I otherwise don't have any need for the iPad. Is it ethical to ask for sponsorship when you are getting paid for the projects ? Should I try it out ?


答:
I would first determine the contract indicates if the web application would support iOS devices.  If it does then this really should have been something you talked about before you agreed upon the price on the contract.

If you do not have a contract, then refuse to test it on iOS devices, unless they are willing to purchase said device.  You could of course tell them as Adam suggested, burrow one from them, and return it to them when the project is completed.


答:
As a freelance web developer, you should have this tool your toolkit already.

We are quickly moving into a mobile age, and you should be able to test on mobile platforms; this is part of your job as a developer.

-- Edit --

I don't believe it is the clients responsibility to purchase any of your tools for you, unless it is an extremely rare tool which you could never use again, in which case this requirement should be negotiated in the initial contract.

I see this as akin to buying the tools for the contractor(s) building your house. Would you like to pay extra thousands of dollars to outfit them with basic tools of the trade, such as hammers and drills?


答: If an iPad is a new requirement your client should be paying for the extra testing and your fee should reflect that. You can ask the client for one to use for their project but if this is an ongoing need you will need to work the cost of hardware into your pricing.</p>


答:
the problem is that there will be too much data to be handled by the
  server, as the application has already reached more than 500 users and
  the data each user processes is more than 5 MB per request and there
  are like 15 request by user on an average day

Considering the size of your requests, adding a few dozen more characters to each request for a license key will have nearly zero cost. Indeed, if you're not already including some identifier that links each request to the user, you probably should be. You don't tell us what your app does, but perhaps adding such an identifier would let you store more data on your server, which might significantly reduce the amount of data that you need to transfer with each request.


答: Can you borrow/lease one for testing purposes instead of buying it?</p>


答:
In your next update, if it's pushed down to the cracked versions automatically, add an update to the app that alerts the users that they bought a cracked version.

Inform them their copy is illegal, and will be disabled in X days.  Don't leave them out in the cold.  Offer a discounted rate to get a valid copy.  Something like 50%.  Entice them to become your customers.

By offering a discount, and not just shutting them down the users will hopefully take it as a sign of good faith, and switch.  Some won't.

However, their software is updating through you, so you have more control than the crackers, and they aren't going to keep buying it from them, nor get support.  They will realize if it's a worthy product, they are better getting it from you.

As for preventing future purchases from crackers. Try and sneak in some 'unique' code into each version downloaded.  That way you can determine which person is buying your software and reselling it.  IANAL, so consult one, but it would aid the authorities if you chose legal action.

Also, improve your authentication verification in the next version.  Leave parts of the app out, and require that they be downloaded at login.  Have some files encrypted, and require they go to your server to be decrypted.  The more you make the crackers have to do, to crack, the better.


问:
Why are brackets required for try-catch?
In various languages (Java at least, think also C#?) you can do things like

```<code>if( condition )
    singleStatement;

while( condition )
    singleStatement;

for( var; condition; increment )
    singleStatement;
</code>```

So when I have just one statement, I don't need to add a new scope with { }. Why can't I do this with try-catch?

```<code>try
    singleStatement;
catch(Exception e)
    singleStatement;
</code>```

Is there something special about try-catch which requires always having a new scope or something? And if so, couldn't the compiler fix that?

答: I think the main reason is that there is very little you can do in C# that would need a try/catch block that is only one line. (I can't think of any right now of the top of my head).  You may have a valid point in terms of the catch block, e.g a one line statement to log something but in terms of readability it makes more sense (at least to me) to require {}.</p>


答:
My suggestion may sound out there, but hear me out... Switch majors.

In my experience in academia, the Computer Science major was a very low-level look at what makes computers tick. You started with a basic primer in C++ to make sure you know what a program was, and the basics of the memory and computation behind the program, and then you learned assembly, OS concepts, electrical engineering, digital design, etc etc. You get this degree and look for work with NVidia or AMD, or Lockheed; somewhere where they're making new hardware, which needs someone who can understand that hardware on a low-enough level to write the drivers and control software.

It sounds like what you want is a course of study that, at my university, was called Management of Information Systems. That's the course I followed; it taught programming in Java, VB.NET, C#, and some PHP and other web scripting along the way. It also required calculus (but not to the same degree as CS), accounting, finance, stats, business communication, O-O A&D, database design, and systems analysis. I got a BBA instead of a BS, and I had the basic tools to start work as a Windows or Web software developer.

What the "Computer Science" major prepares you to do depends highly on which university is offering it. It sounds like you're on an early path to get a very anachronistic, low-level look at computers that doesn't sound like what you're after out of your education. I urge you to look around in the university and find a course of study that's more focused on the type of computer work you'll want to get into after school.

No matter what, your course of study is going to start at very basic, "console-level" program writing. The language doesn't matter; what they're teaching you is basic procedural programming; how to think in small enough steps that the computer can follow you from step to step (because the computer takes nothing for granted, and can't follow most of a human's leaps in logic). From there, you will progress to object-oriented programming (instead of having one long function that does everything, it's much more maintainable to have several smaller code "objects", which represent the state and logic of real-world objects), then to event-driven programming ("Don't call us, we'll call you"; your program basically starts up, tells the OS to set up your initial graphic UI, and then sits and waits for the OS to pass in user input via a message loop), etc etc.


答:
The God Object comes to mind; a single object that knows how to do EVERYTHING. This comes from low adherence to the "cohesion" requirements of the two major design methodologies; if you have an object with 23 interfaces, you have an object that knows how to be 23 different things to its users, and those 23 different things are likely not along the lines of a single task or area of the system.

In SOLID, while the creator of this object has obviously tried to follow the Interface Segregation Principle, they have violated a prior rule; Single Responsibility Principle. There's a reason it's "SOLID"; S always comes first when thinking about design, and all the other rules follow.

In GRASP, the creator of such a class has neglected the "High Cohesion" rule; GRASP, unlike SOLID, teaches that an object doesn't HAVE to have a single responsibility, but at most it should have two or three very closely related responsibilities.

Title: How many are too many interfaces on a class?

Body: I would probably consider it a code smell or even an anti-pattern to have a class that implements 23 interfaces. If it is indeed an anti-pattern, what would you call it? Or is it simply just not following the Single responsibility principle?</p>


答:
Nested Classes to create private classes is NOT bad. In fact that is a good thing to make the classes not visible to outside world. But for this, they should must be private.

However, as per your above code, these classes are public so they become visible to rest of the application. Such things has no special value except that class hierarchy really have special connotations.

Such a thing is good only if they are followed based on a well established model from the real world, but it can become mess if this is done for programmer's convenience.

The other non-functional but very critical difference is, that Nested Classes declaration makes the Code very unreadable often because of a lot of hierarchy. To help that you should declare methods there, but implement them outside in the .cpp file separately.

Dipan.

Title: Is this a correct way to use nested classes to keep track of data?

Body:
I have some instruments. Each instrument should have a name (string) and description (string).

Each instrument can have some setups, which these setups are each a series of commands(string[] or List).

I want this class to be flexible so I can easily add or remove a whole instrument, or add or remove setups for any instrument that is existing in the class.

At the end, I want to save this class in properties of my assembly so each time the program starts it can be loaded. I am also thinking about serializing it and save it on disk for moving to another copy of the software.

So please let me know what you think about this approach and if you think this can be improved or even I should consider going with another way please let me know!

```<code>namespace MeasurementSuite
{
    /// <summary>
    /// Setups for all instruments
    /// </summary>
    public class Setups
    {
        /// <summary>
        /// An instrument
        /// </summary>
        public class Instrument
        {
            /// <summary>
            /// Name of the instrument
            /// </summary>
            public string Name { get; set; }
            /// <summary>
            /// Info about the instrument
            /// </summary>
            public string Info { get; set; }
            /// <summary>
            /// List of existing setups
            /// </summary>
            public List<Setup> SetupList { get; set; }

            /// <summary>
            /// Adds a setup to the instrument
            /// </summary>
            /// <param name="name"></param>
            /// <param name="commands"></param>
            private void AddSetup(string name, string[] commands)
            {
                this.SetupList.Add(new Setup(name, commands));
            }

            /// <summary>
            /// Removes a setup from the instrument
            /// </summary>
            /// <param name="name">Name of the setup</param>
            public void RemoveSetup(string name)
            {
                foreach (Setup setup in SetupList)
                {
                    if (setup.Name == name)
                    {
                        SetupList.Remove(setup);
                    }
                }
            }
        }

        /// <summary>
        /// Setup for a instrument
        /// </summary>
        public class Setup
        {
            /// <summary>
            /// Name of the setup
            /// </summary>
            public string Name { get; set; }
            /// <summary>
            /// Command sets for setup
            /// </summary>
            public string[] CommandSet { get; set; }

            /// <summary>
            /// Constructor
            /// </summary>
            /// <param name="name">Setup Name</param>
            /// <param name="commands">Setup Command sets</param>
            public Setup(string name, string[] commands)
            {
                this.Name = name;
                this.CommandSet = commands;
            }
        }
    }
}
</code>```


问:
Steps towards TDD
I need some advice to take the steps for TDD. How do we think in terms of interfaces for everything when we are writing code? Most of the testing books tell you how to write tests. But I want a book which tells whats the good way to write code in terms of TDD</p>

答:
One of the biggest ways to make your code testable is to use Dependency Injection. This allows you to have a default implementation of the programming logic, but then when you go to test, you can mock that implementation in order to facilitate the tests.

```<code>public interface Model {
  //methods
}
public class DefaultModel : Model {
  //default implementation
}
public class Worker {
  private Model _model;
  public Worker(Model model) {
    _model = model;
  }

  public void DoSomething() {
    var result = _model.Action();
    //...
  }
}

//real code
Worker worker = new Worker(new DefaultModel());

//test code
public class TestModel : Model {
  //code for testing
}
Worker worker = new Worker(new TestModel());
//do testing of worker
</code>```

Following this model, you can test Worker without needing the real implementation of DefaultModel and things it might depend on. You would then have separate tests to ensure DefaultModel is correct.

Here is a tech talk that is about writing testable code. I haven't watched it, but I've seen one given by the same guy. I just couldn't find a link for the one I watched.

Title: Steps towards TDD

Body:
One of the biggest ways to make your code testable is to use Dependency Injection. This allows you to have a default implementation of the programming logic, but then when you go to test, you can mock that implementation in order to facilitate the tests.

public interface Model {
  //methods
}
public class DefaultModel : Model {
  //default implementation
}
public class Worker {
  private Model _model;
  public Worker(Model model) {
    _model = model;
  }

  public void DoSomething() {
    var result = _model.Action();
    //...
  }
}

//real code
Worker worker = new Worker(new DefaultModel());

//test code
public class TestModel : Model {
  //code for testing
}
Worker worker = new Worker(new TestModel());
//do testing of worker

Following this model, you can test Worker without needing the real implementation of DefaultModel and things it might depend on. You would then have separate tests to ensure DefaultModel is correct.

Here is a tech talk that is about writing testable code. I haven't watched it, but I've seen one given by the same guy. I just couldn't find a link for the one I watched.


答:
I think it's to avoid dangling else style issues.  The following would be ambiguous...

```<code>try
    // Do stuff
try
    // Do  more stuff
catch(MyException1 e1)
    // Handle fist exception
catch(MyException2 e2)
    // So which try does this catch belong to?
finally
    // and who does this finally block belong to?
</code>```

It could mean this:

```<code>try {
   try {

   } catch(Exception e1) {

   } catch(Exception e2) {

   }
} finally {

}
</code>```

Or...

```<code>try {
   try {

   } catch(Exception e1) {

   }
} catch(Exception e2) {

} finally {

}
</code>```

Title: Why are brackets required for try-catch?

Body:
In various languages (Java at least, think also C#?) you can do things like

```<code>if( condition )
    singleStatement;

while( condition )
    singleStatement;

for( var; condition; increment )
    singleStatement;
</code>```

So when I have just one statement, I don't need to add a new scope with { }. Why can't I do this with try-catch?

```<code>try
    singleStatement;
catch(Exception e)
    singleStatement;
</code>```

Is there something special about try-catch which requires always having a new scope or something? And if so, couldn't the compiler fix that?

Body:
I think it's to avoid dangling else style issues.  The following would be ambiguous...

try
    // Do stuff
try
    // Do  more stuff
catch(MyException1 e1)
    // Handle fist exception
catch(MyException2 e2)
    // So which try does this catch belong to?
finally
    // and who does this finally block belong to?

It could mean this:

try {
   try {

   } catch(Exception e1) {

   } catch(Exception e2) {

   }
} finally {

}

Or...

try {
   try {

   } catch(Exception e1) {

   }
} catch(Exception e2) {

} finally {

}


答:
The principles of TDD are inherent in its name. The very first thing to keep in mind is, test first.

When you write a test that will exercise a new, previously unwritten object or method, you are basically defining the usage (translated: interface) for that new piece of code. That forces you to examine how you will want to use this code, which is critical to good design.

TDD also encourages a Single-Responsibility way of thinking. You need a new piece of functionality that will run every minute, get some data from the DB, perform some arbitrarily-complex calculation, then write the result back to the DB. Well, the first thing you need is code that will run every minute. So you create a Timer. Then, the timer needs to get something from the DB. That sounds like its own responsibility, so you mock out the use of some DB reader object. That forces you to think of how you want to use THAT object. This inherently-recursive system of defining the usage of something new before you define that something new generally leads to making decent, or at least easily-refactorable, design decisions.

As far as strictly thinking about interfaces, that's not really TDD, that's just "SOLID" design, specifically adherence to the "Dependency Inversion Principle" (stated succinctly, "classes should always depend upon abstractions, never upon other concrete classes"). If your class BusinessLogicObject requires code to write to the DB, it should never be dependent upon a concrete class DBWriter, but instead upon an IDBWriter. This promotes "loose coupling"; that way, if down the line you wanted to swap DBWriter for BetterDBWriter, then as long as BetterDBWriter implemented the same IDBWriter interface, you wouldn't have to change BusinessLogicClass to create or work with BetterDBWriter.

Title: Steps towards TDD

Body: I need some advice to take the steps for TDD. How do we think in terms of interfaces for everything when we are writing code? Most of the testing books tell you how to write tests. But I want a book which tells whats the good way to write code in terms of TDD</p>


答: Royal Family: They don't do anything particularly crazy but they have a billion titles and are related to most other royals somehow.</p>


答:
Since you're on .NET you might want to watch DNRTV with the early episodes on TDD to get a good overview of that (and get a glimpse of the the MVC pattern).

DNRTV - JP Boodhoo on TDD Part 1 of 2 | (alt. link)

DNRTV - JP Boodhoo on TDD Part 2 of 2 | (alt. link)

JP Boodhoo goes through TDD quite clearly together with the concept of interfaces and dependency injection in those videos and at least helped me get a groove on how to do it.

Title: Steps towards TDD


答:
In my humble opinion you need several skills before you can become good at TDD.

First you need an understanding on how to build SOLID code, Agile Principles, Patterns, and Practices in C# (Robert C. Martin)  is great for that. A short introduction is on DimeCast.

You also need Unit test knowledge

an introduction : The Art of unit testing

the bible : XUnit Test Patterns

Than TDD knowledge:

TDD by example

Growing Object-Oriented Software, Guided by Tests

And than you have read all the necessary knowledge and you need to make a mind shift. And the only way I know on how to do that is just by doing. Getting a coach would be great. Also to get a feeling for how the process might work you could watch James Shore's "Lets play TDD" 140+ screencasts.

Title: Steps towards TDD


问:
The dreaded C# programming interview test - any advice?
I have a possible C# dev job lined up but before I can interview, I need to pass a test with the employment agency.

Now even though I am a senior developer with over 10 years of programming experience and more than 3 of these years with c#, I am really not looking forward to this test and I think there is a good chance I will fail it.

In my experience these tests are unpredictable asking you stuff you seldom use in everyday work situations.

I need your best advice on what I should be revising on - a good book or website for example. I have less than 1 week to prepare and it is essential I pass this.

Thanks in advance.

EDIT: To further justify my concerns of writing such tests - Consider the following question:

12) An Event is :

```<code>   a) The result of a users action - correct answer
   b) The esult of a party
   c) code to force users action
</code>```

The correct answer according to the test is A, but since I've been doing SOA development (often when events can be based on system events (not user actions) I'm 100% sure an event doesn't have to be driven by a user action. This was also a C# question (not an ASP.net question). Based on my understanding, I couldn't really spot a correct answer but B seems the best of the lot (if the definition of party is : any entity that can trigger an event.
These kind of questions scare me.

答:
I totally agree with you on:

tests are unpredictable asking you stuff you seldom use in everyday
  work situations.

..but they are part of the process, so there's nothing we can really do about it.
I am somthing like you with about 10 years experience of which about 5 in .NET C#.
I found these that these two VERY good books:

C# in Depth

C# in a Nutshell

should cover everything you need to know about C#.
The rest is your own skills and skills that you pick up on specific technologies based on C# like ASP.NET etc.


答:
Altough somewhat old, maybe this blog post is useful for you: What Great .NET Developers Ought To Know (More .NET Interview Questions)

Everyone who writes code

Describe the difference between a Thread and a Process?

What is a Windows Service and how does its lifecycle differ from a "standard" EXE?

What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?

What is the difference between an EXE and a DLL?

What is strong-typing versus weak-typing? Which is preferred? Why?

Corillian's product is a "Component Container." Name at least 3 component containers that ship now with the Windows Server Family.

What is a PID? How is it useful when troubleshooting a system?

How many processes can listen on a single TCP/IP port?

What is the GAC? What problem does it solve?

Mid-Level .NET Developer

Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.

Describe what an Interface is and how it’s different from a Class.

What is Reflection?

What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?

Are the type system represented by XmlSchema and the CLS isomorphic?

Conceptually, what is the difference between early-binding and late-binding?

Is using Assembly.Load a static reference or dynamic reference?

When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?

What is an Asssembly Qualified Name? Is it a filename? How is it different?

Is this valid? Assembly.Load("foo.dll");

How is a strongly-named assembly different from one that isn’t strongly-named?

Can DateTimes be null?

What is the JIT? What is NGEN? What are limitations and benefits of each?

How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?

What is the difference between Finalize() and Dispose()?

How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?

What does this useful command line do? tasklist /m "mscor*"

What is the difference between in-proc and out-of-proc?

What technology enables out-of-proc communication in .NET?

When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?

Senior Developers/Architects

What’s wrong with a line like this? DateTime.Parse(myString);

What are PDBs? Where must they be located for debugging to work?

What is cyclomatic complexity and why is it important?

Write a standard lock() plus “double check” to create a critical section around a variable access.

What is FullTrust? Do GAC’ed assemblies have FullTrust?

What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?

What does this do? gacutil /l | find /i "Corillian"

What does this do? sn -t foo.dll

What ports must be open for DCOM over a firewall? What is the purpose of Port 135?

Contrast OOP and SOA. What are tenets of each?

How does the XmlSerializer work? What ACL permissions does a process using it require?

Why is catch(Exception) almost always a bad idea?

What is the difference between Debug.Write and Trace.Write? When should each be used?

What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?

Does JITting occur per-assembly or per-method? How does this affect the working set?

Contrast the use of an abstract base class against an interface?

What is the difference between a.Equals(b) and a == b?

In the context of a comparison, what is object identity versus object equivalence?

How would one do a deep copy in .NET?

Explain current thinking around IClonable.

What is boxing?

Is string a value type or a reference type?

What is the significance of the "PropertySpecified" pattern used by the XmlSerializer? What problem does it attempt to solve?

Why are out parameters a bad idea in .NET? Are they?

Can attributes be placed on specific parameters to a method? Why is this useful?

C# Component Developers

Juxtapose the use of override with new. What is shadowing?

Explain the use of virtual, sealed, override, and abstract.

Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d

Explain the differences between public, protected, private and internal.

What benefit do you get from using a Primary Interop Assembly (PIA)?

By what mechanism does NUnit know what methods to test?

What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;}

What is the difference between typeof(foo) and myFoo.GetType()?

Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?

What is this? Can this be used within a static method?

ASP.NET (UI) Developers

Describe how a browser-based Form POST becomes a Server-Side event like Button1_OnClick...

Title: The dreaded C# programming interview test - any advice?

Body:
I have a possible C# dev job lined up but before I can interview, I need to pass a test with the employment agency.

Now even though I am a senior developer with over 10 years of programming experience and more than 3 of these years with c#, I am really not looking forward to this test and I think there is a good chance I will fail it.

In my experience these tests are unpredictable asking you stuff you seldom use in everyday work situations.

I need your best advice on what I should be revising on - a good book or website for example. I have less than 1 week to prepare and it is essential I pass this.

Thanks in advance.

EDIT: To further justify my concerns of writing such tests - Consider the following question:

12) An Event is :

```<code>   a) The result of a users action - correct answer
   b) The esult of a party
   c) code to force users action
</code>```

The correct answer according to the test is A, but since I've been doing SOA development (often when events can be based on system events (not user actions) I'm 100% sure an event doesn't have to be driven by a user action. This was also a C# question (not an ASP.net question). Based on my understanding, I couldn't really spot a correct answer but B seems the best of the lot (if the definition of party is : any entity that can trigger an event.
These kind of questions scare me.


问:
Approach to a programming task
All,

Given a problem statement, when I start of with the analysis and design, I tend to think too much about the various functionalities associated with the task (sometimes not even mentioned in the task). My point is, I get diverted from the main task at hand thinking about various scenarios that I should consider while coding and this tends to demotivate me because I am often very confused in the end. What approach should I take in this case since thinking a lot on all possible scenarios comes naturally and I only try hard not to.

答:
Instead of thinking about everything at once, use a top-down approach.

So think: 'what does this program do on the highest level possible?'

Example: if you're writing a piece of code to take a string array and manipulate each string somehow, you'd code this first:

```<code>public ICollection<string> DoHighLevelStuff(ICollection<string> items)
{
    for(int i=0; i<items.Count; ++i)
        item = DoLowLevelStuff(item);

    return items;
}
</code>```

and worry about exactly how the lower-level methods work later.

I take this approach naturally, but some people can't help doing the opposite.

Note: different problems require different approaches and a bottom-up approach is not neccessarily poor practice.

Title: Approach to a programming task

Body:
Instead of thinking about everything at once, use a top-down approach.

So think: 'what does this program do on the highest level possible?'

Example: if you're writing a piece of code to take a string array and manipulate each string somehow, you'd code this first:

public ICollection<string> DoHighLevelStuff(ICollection<string> items)
{
    for(int i=0; i<items.Count; ++i)
        item = DoLowLevelStuff(item);

    return items;
}

and worry about exactly how the lower-level methods work later.

I take this approach naturally, but some people can't help doing the opposite.

Note: different problems require different approaches and a bottom-up approach is not neccessarily poor practice.


答:
This depends on level of coupling and clarity of abstraction between the GUI and web-service.

Following conditions at architectural level are must to make things work :

The abstractions of data elements must be clearly well defined. Also, if the data exchange is closer to the schema of DB on the web service side, it would be easier. (if applicable).

The flow of message exchanges must be very clearly articulated. the more stateless it is, the better it is.

Web-service should have NO knowledge of the how the GUI is using the data, and there should be no specific logic in the implementation of webservice.
For example, depending on the current view or last query, web-service should not be doing computation.

It is best that sessions of web front-end are kept away from service or restricted; mechanisms like authentication should either be based on independent brokers (like OpenID) or it is shielded between User to GUI vs. GUI to Web service.

Business rules are well documented and agreed upon.

Application of encryption of messages if applicable.

In general try to design web service API such that at least two different type of GUI might need to use it without having to run in inconsistent behavior. (this helps you to make conscious notice of GUI specific coupling).

The above are most basic rules for any to any platform. Apart from this, since you have mentioned, that this is a marriage between .NET and PHP, i would try to play safe and communicate only using pure XML. So i guess REST or even better plain old XML RPC might just work much better than SOAP. It is not that SOAP cannot work - but i guess it wont be without the trouble compared to "plain XML" communication.

Dipan.

Title: whole project of consuming web services with php

Body:
We are in the middle of a strange situation. We and a partner firm have to put up a web portal. They have a lot of functionality already done on their other portal and we are the managing firm on the project. But there are also some new development needed on their side which is designed by us. Strange thing is, we are going to do the GUI on the project and they will provide us some web services to gather data.

They are using .NET and we will be using PHP for the frontend project.

So what do you think that the best approach is to avoid communication and integration problems? For example

We provide them with just the view files and they do the rest all by themselves?

We develop a PHP project where we gather the required data using SOAP/REST web services?

Thanks in advance guys.


答:
If it's an employment agency test it shouldn't be that hard. It's not like they have language specialists to develop the test. Most likely all they will do is copy/paste questions from a website.

As long as you know how the framework works in general, and the most common namespaces/libraries for tasks, what stuff you have to use for certain tasks, you should be good.


问:
Is "Computer Science != Software Engineering" an excuse to teach programming poorly?
We've all heard it; whenever there's a discussion about CS grads having poor development skills someone eventually says,

Computer science isn't software engineering.

The problem that I see is that programming and software development are taught in CS courses. They're just commonly taught poorly. If it's being taught, then why not teach it right the first time? *

So I would like to see what the opinions are on 2 questions:

Is the CS != SE argument a copout or excuse for not properly teaching programming skills.

Regardless of your answer to question 1; if you were in the almighty position of making such a decision: would you force an emphasis on proper teaching of programming in CS courses?

*. I have a suspicion, based on anecdotal evidence I obtained throughout my education, that most academics in the field haven't had to write code to be maintained and haven't maintained code, and as a result don't have the knowledge/skills to teach it effectively.

答:
I think our problem is that we're much more like doctors than we're willing to admit... We have this idea that a four-year degree should prepare students to write software. It's not even close.

Our profession is largely in its infancy compared to other disciplines. Maybe the question should be: how can we improve CS so that the students who graduate with that degree are better suited to become productive members of a real-world software development team in a much shorter time span?

Maybe we should be more like medicine. Four years of basic work (CS degree) and then residency - practice of the craft under the supervision of a more experienced software engineer. Maybe that's what we already have, but it's less formal... I mean, like a resident, we learn our most valuable skills at the workplace in our first jobs.

Maybe as as discipline we just need to formalize this better.


答:
IMO, they're included in Java and C# primarily because they already existed in C++. The real question, then, is why is C++ that way. According to The Design and Evolution of C++ (§16.3):

The try keyword is completely redundant and so are the { } brackets except where multiple statements are actually used in a try-block or a handler. For example, it would have been trivial to allow:

```<code>int f()
{
    return g() catch(xxii) { // not C++
        error("G() goofed: xxii");
        return 22;
    };
}
</code>```

However, I found this so difficult to explain that the redundancy was introduced to save support personnel from confused users.

Edit: As to why this would be confusing, I think one has only to look at the incorrect assertions in @Tom Jeffery's answer (and, especially, the number of up-votes it has received) to realize that there would be a problem. To the parser, this is really no different from matching elses with ifs -- lacking braces to force other grouping, all catch clauses would match up with the most recent throw. For those misbegotten languags that include it, finally clauses would do the same. From the viewpoint of the parser, this is hardly enough different from the current situation to notice -- in particular, as the grammars stand now, there's really nothing to group the catch clauses together -- the brackets group the statements controlled by the catch clauses, not the catch clauses themselves.

From the viewpoint of writing a parser, the difference is almost too tiny to notice. If we start with something like this:

```<code>simple_statement: /* won't try to cover all of this */
                ;

statement: compound_statement
         | simple_statement
         ;

statements:
          | statements statement
          ;

compound_statement: '{' statements '}'

catch_arg: '(' argument ')'
</code>```

Then the difference would be between:

```<code>try_clause: 'try' statement
</code>```

and:

```<code>try_clause: 'try' compound_statement
</code>```

Likewise, for catch clauses:

```<code>catch_clause: 'catch' catch_arg statement
</code>```

vs.

```<code>catch_clause: 'catch' catch_arg compound_statement
</code>```

The definition of a complete try/catch block would not need to change at all though. Either way it would be something like:

```<code>catch_clauses:
             | catch_clauses catch_clause
             ;

try_block: try_clause catch_clauses [finally_clause]
         ;
</code>```

[Here I'm using [whatever] to indicate something optional, and I'm leaving out the syntax for a finally_clause since I don't think it has any bearing on the question.]

Even if you don't try to follow all the Yacc-like grammar definition there, the point can be summarized fairly easily: that last statement (starting with try_block) is the one where catch clauses get matched up with try clauses -- and it remains exactly the same whether the braces are required or not.

To reiterate/summarize: the braces group together the statements controlled by the catchs, but do not group the catchs themselves. As such, those braces have absolutely no effect upon deciding which catch goes with which try. For the parser/compiler the task is equally easy (or difficult) either way. Despite this, @Tom's answer (and the number of up-votes it's received) provides ample demonstration of the fact that such a change would almost certainly confuse users.

Body:
IMO, they're included in Java and C# primarily because they already existed in C++. The real question, then, is why is C++ that way. According to The Design and Evolution of C++ (§16.3):

The try keyword is completely redundant and so are the { } brackets except where multiple statements are actually used in a try-block or a handler. For example, it would have been trivial to allow:

int f()
{
    return g() catch(xxii) { // not C++
        error("G() goofed: xxii");
        return 22;
    };
}

However, I found this so difficult to explain that the redundancy was introduced to save support personnel from confused users.

Edit: As to why this would be confusing, I think one has only to look at the incorrect assertions in @Tom Jeffery's answer (and, especially, the number of up-votes it has received) to realize that there would be a problem. To the parser, this is really no different from matching elses with ifs -- lacking braces to force other grouping, all catch clauses would match up with the most recent throw. For those misbegotten languags that include it, finally clauses would do the same. From the viewpoint of the parser, this is hardly enough different from the current situation to notice -- in particular, as the grammars stand now, there's really nothing to group the catch clauses together -- the brackets group the statements controlled by the catch clauses, not the catch clauses themselves.

From the viewpoint of writing a parser, the difference is almost too tiny to notice. If we start with something like this:

simple_statement: /* won't try to cover all of this */
                ;

statement: compound_statement
         | simple_statement
         ;

statements:
          | statements statement
          ;

compound_statement: '{' statements '}'

catch_arg: '(' argument ')'

Then the difference would be between:

try_clause: 'try' statement

and:

try_clause: 'try' compound_statement

Likewise, for catch clauses:

catch_clause: 'catch' catch_arg statement

vs.

catch_clause: 'catch' catch_arg compound_statement

The definition of a complete try/catch block would not need to change at all though. Either way it would be something like:

catch_clauses:
             | catch_clauses catch_clause
             ;

try_block: try_clause catch_clauses [finally_clause]
         ;

[Here I'm using [whatever] to indicate something optional, and I'm leaving out the syntax for a finally_clause since I don't think it has any bearing on the question.]

Even if you don't try to follow all the Yacc-like grammar definition there, the point can be summarized fairly easily: that last statement (starting with try_block) is the one where catch clauses get matched up with try clauses -- and it remains exactly the same whether the braces are required or not.

To reiterate/summarize: the braces group together the statements controlled by the catchs, but do not group the catchs themselves. As such, those braces have absolutely no effect upon deciding which catch goes with which try. For the parser/compiler the task is equally easy (or difficult) either way. Despite this, @Tom's answer (and the number of up-votes it's received) provides ample demonstration of the fact that such a change would almost certainly confuse users.


答: I was in a situation like yours last year. It had been so long that I've been in an interview that I was dreading it. I did a search for C# interview questions and found several sites (many of them listed by the other posters) and I studied them. Much to my surprise 90% of the interviews were from those very site, verbatim. I guess interviewers use Google as well to find questions :)


答: Build it into the cost of your contract with them.</p>


答:
These tests have increasingly become a part of pre-screening applicants by professional recruiting firms and some companies. They're designed to give non-technical interviewers a way to assess someone's technical abilities. However, they're essentially just trivia tests that won't say anything meaningful about the abilities of a programmer other than to weed out those who really don't know anything. Unfortunately, some companies/recruiters put far too much weight upon these results.

The way to study for them is to find interview question sites, legit sites and not those trying to sell you the answers, plastered with popup ads or other such nonsense, and cram on the answers. That way you'll get a decent score and leap over the hurdle. If the company is placing too much weight on these results, they probably aren't the best company to work for anyhow.


答:
If the client is specifying a specific device and that was not stipulated in the original project scope, I believe it is on them.  If they specified that the product must work on mobile platforms, I think it is on you to make sure that you have a way to test on multiple mobile platforms.  If they are coming to you later and insisting it be tested on an IPad, then they need to provide.  Understanding of course, that if they provide it, they get it back when the project is done, so if you think you may want one later, that's on you.

I always include a clause in my contracts that stipulates the client is responsible for providing any specific and/or non-standard devices they require.  I am responsible for providing my own development environment, but I shouldn't have to go out and keep buying very specific pieces of hardware that are only for this project.  If you can test via an emulator as part of an SDK, good for you.  If they insist it has to be a real "XWidget 10000" then they need to provide.


问:
How to improve your ability to debug existing code
A common task in the working world is dealing with existing, but buggy code. What are some tips to improve your skills as a debugger?</p>

答:
Write automated unit test and other types of integration and functional tests.

The more automated tests you have, the less time you need to spend in a debugger.

Also, good design - SOLID principles. If you're writing small, focused classes and favoring composition over inheritance, eliminating duplication, etc., then your code will always be easier to debug.

I find that well designed code produces a different set of bugs that code that is not designed well. Generally speaking, well-designed code produces bugs that are easier to find, reproduce, and fix.

The exception (and there always is one) is multithreading code :-)


答: Read Clean Code by Robert C. Martin.  You will learn how to write good code, and good code also happens to be easily testable.</p>

Title: Steps towards TDD