答:
One of the nice things about using block delimiters (I.e.: Braces in C-Styled languages, or begin/end in Pascal-like languages) is that when used singly and on a separate line, they introduce additional white-space in your code. Now, without getting into a battle over hanging-brace vs inline-brace style choices, the point is simply that insofar as the compiler doesn't care either way, adding a little extra space helps to improve readability (particularly for those of us with eyes that aren't quite as young as they used to be!!). It's the same trick that you use when you create a resume. More white space makes things stand out better by themselves.

The other reasons to use block delimiters is to make it absolutely clear where something begins and ends. Sure, you can do the following:

```<code>DoTheFirstThing();
if (condition)
DoSomething();
DoSomethingElse();
</code>```

Yet, when reading the code, the eyes can easily skip through the code, and you end up making assumptions about what has occurred as a part of the if statement. Whereas if you were to add a couple of braces:

```<code>DoTheFirstThing();
if (condition)
{
DoSomething();
}
DoSomethingElse();
</code>```

you are making it clearer where the if block actually begins and ends.  Of course, if you are pedantic about your indentation, you might argue that a simple indent is enough.  Sure if you are used to using a language like Python, you may be used to paying particular attention to your indentation, but does it really make things much clearer?  Let's look at a couple more examples.  Decide which if statement stands out as the clearest when you take a really quick glance at the following:

```<code>DoTheFirstThing();
if (condition)
    DoSomething();
DoSomethingElse();
DoTheSecondThing();
if (condition)
{
    DoSomething();
}
DoSomethingElse();
</code>```

Now do the same as the previous example, with this:

```<code>DoTheFirstThing();
if (condition)
    DoSomething();
DoSomethingElse();
DoTheFirstThing();

if (condition)
{
    DoSomething();
}

DoSomethingElse();
</code>```

Out of the two examples, the very last if statement with the greater amount of whitespace stands out, and the code appears clearer, even though it is exactly the same.

So to really answer the OP's question, is it Bad to bunch things up and avoid brackets? My answer is no, and that I think calling it bad or poor or some other negative is laying it on a bit strongly.  The compiler doesn't really care, and the code will work exactly the same. However, it is certainly more readable if you add the braces, and is shows the purpose of the If statement more clearly.  More importantly perhaps, is that it shows that you are taking a little care to ensure the quality of your work stands out.  It's like the difference between quickly painting a wall with a wide paint-brush once, or using a roller and carefully applying two coats of paint. Just as it is important to look at the finish of a paint job, so to the extra care taken in your code shows that you are willing to take the time to ensure others will not find it difficult to read through your work.  This pays itself back when you need to revisit the code months or even years later, or when someone else needs to support you code after you're done.

Carefully written, clean, readable code inspires confidence in the code, while messy looking code will usually inspire an it's awful and too hard to work with attitude towards the code. Attention to detail shows a difference between the careful professional, and the less careful programmer. It inspires trust in your work, and is a pleasure to work with.

Body:
One of the nice things about using block delimiters (I.e.: Braces in C-Styled languages, or begin/end in Pascal-like languages) is that when used singly and on a separate line, they introduce additional white-space in your code. Now, without getting into a battle over hanging-brace vs inline-brace style choices, the point is simply that insofar as the compiler doesn't care either way, adding a little extra space helps to improve readability (particularly for those of us with eyes that aren't quite as young as they used to be!!). It's the same trick that you use when you create a resume. More white space makes things stand out better by themselves.

The other reasons to use block delimiters is to make it absolutely clear where something begins and ends. Sure, you can do the following:

DoTheFirstThing();
if (condition)
DoSomething();
DoSomethingElse();

Yet, when reading the code, the eyes can easily skip through the code, and you end up making assumptions about what has occurred as a part of the if statement. Whereas if you were to add a couple of braces:

DoTheFirstThing();
if (condition)
{
DoSomething();
}
DoSomethingElse();

you are making it clearer where the if block actually begins and ends.  Of course, if you are pedantic about your indentation, you might argue that a simple indent is enough.  Sure if you are used to using a language like Python, you may be used to paying particular attention to your indentation, but does it really make things much clearer?  Let's look at a couple more examples.  Decide which if statement stands out as the clearest when you take a really quick glance at the following:

DoTheFirstThing();
if (condition)
    DoSomething();
DoSomethingElse();
DoTheSecondThing();
if (condition)
{
    DoSomething();
}
DoSomethingElse();

Now do the same as the previous example, with this:

DoTheFirstThing();
if (condition)
    DoSomething();
DoSomethingElse();
DoTheFirstThing();

if (condition)
{
    DoSomething();
}

DoSomethingElse();

Out of the two examples, the very last if statement with the greater amount of whitespace stands out, and the code appears clearer, even though it is exactly the same.

So to really answer the OP's question, is it Bad to bunch things up and avoid brackets? My answer is no, and that I think calling it bad or poor or some other negative is laying it on a bit strongly.  The compiler doesn't really care, and the code will work exactly the same. However, it is certainly more readable if you add the braces, and is shows the purpose of the If statement more clearly.  More importantly perhaps, is that it shows that you are taking a little care to ensure the quality of your work stands out.  It's like the difference between quickly painting a wall with a wide paint-brush once, or using a roller and carefully applying two coats of paint. Just as it is important to look at the finish of a paint job, so to the extra care taken in your code shows that you are willing to take the time to ensure others will not find it difficult to read through your work.  This pays itself back when you need to revisit the code months or even years later, or when someone else needs to support you code after you're done.

Carefully written, clean, readable code inspires confidence in the code, while messy looking code will usually inspire an it's awful and too hard to work with attitude towards the code. Attention to detail shows a difference between the careful professional, and the less careful programmer. It inspires trust in your work, and is a pleasure to work with.


问:
how to structure MVC models and ORM models
I have some trouble getting a good folder structure in my project and i would like to know what other ways i could use to structure my files.

I'm currently working in an MVC sturctured folder.

```<code>www/
  Controllers/
  Models/
  Views/
</code>```

Nothing special so far. But i'm also using an ORM system. With it i can easily get an 'object' from my database like:

```<code>ORM::load('table');
</code>```

Now this sort of code should reside in a Model right? So i'd get something like this:

```<code><?php
class userModel
{
    public function getAllUsers ( )
    {
        return ORM::load('table');
    }

    public function getUserById ( $id )
    {
        return ORM::load('table', 'userid=?', array($id));
    }
}
?>
</code>```

Looks good so far in my opinion... But there's one more thing. I can also specify a 'model' when using the ORM system. With this model i can basically set up validation rules. Like so:

```<code>ORM::withModel('authModel');
</code>```

This lets the ORM know that before it adds a new row (or updates an existing one) to the DB, that it should check the following model first for validation rules.

```<code><?php
class authModel //Or maybe authValidation??
{
    // Method gets automatically triggered when an update is done with the ORM
    public function onUpdate ( $obj )
    {
        if ( $obj->username == '' )
            throw new \Exception('No username');
    }

    public function onInsert ( $obj )
    {
        // Validations here too.
    }
}
?>
</code>```

Now the problem is, is that i have 2 sorts of models. One where i basically use getters/setters to get and store data to the database (from my controller to my model).

And i have another model in which validation rules are set... I don't want to mix both in the same folder. So i must come up with another structure for this. Something like:

```<code>www/
  Controllers/
  Models/
    Repositories/
    Entities/
  Views/
</code>```

It's just that my model isn't a real 'repository', since it doesn't store any objects in the repo class and doesn't have a commit() method or anything like that.

I also can't store the 2nd model (for validations) in the Entities folder, because they're not Entities at all...

Any idea how i should structure this..??

答:
I would not call myself a backend developer, so before I answer, I will strongly encourage you to spend some time looking at how others are doing MVC architecture. I think CakePHP is a great place to start (and their code is very well documented!).

The way I would set out about doing it is to make a /Utilities folder that other parts of your program can call on when needed. Things that you might often be using in multiple controllers, views or models. You could place standard validation rules -- notEmpty(), alphaNumeric(), email(), etc. --  in this file (/Utilites/Validation.php).

Then you might make a /Models/Model.php that has your basic model template (save, delete, update, beforeSave, etc.) that would let new models inherit from it so you don't have to copy/paste repeated lines of code everywhere. Then you could make your userModel and if necessary have custom validation inside of that file.

Again, not a back end developer but I am familiar with CakePHP and looking out how they decided to handle these difficulties might give you some ideas!

ContentLicense: CC BY-SA 3.0


问:
What software programming languages were used by the Soviet Union's space program?
I got interested in the Soviet space program and was interested to discover that the software on the Buran spacecraft circa 1988 was written in Prolog.

Does anyone know what languages might have been used in earlier missions, especially the Mars PrOP-M rover missions of the early 1970s which were somewhat autonomous and could navigate obstacles?

Edit

My source for the Buran Prolog is this declassified document from the CIA site from May 1990.  I couldn't find an OCR version, so here's the relevant quote from p. 0449:

According to open-source literature, the Soviets used the
  French-developed programming language known as Prolog to develop
  on-board system software for the Buran vehicle...

答:
There's a book in Russian, German Noskin, First computers (literally board digital computing machines) for space applications (Герман Носкин, Первые БЦВМ космического применения), ISBN 978-5-91918-093-7.

The author himself participated in many early projects (mostly in hardware) and according to him analog hardware was in favor for a long time, he mentions that space rendezvous tasks didn't use digital computers until the late 70's. Due to this policy many digital computers were really proofs of concept although used in other areas of soviet economics. The first computer according to him used on-board was the Argon-11S (Аргон-11С) on the unmanned missions to the Moon closer to Apollo-8 in time. Also Noskin briefly says that the on-board computer Salut-4 was compatible with general-purpose computers ES used in Soviet economics so it was possible to develop software in PL-1 and Fortran.

There are several mentions of Buran program languages on Russian websites. According to Vladimir Parondjanov, an engineer from the program (Russian Post) three languages using Russian as a base were developed: PROL2 (ПРОЛ2) for onboard programs, Dipol (Диполь) for earth tests, and Laks (Лакс) for modelling. All of them were intended for use not only by professional programmers but also engineers from other areas.

When the Buran program was closed they were merged into a new language Drakon (Дракон, Russian word for "Dragon") that is claimed to be be a "graphical" language having 2-dimensional descriptions of the programs and using arbitrary well-known languages for code generation. This language was also intended for use by non-programmers. The language probably does not have and international community and isn't even well-known within Russia although heavily promoted by its author, Vladimir Parondjanov (the Russian Wikipedia article article is very long and was even deleted once for not following Wikipedia rules). Drakon was first used for programming for the Sea Launch missions and has been used in other Russian space programs since.


问:
Dealing with estimates as a junior programmer
I have been working for a couple of months now in a company that estimates (for the general population, not juniors specifically) tasks and then we are given the task, solve it, it goes through two tests and at the end the estimate should be somewhat met.

I am beyond stressed because some of the estimates are simply impossible for me to meet. I still don't know the entire system(because it is quite substantial) so sometimes half the time is spent finding out what i need to do and where and by the time I finish sometimes the estimate is over and there is still testing to be done (and correcting mistakes if they were any).

The second time I have to deal with a similar functionality it all works much faster, but so far I feel like I am just bad at programming.

Is there anything you did when you were just beginning that helped you get over this stage? I get so stressed when I see how little time there is to code that sometimes I can't even focus properly at what I'm doing which makes it even worse.

答:
This is common.

In general, it's better to give bigger estimates, than smaller (Most of the time you'll go over the estimate anyway). I'd advice you to cut the task into smallest possible subtasks and estimate these with each task no longer than 4 hours.

If a task may take more than 4 hours break it down into another set of subtasks. Also add a percentual buffer for tasks you can't foresee now (my personal preference is 1 unexpected task for every 2 estimated tasks with each unexpected task taking 2 - 4h depending on the system you're working with).

After that add the time you'd think it would take for testing, communication, analysis etc.


问:
Has whitespace in identifiers ever been idiomatic?
C# style suggests using CamelCase in identifiers to delimit words. Lisp tradition suggests using-dashes-instead.

Has there ever existed a programming language where using spaces in identifiers was not only allowed, but a commonly used idiom when employing multi-word identifiers?

It's possible to have identifiers with spaces in some Scheme implementations, but it's not a widely seen practice. Here's an example:

```<code>Petite Chez Scheme Version 8.4
Copyright (c) 1985-2011 Cadence Research Systems

> (define |hey there| 100)
> (define |x y z| 200)
> (list |hey there| |x y z|)
(100 200)
</code>```

答:
Scala allows arbitrary identifiers using backticks.  The usual use for this is to invoke Thread.`yield` because yield is a reserved word in Scala.  This could be (ab)used to have spaces in names, although that would be far from idiomatic Scala code:

```<code>val `the answer` = 42
println(`the answer`)
</code>```

Heck, you can even have tabs in identifiers:

```<code>scala> val `the\tanswer` = 42
the     answer: Int = 42
</code>```

I suppose this could conceivably be idiomatic for the literate programming folk. Maybe.

Body:
Scala allows arbitrary identifiers using backticks.  The usual use for this is to invoke Thread.`yield` because yield is a reserved word in Scala.  This could be (ab)used to have spaces in names, although that would be far from idiomatic Scala code:

val `the answer` = 42
println(`the answer`)

Heck, you can even have tabs in identifiers:

scala> val `the\tanswer` = 42
the     answer: Int = 42

I suppose this could conceivably be idiomatic for the literate programming folk. Maybe.


问:
Django development best practices
I have spent some time studying Django and I've done some applications. But I really don't know what is the best approach while developing an application, I mean, there are several options: Make all the models, then all the urls, the views and then make all the templates.

Other people recommend using an agile approach, take a use case and go all the way until it's totally functional, and of course there might be other possible recommendations. Personally I feel really attracted by the agile approach, but I don't really know because for example every single model I append to my database would imply to create a new one.

To sum up, what is the best approach one should take when developing and application in Django, taking into account all the consequences that it carries?

答:
Agile only, unless you're working for NASA :-)

It's either you or your customer/employer who has ideas about what IT should be. I've never seen people who're absolutely about what they're expecting to get. On the other hand, I do know a lot of people who have new ideas every day. So, in my opinion, the waterfall model only works for NASA and I've never seen it being used in programming.

Title: Django development best practices


问:
How do you organize your projects folders?
Good afternoon

I would like to know how do you guys organize your project folders?

I had once a boss that suggest me to organize by Customers.

```<code>Projects
|
|----Customer 1
     |---- A Cool Solution 1
           |---- source
                 |---- version1.0
                 |---- version1.1
           |---- docs
                 |---- analysis
                 |---- meetings
                 |---- manuals
|----Customer 2
|----Customer 3
</code>```

A friend of mine told me to organize tem by Technology

```<code>Projects
|
|----.NET
     |---- C#
          |---- Customer 1
                |---- A Cool Solution 1
                      |---- source
                            |---- version1.0
                            |---- version1.1
                      |---- docs
                            |---- analysis
                            |---- meetings
                            |---- manuals
|----Ruby
|----PHP
</code>```

And you? Do you have a clever way to organize your project folders?

答:
I have a structure that loosely looks like the following:

```<code>~/
|-- Developer/
|   |-- Projects/
|   |   |-- Archives/
|   |   |-- Current/
|   |   |-- Work/
|-- Projects -> ~/Developer/Projects/Current
</code>```

Archives contains old projects I'm no longer working on. Work contains work-related projects. Current is all current development. Then, in my home directory, I symlink Projects to ~/Developer/Projects/Current. ~/Projects also includes symlinks to some work projects.

ContentLicense: CC BY-SA 2.5

Body:
I have a structure that loosely looks like the following:

~/
|-- Developer/
|   |-- Projects/
|   |   |-- Archives/
|   |   |-- Current/
|   |   |-- Work/
|-- Projects -> ~/Developer/Projects/Current

Archives contains old projects I'm no longer working on. Work contains work-related projects. Current is all current development. Then, in my home directory, I symlink Projects to ~/Developer/Projects/Current. ~/Projects also includes symlinks to some work projects.


问:
The bracketless if statement is frowned upon, but is it still bad style if your IDE is equipped for it?
This type of conditional statement is generally frowned upon

```<code>if(condition)
  statement;
</code>```

because if you add another statement, like this

```<code>if(condition)
  statement;
  statement;
</code>```

it gives the impression that the second statement is part of the if block when it isn't.

That said, my IDE does automatic indentation, which I think makes this problem moot. Furthermore, when I want to add another statement, it automatically does the bracket completion--which makes the issue about having to manually add brackets when you want to add another statement moot.

Is there any reason why this would still be bad style?

答: Readability and maintainability are, in most circumstances, the two most important attributes of any piece of code.  Using conditional logic without braces reduces readability, which is why it's considered bad style.  Having a fancy IDE doesn't turn bad style into good style.  Don't do it.</p>


问:
How do I write unit tests for robots (and other mechanical devices)?
I'm a member of my high school's robotics club, and am responsible for programming the robot.  One suggestion I keep hearing from various adults is that I should be writing unit tests to help validate my code.  The code base is getting a bit big, and I do agree that unit tests would be really helpful in helping me catch bugs quicker.

However, I'm not entirely sure how I could accomplish this.  To the best of my knowledge, unit testing is done by taking a function (or a subsystem of the code) and feeding it a set of input to make sure it comes out with the same output each time.  The code that I currently have doesn't do any heavy data crunching, but rather directly manipulates the hardware components on the robot.  Most of the complexity comes from making sure that the electronics are sound, that the code at the moment matches the actual hardware on the robot, etc.  Often times, I can only see if there's a problem by loading the code to the robot itself, and attempting to run it.

By extension, how can unit tests be written for code meant to operate any mechanical device?  It seems to me that you can only catch errors by physically observing the operation of the machine.

Or am I just misunderstanding how unit tests should work?

(If it matters, here's the code, it's written in C++, and I'm participating in FRC)

答:
You will need to mock the hardware layer to do this testing. The idea is that instead of your code talking to the actual hardware, you talk to a fake version of the hardware that you can control and then use to verify that your code is working correctly.

Unfortunately there are some problems you have to overcome:

Mocking things in relatively low-level languages is more difficult (and thus, a lot more work)

Mocking hardware-level stuff is more difficult (and thus, a lot more work)

Also, most of the value of automated, unit testing comes from being able to run your tests at any time to catch regression bugs for long periods of time after you write the original code. With these sorts of competitions, your code won't be used at all after the contest is over, so you won't really get most of the value out of the tests. And considering how difficult it would be to add tests to your particular case, it might be better use of your time to just do manual testing and focus on features for the contest.


答:
Code quality is independent of the IDE used to generate it (past tense!). The IDE that will be used to change it might alleviate some code problems. But this is in the future. You should strive for quality now.

As you can see from the other answers, some people do not consider this to be bad style. But I suppose most would agree that mixing two styles is much worth than < whatever coding style you despise goes here >. So if you are on a team or work with an existing consistent code base, stick to the rules. IMHO that's the professional thing to do.

Title: The bracketless if statement is frowned upon, but is it still bad style if your IDE is equipped for it?

Body:
This type of conditional statement is generally frowned upon

```<code>if(condition)
  statement;
</code>```

because if you add another statement, like this

```<code>if(condition)
  statement;
  statement;
</code>```

it gives the impression that the second statement is part of the if block when it isn't.

That said, my IDE does automatic indentation, which I think makes this problem moot. Furthermore, when I want to add another statement, it automatically does the bracket completion--which makes the issue about having to manually add brackets when you want to add another statement moot.

Is there any reason why this would still be bad style?


问:
Do you actively think about security when coding?
When you're coding, do you actively think about your code might be exploited in ways it wasn't originally meant to do and thus gain access to protected information, run commands or something else you wouldn't want your users to do?</p>

答:
Absolutely.

Security is everything. And with numerical software, that goes twice.

Just the other day, a user managed to find and exploit the bug in one of my old programs. The damage was unreparable. See below:

It used to be round.


问:
How to be a successful programmer without a CS degree

Disclaimers (Please read before jumping to answer):

I've seen a number of questions similar to the one I would like to ask, so here are some similar questions.

IMHO They are neither completely what I'm asking, nor are they as thorough as I hope to be (I don't mean to brush off the answers to the below questions, nor am I discrediting the askers, I just want to be a little more thorough):

Can a CS degree benefit an older programmer?

https://softwareengineering.stackexchange.com/questions/80024/importance-of-certifications-for-java-programmer-without-bs-degree

https://softwareengineering.stackexchange.com/questions/81591/in-the-absense-of-a-cs-degree-how-can-i-fill-in-the-gaps-so-to-speak

Importance of CS degree when applying for development jobs?

Let me be clear, I'm not asking the following:

How to teach myself programming from scratch (without a degree in CS)

How to market myself as a good software developer (without a degree in CS)

How to get a great high paying job as a software developer (without a degree in CS)

A little context:

Now that I have disclaimers out of the way, let me flesh out my question, starting with a brief history of my experience as a software developer.

First off, I have been incredibly lucky. I've been given several job opportunities (a couple heavy backend PHP/MySQL projects, and several WP7 apps in XAML/C#) through which I really learned everything I know about software development. Nearly all of the software development jobs I've had were ones that I was not rightfully qualified to have (and I made that clear to my employers before they hired me). I don't want to give myself credit where it's not due, but I would say that perfect humility dispenses with modesty.

In nearly every single development job I've had, I have exceeded the expectations of my employer, and proved to be a valuable asset. There are of course exceptions1. But my point is I'm fairly intelligent and was able to teach myself what I needed to know in order to be successful at my job. With each job I had, I was stretched more and more.

I attend the University of Washington's Seattle campus, and am currently in my fourth year with two years left, working on a Math degree. During the various jobs I've had (see my résumé if you want that list) I've also been attending school as a full time student.

As I think most developers would agree, studying the typical general ed undergraduate courses, including introductory programming courses ABSOLUTELY PALES in comparison with writing real code, building real2 products, working with awesome people, and positively affecting the lives of users3.

So... as things go... I spent far more of my time and energy working instead of focusing on my studies. At times I performed very horribly, but for the most part I was able to stay afloat with my grades.

However the computer science program at UW is very, very, very, very competitive.

So, it was no surprise to me when I got rejected by the program. Twice. Ironically enough, the same half-hour window in which I received the always polite, albeit disheartening rejection notice via email, I got a phone call from Amazon offering me a summer internship4 as an SDE.

As I look around at other 'gents my age (21), who share the same goals as myself in software development, I find myself feeling pretty good about where I'm at, what I'm learning, who I am, and what I can do. There are of course much, much, much more brilliant 21 year olds out there than myself, I don't mean to say I stand out in a crowd, merely that I feel like I'm not abysmally behind the progress of my average peer.

I feel confident about my ability to be successful in the world of software. More importantly I feel confident in my ability and desire to continue to grow, learn, and be embarrassingly humbled when I really need it.

Math Degree

I find myself pursuing a Math degree with the sole purpose of having a degree. There are those that say I should drop out and start working now (as I've had opportunity to do), and there are those that say I should really finish my degree. I've made up my mind to go ahead with my degree for entirely different reasons than either camp tends to bring up, so please don't encourage me one way or another on that matter. Consider the issue "closed" :)

*DEEP BREATH* ...sorry this is longer than I anticipated.

This in essence, is my question:

How do I objectively determine what areas of study, general knowledge, and other skills I would have gained through a CS degree that I may or may not be lacking in now?

How do I sort these skills in order of most importance?

What is the best way (over the next two years) to supplement my education to attain those attributes in such a way to match or even surpass the level of a CS undergrad from a top university?

Here are the steps that I am taking already:

Ask the development community (this post)

Pursue mentorships with seasoned developers who share a similar career path with me

Define short and long term "learning" goals and subsequent syllabi outlining topics of study

Continue to write code and work on projects that I'm passionate about

If you've gotten this far, you deserve a cookie :) I appreciate you bearing with me.

So... development community, seasoned developers, fellow students who are in the same boat as me, what advice would you have?

Also... please do keep in mind my disclaimers at the top of this post about what I'm NOT asking for.

Update:

I realize that I did not provide very concrete parameters for what I deem a successful "answer" to my question(s). I think the question is very vague, and could warrant a number of "correct" answers.

After a reasonable amount of time I will select the answer that fits the following attributes:

Explains the why behind their answer

Can speak from some level of experience (be it hiring/interacting with or being someone who has/is in my shoes)

Is concise but thorough, gives broad principles preferably coupled with specific examples

Lastly, considering the length that matching the above would seem to require, please make it a good well communicated answer that's pleasant to read. Others who may be interested in this in the future I would hope would be entertained as well as educated by the response.

So there are some parameters for "correct". They're very high I think, but I've designed them as kind of an outline for what I envision the "best" answer would be. Obviously given enough time I'll select the closest matching response as the "answer".

```
(1) - I worked on a prior version of this website, and while we did not have an explicit
      conversation about it, I felt that I was not able to do very well at all (this can be
      evidenced by the fact that they have since changed their website entirely)
(2) - Firstly, yes, it's a real product (even though I'm writing this post in Chrome...), and
      it kicks ass. Secondly, I was a high school intern developer in test, wrote proof of
      concept code for some of the new features for IE8... so it was a while ago.
(3) - At the time of this posting I am the developer who wrote this app, I am no longer
      responsible for it's code base
(4) - My internship will start in June of 2012, and I'll be working in the Web Store
      team.
```

答:
First, let me LOL at the "concise but thorough" stipulation near the end of your grand opus. Down to business:

How do I objectively determine what areas of study, general knowledge,
  and other skills I would have gained through a CS degree that I may or
  may not be lacking in now?

As others mentioned, you can start at the course catalog. But I'd encourage you to step outside of the bounds of that list. It's actually good that you're majoring in Math. Many engineers I've worked with can't remember how to perform simple integration, and never explored outside the walls of the traditional CS discrete maths coursework.

This answer seems pretty sparse in terms of specifics. I don't have a CS degree, and I haven't found myself lacking in any necessary areas. I do wish, however, that I spent more time on the other things that interested me. History, Linguistics, and English, for example.

How do I sort these skills in order of most importance?

Learn what you love

What's important to you? What's important to employers? My personal heuristic has always been to learn what seems most interesting to me – you need to love what you do; otherwise, you'll burn out. Software is such a sprawling field of endeavor that there always seems to be a job available for a competent developer who is passionate about any of these skills.

Learn to learn, and push yourself

I guess that leads me to two meta-skills that I'd place above the rest: learn things voraciously, and work hard. Those may sound clichéd and painfully obvious, but the combination is rare. I've been all over the map in terms of skills "needed" – front-end HTML/javascript to language extensions to mobile development to computer vision to systems administration and back again, over 7+ languages. The only true core skill in all that is having made overcoming my own ignorance a habit.

I really love Jack White's philosophy about guitars and music (seriously, go watch that), and I think it's supremely applicable to the programming world. Put things a little further out of reach. Push yourself. Then it'll seem easy when all someone wants for you to do is your job.

What is the best way (over the next two years) to supplement my
  education to attain those attributes in such a way to match or even
  surpass the level of a CS undergrad from a top university?

Non-major CS classes

Like you, the CS department at UW rejected me... although I think I let them do it a third time before coming to my senses. I wound up majoring in Informatics and minoring in Applied Math. But I still took the entire non-major CS track. That's CSE 373, 410, 413, 415, and 417. So, sure I believe that you should follow your passion first. Mine lead me to those classes. And I think that you get a pretty comprehensive core education with them, although it might be a little light on the theoretical side of things.

Now, here's the cool thing: with Informatics, most of these counted towards my required electives. In the Math department, you might need to get explicit approval, and it might be a stretch for any but CSE 417.

Summon up a DARS inquiry (probably a UWNetID-only link) and see where things stand. I used to do this for various majors ad nauseum.

AMATH Classes

Along the same lines, the Applied Math department has some classes that could be worked in as elective requirements. You could even minor in AMATH like yours truly.

Why do I mention this? Numerical computing – e.g. AMATH 301/352 – is a huge mystery to most programmers. If you get nothing else from it, you'll be able to write interesting blog posts. But I'd contend that knowing the issues surrounding a language's numerical types and knowing how to measure and ameliorate them is pretty darn important.

Build something!

The most important thing you can do is to build something new. Take an idea from start to finish. Don't let it be something easy that's within your comfort zone.

The most fruitful programming classes I took always had a large hands-on programming component. For an engineer, theory incredibly important – so long as it can be turned into something real. So go find a cool sounding CS paper and try to implement it. Seriously.

Get a job

Now, you already mentioned that you have an internship at Amazon. That's great. Actual work experience really is key! There are plenty of people with CS degrees who can't program their way out of a wet paper bag. Having good work experience is worth way more than a degree.


答:
I can think of a couple of things that you will need to consider. The first is to make your hardware access layer as thin as you can, even if that means creating a basic wrapper-type of layer for it. This offers you a couple of advantages.  The first is that it allows you to isolate the hardware-specific behaviours of your code from the hardware access itself, which means you can test everything down to the very bottom of your hardware comms without needing to access the hardware itself.

For example, if you need to design an I2C-based signalling protocol, you can test your code is generating the correct I2C signals without needing to hook the hardware into your tests.

For calls to the actual hardware, you can test that they are behaving correctly by mocking your hardware layer, and this is where keeping a very thin hardware layer really pays off, because you can reduce your mock to needing only handle the minimum functions required to actually address the hardware, but you don't necessarily need to test the individual signals themselves, as all of your signalling should have been testable at a higher level. This means then that you use your mock to check that calls are made to specific hardware methods that cause your signals to be sent to hardware. If you need to poll your hardware, then your mock needs to be able to trigger events or methods in your code only, because again, your return signalling should be handled in a higher layer.

This basically fits with what Oleksi said in his answer, in that it is usually more work to mock hardware-level stuff, however it isn't so difficult if you keep to the leanest possible minimal-code/call layer you can make for the hardware.

When you have code that passes all of its tests, you will still need to run through a series of manual tests in order to be sure you hoked everything up correctly in your hardware layer.

The other thing that comes to mind aside from the mocking and the layering, is to use a test-first development practice. Essentially, you code your requirements as test criteria, and you base your implementation off your tests. This will help you to ensure you keep your implementation code to a minimum, while ensuring all of your test cases are driving your development efforts. By not wasting too much time on other potentially non-critical code that you might be tempted to do "just because", test first helps you to stay focused, and will make it easier to change your code as you debug, as will the use of your unit tests and mocks.  Debugging software bugs through the hardware is notoriously complicated and sucks up large amounts of your time that you would find better spent on other tasks.

Title: How do I write unit tests for robots (and other mechanical devices)?

Body:
I'm a member of my high school's robotics club, and am responsible for programming the robot.  One suggestion I keep hearing from various adults is that I should be writing unit tests to help validate my code.  The code base is getting a bit big, and I do agree that unit tests would be really helpful in helping me catch bugs quicker.

However, I'm not entirely sure how I could accomplish this.  To the best of my knowledge, unit testing is done by taking a function (or a subsystem of the code) and feeding it a set of input to make sure it comes out with the same output each time.  The code that I currently have doesn't do any heavy data crunching, but rather directly manipulates the hardware components on the robot.  Most of the complexity comes from making sure that the electronics are sound, that the code at the moment matches the actual hardware on the robot, etc.  Often times, I can only see if there's a problem by loading the code to the robot itself, and attempting to run it.

By extension, how can unit tests be written for code meant to operate any mechanical device?  It seems to me that you can only catch errors by physically observing the operation of the machine.

Or am I just misunderstanding how unit tests should work?

(If it matters, here's the code, it's written in C++, and I'm participating in FRC)


答:
well, in my opinion, since you are choosing django you are already reinforcing a beautiful MTV design. things would be quite different if you use java frameworks or even start from scratch.

agile is definitely recommended, but I would also like to remind you that: pre-mature optimization is the root of evil.

as long as your code is functioning and as long as you put refactoring in mind. you are already doing a good design.

Title: Django development best practices

Body:
I have spent some time studying Django and I've done some applications. But I really don't know what is the best approach while developing an application, I mean, there are several options: Make all the models, then all the urls, the views and then make all the templates.

Other people recommend using an agile approach, take a use case and go all the way until it's totally functional, and of course there might be other possible recommendations. Personally I feel really attracted by the agile approach, but I don't really know because for example every single model I append to my database would imply to create a new one.

To sum up, what is the best approach one should take when developing and application in Django, taking into account all the consequences that it carries?


答:
I think that you means "documentation folder".
I organise my documents for sector first at all, after for customer/application, at the end for "developing and maintenance".

Example:
Projects

Financial

Web application

App Alpha

```<code> - source
 - functional docs
 - etc etc (testing, meeting with customer)
</code>```

App Beta

```<code> - functional docs
 - etc etc (testing, meeting with customer)
</code>```

Desktop software

Energy & utilities

BLA BLA

Title: How do you organize your projects folders?

Body:
Good afternoon

I would like to know how do you guys organize your project folders?

I had once a boss that suggest me to organize by Customers.

```<code>Projects
|
|----Customer 1
     |---- A Cool Solution 1
           |---- source
                 |---- version1.0
                 |---- version1.1
           |---- docs
                 |---- analysis
                 |---- meetings
                 |---- manuals
|----Customer 2
|----Customer 3
</code>```

A friend of mine told me to organize tem by Technology

```<code>Projects
|
|----.NET
     |---- C#
          |---- Customer 1
                |---- A Cool Solution 1
                      |---- source
                            |---- version1.0
                            |---- version1.1
                      |---- docs
                            |---- analysis
                            |---- meetings
                            |---- manuals
|----Ruby
|----PHP
</code>```

And you? Do you have a clever way to organize your project folders?

Body:
I think that you means "documentation folder".
I organise my documents for sector first at all, after for customer/application, at the end for "developing and maintenance".

Example:
Projects

Financial

Web application

App Alpha

 - source
 - functional docs
 - etc etc (testing, meeting with customer)

App Beta

 - functional docs
 - etc etc (testing, meeting with customer)

Desktop software

Energy & utilities

BLA BLA


答:
OK, I find it too tempting not to answer your question, so here I am...

A few things about me first

I am 26 years old, and thanks to my father (btw, a mathematician and currently working as a professor) I've had the chance from a very early stage of my life to be around computers. (back in 1986 when I was born, though not the most common thing in those days, we always had one or two computers at home). That being said, and - obviously because of my curious and math-inclined / problem-solving oriented nature - it wasn't long before I found myself in love with programming. First with Pascal, at the age of 7-8 and then pretty much everything else just followed.

First, let me say that, while at school, I've always excelled in anything math-related, simply because I liked it, and honestly I could easily follow my father's example and become a mathematician too. But that didn't happen.

What did happen was probably the biggest mistake of my life (so far) : What would you call it when someone in love with code, who speaks 15+ languages and has written thousands of lines of code (from compilers to micro-kernels and web frameworks) by the age of 18, suddenly (the reasons are still too obscure in my mind, but the general, even if subtle, influence of your environment is never too negligible) decides to pursue a career in Medicine? I guess a "mistake".

The result? 5 years later (at 23), and 1 year before finishing my Med degree (still working on personal open-source programming projects as a hobby all the time), I decided I've had enough and decided to quit. And it was not only that I hated this new field (Medicine) so much, but also that there was something unsettling in this whole situation, an insatiable itch hidden deep inside... (what would it have been if...? ) Moreover, I had just realized that my hobby, what I considered great but had not even imagined as a real job, could not only bring some money but bring me lots of it + keep me happy as an individual. So, I decided to quit. (= the best choice, even if a bit late, I've ever made).

So, here I am now, an once-gonna-be-doctor (on-the-verge-of-a-nervous-breakdown psychiatrist to be precise; stupid me!) going for a CS degree (on my 3rd year actually; and, honestly, pursuing it in order not to end up lacking in those dreaded typical qualifications...) and a more-than-happy professional working on something that I adore and definitely the subject on which I have to offer the most.

A few observations (from my own experience)

Programming is one of the very few fields where the really good ones will always find their way up, no matter what. And this is most definitely NOT a matter of typical qualifications (honestly, if I had a company and wanted to recruit programmers, I can easily tell who's good in a matter of minutes - regardless of whether he even has any degree or not)

What it takes to be a good programmer is : math-oriented intelligence (but NOT maths itself) and passion (that will make the endless hours of studying a pleasure instead of a burden; and, even if I haven't realized that, trust me i've studied TONS of material on the subject in my life, purely on my own). Formal education is a nice thing, but it's a bit overrated. The core ingredients of success are the first two.

Maths is definitely where CS was born. But CS is not just maths anymore. I've always had a strong math-oriented brain, but I'm by no means a math guru. And honestly, in every day programming, (unless you're into building a graphics engine or something too localized) you'll most likely never need anything other than simple arithmetic (addition, subtraction, multiplication, division, modulo) and a few things about arrays. (many will disagree with me, probably mathematicians or too academic-oriented programmers, but definitely mastering calculus is NOT what it takes to be a good programmer). Having a good math background will maybe help you, but NOT because of the math itself; it'll help you solely based on one common thing these two field share : problem-solving skills.

Maths is a science (and a science I respect).

Programming is an art. (And an applied science as well, if you insist) But keep that in mind : an art - and that's how I've always treated it. And as with all arts, it cannot be taught. I may teach you the formal way of drawing a face and make you better than average but that won't make you neither a Da Vinci, nor a Klimt. Mona Lisas are painted by Da Vincis, and not by carefully educated painters. Great code is written by great code artists. And skill and devotion can easily outbalance formal education.

So, what does it take to become a *really* good programmer?

Being smart, great problem-solving skills and a passion for the subject (if you don't have it, just leave it; being mediocre is no excuse)

Lots of time to devote to the subject

Studying all the time ('coz you'll simply never know it all; and note: why does 'studing' has to be related to some degree? I've always found it far more pleasure doing things on my own pace...)

Writing code all the time (no matter how many books you have read; your coding level is directly equivalent to the amount of code you've written)

And again, LOVE for the subject (if you don't love it enough, and I mean really love it, all of the above will sooner or later become unbearable; for me, coding as a job is still like getting paid for... watching movies : absolutely absurd but yet simply great)

On your questions

How do I objectively determine what areas of study, general knowledge, and other skills I would have gained through a CS degree
  that I may or may not be lacking in now?

Though, I'd have to really know what's included Math degree, let me sum up what you'll most likely be missing from a CS degree (as courses/subjects/etc - inspired by my uni's programme of studies) in no particular order :

Logic Design of Digital Systems (some low-level circuit stuff, and/or/xors/etc - seemingly not too related, but still really educational)

Computer Architecture (along with some Assembly coding; you'll most likely never use it, but you can't tell how much it could shape your attitude as a programmer)

Data Structures (from linked list, to complex trees, etc; as simple as they may seem, sooner or later you'll need some good background on these; using ready-made solutions that you don't understand is not something a good programmer would do)

Compilers (yep, compilers! will you ever write a compiler? probably not; but unless you can write one, you'll never really know how things work...)

Operating Systems (same as above)

Computer Networks

Artificial Intelligence and expert Systems (you'll most likely never code in Prolog too; but it's still one of the things that might shape your coding brain and make it see things from a radically different perspective)

How do I sort these skills in order of most importance?

Knowing what to prioritize in an always-changing field as CS will always be a gamble - a guessing game.

Get to know what you want to do, and trust your instict. Of course, having a solid basic knowledge is a must. But what you'll delve into, it's entirely up to you. Also, plan your career carefully : if you want to be employed, then choose your target and be great at it (e.g. wanting to be employed by Google and not knowing how to read a simple Python script is probably one of those no-go situations). If you're starting something on your own (a company), then you have no "boss" to satisfy; just pick what suits you best.

For example, if you want to do something web-related, I'd definitely advise you to go for : PHP / MySQL / HTML / CSS / JavaScript (+jQuery/AJAX). But that's just me. Someone may like (or see more future in) Ruby/Rails than in PHP.

I, for instance, am now primarily coding in Objective-C / Cocoa. Would I advise you to pursue that? Definitely not. That is : unless you're into Macs or want a career selling Mac/iPhone-related software. If you're into Windows development, going for C# / .NET Framework would probably be your best choice. (if you want to get an idea of what I'm mostly into, just have a look in my StackOverflow Profile)

What is the best way (over the next two years) to supplement my
  education to attain those attributes in such a way to match or even
  surpass the level of a CS undergrad from a top university?

Study a lot (books, internet, other people's code, whatever) and write as much code as you can.

Ah, and try to get a job in anything code related. (I first started working as a freelancer and it's been a really valuable experience, just to see how things really work in the real world).

Just my .2 friendly cents... :-)

Sidenote : I know that some of my points may seem controversial, and i'm sure that there'll be many who will disagree with me. That's acceptable. But that doesn't change the way I see things - and especially the things i love.

Title: How to be a successful programmer without a CS degree

Body:
Disclaimers (Please read before jumping to answer):

I've seen a number of questions similar to the one I would like to ask, so here are some similar questions.

IMHO They are neither completely what I'm asking, nor are they as thorough as I hope to be (I don't mean to brush off the answers to the below questions, nor am I discrediting the askers, I just want to be a little more thorough):

Can a CS degree benefit an older programmer?

https://softwareengineering.stackexchange.com/questions/80024/importance-of-certifications-for-java-programmer-without-bs-degree

https://softwareengineering.stackexchange.com/questions/81591/in-the-absense-of-a-cs-degree-how-can-i-fill-in-the-gaps-so-to-speak

Importance of CS degree when applying for development jobs?

Let me be clear, I'm not asking the following:

How to teach myself programming from scratch (without a degree in CS)

How to market myself as a good software developer (without a degree in CS)

How to get a great high paying job as a software developer (without a degree in CS)

A little context:

Now that I have disclaimers out of the way, let me flesh out my question, starting with a brief history of my experience as a software developer.

First off, I have been incredibly lucky. I've been given several job opportunities (a couple heavy backend PHP/MySQL projects, and several WP7 apps in XAML/C#) through which I really learned everything I know about software development. Nearly all of the software development jobs I've had were ones that I was not rightfully qualified to have (and I made that clear to my employers before they hired me). I don't want to give myself credit where it's not due, but I would say that perfect humility dispenses with modesty.

In nearly every single development job I've had, I have exceeded the expectations of my employer, and proved to be a valuable asset. There are of course exceptions1. But my point is I'm fairly intelligent and was able to teach myself what I needed to know in order to be successful at my job. With each job I had, I was stretched more and more.

I attend the University of Washington's Seattle campus, and am currently in my fourth year with two years left, working on a Math degree. During the various jobs I've had (see my résumé if you want that list) I've also been attending school as a full time student.

As I think most developers would agree, studying the typical general ed undergraduate courses, including introductory programming courses ABSOLUTELY PALES in comparison with writing real code, building real2 products, working with awesome people, and positively affecting the lives of users3.

So... as things go... I spent far more of my time and energy working instead of focusing on my studies. At times I performed very horribly, but for the most part I was able to stay afloat with my grades.

However the computer science program at UW is very, very, very, very competitive.

So, it was no surprise to me when I got rejected by the program. Twice. Ironically enough, the same half-hour window in which I received the always polite, albeit disheartening rejection notice via email, I got a phone call from Amazon offering me a summer internship4 as an SDE.

As I look around at other 'gents my age (21), who share the same goals as myself in software development, I find myself feeling pretty good about where I'm at, what I'm learning, who I am, and what I can do. There are of course much, much, much more brilliant 21 year olds out there than myself, I don't mean to say I stand out in a crowd, merely that I feel like I'm not abysmally behind the progress of my average peer.

I feel confident about my ability to be successful in the world of software. More importantly I feel confident in my ability and desire to continue to grow, learn, and be embarrassingly humbled when I really need it.

Math Degree

I find myself pursuing a Math degree with the sole purpose of having a degree. There are those that say I should drop out and start working now (as I've had opportunity to do), and there are those that say I should really finish my degree. I've made up my mind to go ahead with my degree for entirely different reasons than either camp tends to bring up, so please don't encourage me one way or another on that matter. Consider the issue "closed" :)

*DEEP BREATH* ...sorry this is longer than I anticipated.

This in essence, is my question:

How do I objectively determine what areas of study, general knowledge, and other skills I would have gained through a CS degree that I may or may not be lacking in now?

How do I sort these skills in order of most importance?

What is the best way (over the next two years) to supplement my education to attain those attributes in such a way to match or even surpass the level of a CS undergrad from a top university?

Here are the steps that I am taking already:

Ask the development community (this post)

Pursue mentorships with seasoned developers who share a similar career path with me

Define short and long term "learning" goals and subsequent syllabi outlining topics of study

Continue to write code and work on projects that I'm passionate about

If you've gotten this far, you deserve a cookie :) I appreciate you bearing with me.

So... development community, seasoned developers, fellow students who are in the same boat as me, what advice would you have?

Also... please do keep in mind my disclaimers at the top of this post about what I'm NOT asking for.

Update:

I realize that I did not provide very concrete parameters for what I deem a successful "answer" to my question(s). I think the question is very vague, and could warrant a number of "correct" answers.

After a reasonable amount of time I will select the answer that fits the following attributes:

Explains the why behind their answer

Can speak from some level of experience (be it hiring/interacting with or being someone who has/is in my shoes)

Is concise but thorough, gives broad principles preferably coupled with specific examples

Lastly, considering the length that matching the above would seem to require, please make it a good well communicated answer that's pleasant to read. Others who may be interested in this in the future I would hope would be entertained as well as educated by the response.

So there are some parameters for "correct". They're very high I think, but I've designed them as kind of an outline for what I envision the "best" answer would be. Obviously given enough time I'll select the closest matching response as the "answer".

```
(1) - I worked on a prior version of this website, and while we did not have an explicit
      conversation about it, I felt that I was not able to do very well at all (this can be
      evidenced by the fact that they have since changed their website entirely)
(2) - Firstly, yes, it's a real product (even though I'm writing this post in Chrome...), and
      it kicks ass. Secondly, I was a high school intern developer in test, wrote proof of
      concept code for some of the new features for IE8... so it was a while ago.
(3) - At the time of this posting I am the developer who wrote this app, I am no longer
      responsible for it's code base
(4) - My internship will start in June of 2012, and I'll be working in the Web Store
      team.
```


问:
What does Dijkstra mean when he recommends an exceptionally good mastery of one's native tongue?
Dijkstra writes here:

Besides a mathematical inclination, an
  exceptionally good mastery of one's
  native tongue is the most vital asset
  of a competent programmer.

I do not understand the latter part of this quote. Can you please explain or elaborate?

P.S. I have grown up in India. I speak Bengali at home; I speak Marathi in the community that I live in; Hindi is the national language and very widely spoken, so I know that, and in school and college I was taught with English as the first language. Of course, now I think in a multitude of languages and I must admit I don't have mastery over any. Is this really affecting my programming aptitude? If yes how ? and are there any solutions?

答:
I think being good at (any) language serves this -

If your point is not clear, you can think, revise, restate in improved manner.
Until what you say is exactly what you want next person(or machine) to understand.


答:
Whether or not to use the brace is a personal (and/or team)  preference. There are pros to cons about each. The reason for picking sides is to be consistent, and to produce code that is easiest for you to understand and maintain (and by "you" I mean "your team" if you're working in a team environment).

Your question seems to be not whether one is better than the other, but whether you should  let your IDE tell you what is best. And to that question I say a resounding NO. Choose your coding conventions based on what you think is best, or your team if you're working on a team.


问:
How can I do test automation using a python script to test a c program?
I was wondering if I can use a Python script to test a C program automatically.

Suppose I have a very simple C program which reads data (numbers as test cases) from the console, calculates them, then outputs it to the console. Now I want to read data from a file then output whatever the program outputs into a file.

Suppose in the original C program I use while loop andscanf to read two numbers into two variables a and b for several times and do different calculations according to the values of a and b, like this:

```<code>if(a>4 && a<10){...}
else if(a>=10){...}
</code>```

Now can I use a Python script to test the program automatically? And do I need to modify my C program? How?

EDIT: If any method is permitted, then what is the best way to test the C program automatically without using frameworks?

答:
Hmmm... If I'll have same task, I will solve it just by calling C program with different params in python. Like this:</p>

```<code>import commands
params_results = [(1,2), (2,3), (3,4)]
for param in pamams_results:
    out = commands.getoutput('mycompiledprogram %s' % param[0])
    assert out == param[1]
</code>```

Body:
Hmmm... If I'll have same task, I will solve it just by calling C program with different params in python. Like this:

import commands
params_results = [(1,2), (2,3), (3,4)]
for param in pamams_results:
    out = commands.getoutput('mycompiledprogram %s' % param[0])
    assert out == param[1]


问:
What tools do you use to manage requests from users?
I'm drowning in user emails and I'd like to implement a better way to manage all these requests I get and put them in a queue where those people on a team, as well as users, have access to them and can make common notes. I'm thinking about some sort of task management tool that would allow multiple tasks to be created under a project where emails, comments, ideas, etc. could be dropped/entered and easily accessible.

I need something that all parties can be involved in - users, managers, team leaders, developers. I'm looking for a tool that can allow:

Users to just drag/drop an email to submit a request for maintenance or enhancement.

Developers to just see their queue and the weighted priority of each task/project.

A team of developers to see what everyone is working on in real-time.

Management to keep a a log of time spent on each task.

I I am starting to look in more of a Agile/Scrum direction for solving this problem. I found list of scrum agile sofware project management open source tools. Since I am limited on time, has anyone used these? Which one should I test to see if it will meet my needs? TeamPulse is a good direction, but think it is a little too bloated. I need something simple for all parties.

答:
Mantis

...web-based bugtracking system (feature list). It is written in the PHP scripting language and works with MySQL, MS SQL, and PostgreSQL databases and a webserver. MantisBT has been installed on Windows, Linux, Mac OS, OS/2, and others. Almost any web browser should be able to function as a client. It is released under the terms of the GNU General Public License (GPL)...

I thought mantis was easy to use as far as bug/feature tracking goes.


问:
Efficient try / catch block usage?
Should catch blocks be used for writing logic i.e. handle flow control etc? Or just for throwing exceptions? Does it effect efficiency or maintainability of code?

What are the side effects (if there are any) of writing logic in catch block?

EDIT:

I have seen a Java SDK class in which they have written logic inside the catch block. For example (snippet taken from java.lang.Integer class):

```<code>        try {
            result = Integer.valueOf(nm.substring(index), radix);
            result = negative ? new Integer(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            String constant = negative ? new String("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }
</code>```

EDIT2:

I was going through a  Essential Classes > Exceptions)">tutorial where they count it as an advantage of writing logic of exceptional cases inside the exceptions:

Exceptions enable you to write the main flow of your code and to deal
  with the exceptional cases elsewhere.

Any specific guidelines when to write logic in catch block and when not to?

答:
Catch blocks should only be used for handling exceptions, nothing else and never ever for control flow. In any situation where you want to use exceptions to manage flow you would be better off checking pre-conditions.

Handling flow with exceptions is slow and semantically incorrect.

Title: Efficient try / catch block usage?


答:
This is something that tends to be dependent on language and paradigm.

Most of my work is done in Java (and sometimes C++). The tendency is to use exceptions for exceptional conditions only. There are some questions on Stack Overflow about the performance overhead of exceptions in Java, and as you can see, it's not exactly negligible. There are also other concerns, such as the readability and maintainability of the code. When used properly, exceptions can delegate error handling to the appropriate components.

However, in Python, the idea that it is easier to ask forgiveness than permission reigns. In the Python community, this is known as EAFP, which is contrasted with the "look before you leap" (LBYL) approach in C-style languages.

Title: Efficient try / catch block usage?

Body:
Should catch blocks be used for writing logic i.e. handle flow control etc? Or just for throwing exceptions? Does it effect efficiency or maintainability of code?

What are the side effects (if there are any) of writing logic in catch block?

EDIT:

I have seen a Java SDK class in which they have written logic inside the catch block. For example (snippet taken from java.lang.Integer class):

```<code>        try {
            result = Integer.valueOf(nm.substring(index), radix);
            result = negative ? new Integer(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            String constant = negative ? new String("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }
</code>```

EDIT2:

I was going through a  Essential Classes > Exceptions)">tutorial where they count it as an advantage of writing logic of exceptional cases inside the exceptions:

Exceptions enable you to write the main flow of your code and to deal
  with the exceptional cases elsewhere.

Any specific guidelines when to write logic in catch block and when not to?


答:
The example you cite is due to poor API design (there is no clean way to check whether a String is a valid integer except trying to parse it and catching the exception).

At the technical level, throw and try/catch are control flow constructs that allow you to jump up the call stack, nothing more and nothing less. Jumping the up the call stack implicitly connects code that is not close together in the source, which is bad for maintainability. So it should only be used when you need to do that and the alternatives are even worse. The widely accepted case where the alternatives are worse is error handling (special return codes that need to be checked and passed up each level of the call stack manually).

If you have a case where the alternatives are worse (and you really have considered all of them carefully), then I'd say using throw and try/catch for control flow is fine. Dogma is not a good substitute for judgement.

Title: Efficient try / catch block usage?


答:
I'm pretty flat:

/Projects

Some varation getting there depending on box, but behind that there are just lots of individual folders for projects. Real deal lives in source control anyhow, so this is just the temporary local home.


答:
Should catch blocks be used for writing logic i.e. handle flow control etc? Or just for throwing exceptions? Does it effect efficiency or maintainability of code?

First, forget the notion that "exceptions should be used for exceptional conditions".  Also stop worrying about efficiency, until you have code that performs unacceptably and you have measured to know where the problem lies.

Code is easiest to understand when actions follow in a simple sequence, without conditionals.  Exceptions improve maintainability by removing error checking from the normal flow.  It doesn't matter if execution follows the normal flow 99.9% of the time or 50% of the time or 20% of the time.

Throw an exception when a function is unable to return a value, when a procedure is unable to complete the expected action, or when a constructor is unable to produce a usable object.  This allows programmers to assume that a function always returns a usable result, a procedure always completes the requested action, a constructed object is always in a usable state.

The biggest problem I see with exception handling code is that programmers write try/catch blocks when they should not.  For example, in most web applications, if a database request throws an exception, there is nothing that can be done in the controller.  One generic catch clause at the highest level is enough.  Then the controller code can blissfully ignore the possibility that the disk has crashed or the database is offline or whatever.

Title: Efficient try / catch block usage?


问:
Limitations of UML?
I'm currently studying for an examination and one of the sample paper questions is to discuss the limitations of UML. Most of the material I'm finding on the net is relating to a specific UML implementation or language. I'm wondering from a generalists point of view what would you consider the limitations of UML to be? </p>

答:
Limitation 1: be quickly out-of-sync with the source

Limitation 1bis: need constant effort to keep it in sync

Limitation 2: it answers "how" it is, but not "why"

Limitation 3: lack of expressiveness:

it's hard to point out what's important, and what's not

pure text allows you more flexibility when explaining things

it only shows one isolated aspect at once (either the class diagrams, the uses cases, the flow, etc) but usually, what you need for a good understanding is a mix of those

Limitation 4: you can hardly express unusual concepts (reflection, first class functions, closures, pointers of pointers, annotations, dynamics...)

Title: Limitations of UML?


问:
Find a "hole" in a list of numbers
What is the fastest way to find the first (smallest) integer that doesn't exist in a given list of unsorted integers (and that is greater than the list's smallest value)?

My primitive approach is sorting them and stepping through the list, is there a better way?

答:
I believe I have come up with something that should work generally and efficiently if you are guaranteed not to have duplicates* (however, it should be extensible to any number of holes and any range of integers).

The idea behind this method is like quicksort, in that we find a pivot and partition around it, then recurse on the side(s) with a hole. To see which sides have the hole, we find the lowest and highest numbers, and compare them with the pivot and number of values on that side. Say the pivot is 17 and the minimum number is 11. If there are no holes, there should be 6 numbers (11, 12, 13, 14, 15, 16, 17). If there are 5, we know there is a hole on that side and we can recurse on just that side to find it. I'm having trouble explaining it more clearly than that, so let's take an example.

```<code>15 21 10 13 18 16 22 23 24 20 17 11 25 12 14
</code>```

Pivot:

```<code>10 13 11 12 14 |15| 21 18 16 22 23 24 20 17 25
</code>```

15 is the pivot, indicated by pipes (||). There are 5 numbers on the left side of the pivot, as there should be (15 - 10), and 9 on the right, where there should be 10 (25 - 15). So we recurse on the right side; we'll note that the previous bound was 15 in case the hole is adjacent to it (16).

```<code>[15] 18 16 17 20 |21| 22 23 24 25
</code>```

Now there are 4 numbers on the left side but there should be 5 (21 - 16). So we recurse there, and again we'll note the previous bound (in brackets).

```<code>[15] 16 17 |18| 20 [21]
</code>```

The left side has the correct 2 numbers (18 - 16),  but the right has 1 instead of 2 (20 - 18). Depending on our ending conditions, we could compare the 1 number to the two sides (18, 20) and see that 19 is missing or recurse one more time:

```<code>[18] |20| [21]
</code>```

The left side has a size of zero, with a gap between the pivot (20) and previous bound (18), so 19 is the hole.

*: If there are duplicates, you could probably use a hash set to remove them in O(N) time, keeping the overall method O(N), but that might take more time than using some other method.

Title: Find a "hole" in a list of numbers

Body:
I believe I have come up with something that should work generally and efficiently if you are guaranteed not to have duplicates* (however, it should be extensible to any number of holes and any range of integers).

The idea behind this method is like quicksort, in that we find a pivot and partition around it, then recurse on the side(s) with a hole. To see which sides have the hole, we find the lowest and highest numbers, and compare them with the pivot and number of values on that side. Say the pivot is 17 and the minimum number is 11. If there are no holes, there should be 6 numbers (11, 12, 13, 14, 15, 16, 17). If there are 5, we know there is a hole on that side and we can recurse on just that side to find it. I'm having trouble explaining it more clearly than that, so let's take an example.

15 21 10 13 18 16 22 23 24 20 17 11 25 12 14

Pivot:

10 13 11 12 14 |15| 21 18 16 22 23 24 20 17 25

15 is the pivot, indicated by pipes (||). There are 5 numbers on the left side of the pivot, as there should be (15 - 10), and 9 on the right, where there should be 10 (25 - 15). So we recurse on the right side; we'll note that the previous bound was 15 in case the hole is adjacent to it (16).

[15] 18 16 17 20 |21| 22 23 24 25

Now there are 4 numbers on the left side but there should be 5 (21 - 16). So we recurse there, and again we'll note the previous bound (in brackets).

[15] 16 17 |18| 20 [21]

The left side has the correct 2 numbers (18 - 16),  but the right has 1 instead of 2 (20 - 18). Depending on our ending conditions, we could compare the 1 number to the two sides (18, 20) and see that 19 is missing or recurse one more time:

[18] |20| [21]

The left side has a size of zero, with a gap between the pivot (20) and previous bound (18), so 19 is the hole.

*: If there are duplicates, you could probably use a hash set to remove them in O(N) time, keeping the overall method O(N), but that might take more time than using some other method.


问:
How do I stay compliant with GPL when forking on Github?
I've recently forked a project on Github and made some modifications to it, pushed them back to the forked repository and asked the original developer to pull the changes. (I gather this is the preferred way of contributing on Github.) The project is licensed under GPLv3.

I am the author and the copyright holder of the changes I've made to the code. I am also allowed to publish the modified code (i.e. the combination of the original code and my changes -- which I've done by pushing the changes into my fork) as long as I comply with the license the original author set up.

Now, I came across the following requirement in GPL.

The work must carry prominent notices stating that you modified it, and giving a relevant date.

It seems that some work beyond actual coding is required before I'm legally allowed to push my changes to Github. What does this work entail? How do I comply with the above requirement? (Do I add additional copyright notices to the modified source files? Do I create Contributors file and add myself to it? Or is the fact that the commits indicate my ownership sufficient?) Are there any additional pitfalls when forking a project protected by GPL?

答:
This line is meant to pertain to derivative works which are maintained and shipped separately from the master. In such a case, you would need to keep these records (which is done automatically by source control)

What you have done however is not a derivative work. You have committed your changes and have been pulled back to the main branch. Your changes are now part of the original project.

Furthermore, using source control (a public repository) means you will always be complying with this requirement.

There is the issue of how each person may define "prominent". To developers, source control(/+issue tracker) is a prominent way of viewing changes, however if you are maintaining a derivative work, you may want to maintain a list of substantial changes in a non-technical format.


答:
That is not the best way of thinking about try/catch blocks.  The way to think about try/catch blocks is this: a failure has happened, where is the best place to deal with THIS specific failure.  That may be the very next line of code, it may be twenty levels up the call chain.  Wherever it is, that is where it should be.

What the catch block does depends upon the error and what you can do about it.  Sometimes it can simply be ignored (failure to delete a scratch file with no imortant data in it), sometimes it will be used to set a functions return value to true or false (java's int parse method), sometimes you'll exit the program.  All of that depends upon the error.

The important part to understand is: catch block == I know how to deal with this.

Title: Efficient try / catch block usage?


问:
What kind of problems does MapReduce solve?
I have been reading about MapReduce for a while -- but what I can't understand is how someone would make a decision to use (or not use) MapReduce.

I mean, what are the problem patterns that signal that MapReduce could be used.

答:
Here's the major questions I use to probe a decision to use (or not use) MapReduce.

Is achieving reasonable parallel execution performance with minimal programmer effort important for a given problem?

Do I have a large number (hundreds) of parallel execution elements available?

Is there excellent communication bandwidth/throughput among the parallel execution elements?

Do I need to process a huge amount (TB) of data?

Does the problem I am trying to solve decompose into Map and Reduce operation?

Map: Execute the same operation on all data.

Reduce: Execute the same operation on each group of data produced by Map.


答:
A solution that doesn't use additional storage or assume the width (32 bits) of integers.

In one linear pass find the smallest number. Lets call this "min". O(n) time complexity.

Pick a random pivot element and do a quicksort style partition.

If the pivot ended up in the position = ("pivot" - "min"), then recurse on the right side of the partition, else recurse on the left side of the partition. The idea here is that if there are no holes from the beginning, the pivot would be at ("pivot" - "min")th position, so the first hole should lie to the right of the partition and vice versa.

Base case is an array of 1 element and the hole lies between this element and the next one.

The expected total running time complexity is O(n) (8*n with the constants) and worst case is O(n^2). The time complexity analysis for a similar problem can be found here.

Title: Find a "hole" in a list of numbers

Body:
What is the fastest way to find the first (smallest) integer that doesn't exist in a given list of unsorted integers (and that is greater than the list's smallest value)?

My primitive approach is sorting them and stepping through the list, is there a better way?


问:
How to create the architecture/design of an application in Agile?
If I am about to develop an Enterprise application, but as far as I understand from agile process, I break features into small chunks and develop them iteratively. I used to create the database and the core of the application first, then I extend these iteratively.

The question is: Do I have to keep what I used to do previously (develop the core first) or I have to distribute core development over stories' development? In the later, I am not sure the code will be flexible enough for future extensions!

Any idea?

答:
Do not develop the core first.  A key principle of Agile development is to write the minimal code needed for the completed features.  That way you can deliver at any time.  The code stays flexible because you continuously refactor to eliminate duplication.  Refactoring is supported by the automated tests you wrote for each feature as you built it.  The core grows automagically as you factor out duplication from higher level code.

Basically, instead of building in flexibility in a usually futile attempt to minimize expensive future code changes, Agile builds automated tests to support refactoring, so that code changes are relatively inexpensive.

Martin Fowler's Refactoring is my favorite book on effective refactoring techniques.  It is much easier to factor out a usable core than it is to define one up front.  Defining a usable core before feature implementation is nearly impossible, unless you are merely reimplementing an existing API.  And there's no value in that.


问:
Where do you draw the line between quantity and quality?
My manager has talked with me and says that the quality of my work is excellent, but I need to step up the quantity of how much I crank out. I've only been working for a couple of years, so I still feel like I have a lot to learn. Which route do I take (or is there another?):

Quantity: If they want crap, I can give them lots of it.

Quality: Ignore the request, and hope that my productivity will increase with experience.

答: Start thinking of projects more generically, start building your own frameworks for things and as time progresses your toolkit will grow to such a degree that you will start to be able to snap together old projects to create new ones, that is when the quantity will grow whilst maintaining quality.</p>


答:
My approach to agile development is to build "vertical slices". I take a story from the UI to storage and implement it. I have some lightweight tools that I use to help this process (like a simple IRepository/UnitOfWork framework that has adapters for In Memory(usually for testing), Entity Framework, and NHibernate. At this point I don't think there's much of an argument of whether one should use an O/RM but rather which one to use. And for me it depends on the environment.

I've found that this approach wins over naysayers regarding agile development because they get to see working software more quickly than if I spend a lot of up front time creating a core. Combined with Domain Driven Design and some other techniques I use, I'm usually able to get a lot of working functionality in front of the users very rapidly.

TDD or even post-hoc unit testing is important because part of maintaining velocity as your application grows is having that safety net that a comprehensive unit test suite provides. "I need to make a change to this class, how do I make sure I didn't break anything?" With a good unit test suite, it's as simple as running that test suite. Without, it becomes a matter of manually running through your app to verify. Not fun at all.

Title: How to create the architecture/design of an application in Agile?

Body:
If I am about to develop an Enterprise application, but as far as I understand from agile process, I break features into small chunks and develop them iteratively. I used to create the database and the core of the application first, then I extend these iteratively.

The question is: Do I have to keep what I used to do previously (develop the core first) or I have to distribute core development over stories' development? In the later, I am not sure the code will be flexible enough for future extensions!

Any idea?


问:
How to optimize Cartesian product
Is there a better way to compute cartesian product. Since cartesian product is a special case that differs on each case. I think, I need to explain what I need to achieve and why I end up doing cartesian product. Please help me if cartesian product is the only solution for my problem. If so, how to improve the performance.

Background:

We are trying to help customers to buy products cheaper.

Let say customer ordered 5 products (prod1, prod2, prod3, prod4, prod5).

Each ordered product has been offered by different vendors.

Representation Format1:

Vendor1 - offers prod1, prod2, prod4

vendor2 - offers prod1, prod5

vendor3 - offers prod1, prod2, prod5

vendor4 - offers prod1

vendor5 - offers prod2
vendor6 - offers prod3, prod4

In other words

Representation Format2:

Prod1 - offered by vendor1, vendor2, vendor3, vendor4

Prod2 - offered by vendor5, vendor3, vendor1

prod3 - offered by vendor6

prod4 - offered by vendor1, vendor6

prod5 - offered by vendor3, vendor2

Now to choose the best vendor based on the price. We can sort the products by price and take the first one.

In that case we choose

prod1 from vendor1

prod2 from vendor5

prod3 from vendor6

prod4 from vendor1

prod5 from vendor3

Complexity:

since we chose 4 unique vendors, we need to pay 4 shipping price.

Also each vendor has a minimum purchase order. If we don't meet then we end up paying that charge as well.

In order to choose the best combination of product. We have to do cartesian product of offered products to compute the total price.

```<code>total price computation algorithm:

foreach unique vendor
if(sum(product price offered by specific vendor * quantity)<minimum purchase order limit specified by specific vendor)
totalprice +=sum(product price * quantity) + minimum purchase charge + shipping price
else
totalprice +=sum(product price * quantity) + shipping price
end foreach
</code>```

In our case

{vendor1, vendor2, vendor3, vendor4}

{vendor1, vendor3, vendor5}

{vendor6}

{vendor1, vendor6}

{vendor2, vendor3}

4 * 3 * 1 * 2 * 2 = 48 combination needs to be computed to find the best combination.

{vendor1,vendor1, vendor6, vendor1, vendor2}=totalprice1,

{vendor1, vendor3, vendor6, vendor1, vendor2}=totalprice2,

.

.

{vendor4, vendor5, vendor6, vendor6, vendor3}=totalprice48

Now sort the computed totalprice to find the best combination.

Actual Problem:

If customer order's more than 15 products.Lets assume, each product has been offered by 8 unique vendor then we end up computing 8^15=35184372088832 combination. Which takes more than couple of hours. If customer order's more than 20 products then it takes more than couple of days.

Is there a solution to approach this problem in a different angle?

答:
Your Problem is in the same category as the famous "travelling salesman problem". Finding the best solution will be very expensive with rising numbers of vendors and products. You can try to implement a backtracking algorithm that tries to cut the solution space as early as possible.

Some ideas are:

Start with the "biggest cost" = max(quantity * min(price))

Try to minimize the number of vendors (=> try to get more products from a vendor already in the list)

add a solution if all items are ordered

break and track back if the current total sum is bigger than your best result

...

Title: How to optimize Cartesian product


问:
Is it a bad practice to use GUI designer tools with code generation for application programming in Java/C++?
In a stackOverflow question I have read that using a GUI designer program can generate lots of messy code and is considered to be a bad practice unless you're making smaller programs.

My question is why and how. Is it bad to use a GUI designer program? Why?

Additional details:

Programming on a Windows platform;

Only programming in C++/Java for windows programs.

For IDE I've been using visual studio 2010 (Not the express edition) since it comes with the GUI designer.

答: You need to understand what your code does. If someone comes to you and says "Why does this happen?", "Visual Studio made that for me, I have no idea" is not an acceptable answer. So long as you can find and resolve your own program bugs, there's no issue with a GUI designer, but once you find yourself fighting the program and unable to follow the logic, you need to back away from the WYSIWYG.</p>


问:
Memoization, Caching, Buffering and Page Filing?
I'm writing something on how iterative Fibonacci is substantially better than recursive Fibonacci - a few lines. The main reason of this I find, as do many prominent researchers I believe, is that you don't recalculate values - space vs time. From this I thought ah ha! caching! But I'm not sure if it is caching, memoization, buffering or one of the others.

I personally think buffering to be the preloading of material before something is done with it vs caching and memorization being more of a processing based thing. The buffering notion is that I get from such a buffering a picture or a video.

What is the difference between buffering, memoization, caching and page filing?

答:
Iterative fibonacci vs recursive fibonacci has more to do with the fact that compilers typically don't transform non tail-end recursive functions into iterative functions.  The difference between these two is keeping your variables on the stack (and in memory) for recursive, vs keeping two variables in registers saving tons of memory accesses for iterative.

It is not memoization since you don't keep a table of precalculated values (which could be done in either scenario).  Memoization and caching to me are almost the same thing, both involving storing precomputed results under a key, unless by caching you get concerned about the physical CPU caches and worry about cache alignment.

Buffering is simply filling memory space via i/o from a slow device such as a network or hard drive, vs pure byte by byte stream processing which is slow due to lots of i/o accesses.


问:
Python - Service, how to get a code review
I am usually a PHP and Delphi developer and have been getting into Python lately.

I am developing an app and would love to get some feedback on the code, there are few things which I would love to tidy up myself but I am sure there are other things.

Where / how is a good way to get in touch with an experienced Python dev? Paying is no problem.

答:
You could also try Code Review - Stack Exchange

for sharing code from projects you are working on for peer review. If you are looking for feedback on a specific working piece of code from your project in the following areas…

Best practices and design pattern usage

Security issues

Performance

Correctness in unanticipated cases

then you are in the right place..


答:
Caching is related to all the other concepts you mentioned, if you were talking about a hierarchy of concepts, caching would be the parent concept and memoization, some forms of buffering, and page files are specific forms of caching.

Memoization is storing precomputed values and then using those for looking up values rather than spending time to recalculate them. (time vs space tradeoff)

Buffering I assume you're referring to things like buffered IO, which can be used in software or hardware. In code, you can use buffered streams like in Java or C#, which will keep some amount of data in memory so programs don't have to wait for slow network/disk access. This isn't specifically caching.

Hardware buffers like in hard drives will cache a small amount of data for quick access. These are controlled by algorithms and predictions that if data was very recently used, it will probably be used again very soon.

Page files are a little different - it's a cache, but it's mainly to solve the problem of what happens when your program needs to have a lot of data in memory, but not enough memory to store that data? In environments with lots of different programs running, page files were created to solve this problem that you might have very limited RAM (shared by all apps) but significantly more storage space that could transparently be used for storing program data in addition to RAM (but significantly slower).

However, as Peter Smith mentioned, iterative vs. recursive algorithms aren't inherently memoized or anything (unless you're using constructs or languages that use transparent memoization). Recursive function calls require exponential function calls pushed onto the stack, and unless your language/compiler uses tail recursion elimination, this can be slower and also cause stack overflows.

You can memoize recursive or iterative solutions.

Title: Memoization, Caching, Buffering and Page Filing?

Body:
I'm writing something on how iterative Fibonacci is substantially better than recursive Fibonacci - a few lines. The main reason of this I find, as do many prominent researchers I believe, is that you don't recalculate values - space vs time. From this I thought ah ha! caching! But I'm not sure if it is caching, memoization, buffering or one of the others.

I personally think buffering to be the preloading of material before something is done with it vs caching and memorization being more of a processing based thing. The buffering notion is that I get from such a buffering a picture or a video.

What is the difference between buffering, memoization, caching and page filing?


答:
Catch blocks should not be used for writing code logic. They should be used only for handling errors. An example is (1) cleanup any allocated resources, (2) print a useful message, and (3) exit gracefully.

It's true that exceptions can be abused and cause undesired goto effects. But that doesn't make them useless. When properly used, they can improve many aspects of your code.

Title: Efficient try / catch block usage?


问:
When accessing/manipulating complex data, is it better to store it in many small pieces or one large chunk?
I am building a web app that manipulates fairly complex data: guitar tabs.

```<code>    As a reference, guitar tabs look like this:
Eb|-------------------------------------------------------------------------|
Bb|-------------------------------------------------------------------------|
Gb|--5-5-5-5----------------------------------------------------------------|
Db|--5-5-5-5--3-3-3-3--7-7-7-7--5-5-5-5--2-2-2-2--3-3-3-3--2-2-2-2--5-5-5-5-|
Ab|--3-3-3-3--3-3-3-3--7-7-7-7--5-5-5-5--2-2-2-2--3-3-3-3--2-2-2-2--5-5-5-5-|
Eb|-----------1-1-1-1--5-5-5-5--3-3-3-3--0-0-0-0--1-1-1-1--0-0-0-0--3-3-3-3-|
</code>```

Would it be more efficient for performance to store this data as a large chunk, or to break it up and store it on a "note by note" basis?

```<code>As a use case:
User changes first chord from:       to:
                         Eb|---   Eb|---
                         Bb|---   Bb|---
                         Gb|--5   Gb|--4
                         Db|--5   Db|--4
                         Ab|--3   Ab|--2
                         Eb|---   Eb|---
</code>```

If I store it as a block, the code to manipulate the tabs would have to be much more complex. If I store it note by note, the database will have to be accessed a lot more. Which method is more efficient? Potentially, a lot of users will be modifying the data. I want the best performing web app. I will be using MySQL if that affects the answer at all.

答:
The number of operations is going to be the same either way.  You do one query to get all the chords for a song, then you do one update every time a change is made.  The difference is really in the size of the updates.  With the block method, you have to save the entire song every time you change a chord.  With the individual method, your updates will be smaller, and probably more efficient overall, though the difference may be negligible.

Another thing to consider is the note-by-note method is more normalized, meaning you'll have more query options open to you down the road if you use it.  For example, beginners could filter out chords they don't know when searching for a song to learn, or you could allow searching based on the opening chords if someone doesn't know a song title.  Even if you don't plan those features now, it will be a huge pain to change your database if you want something like that later.