问:
Stack-instructions machines
When I look up "stack machine" I often get stuff like the JVM that uses a stack for data, but it still uses an array to store its instructions.

I would like to find out more about machines whose programs are stacks. For example, executing the command at the top of the stack by default removes the element at the top of the stack, and the program execution ends when the instruction stack is empty.

I'm afraid that this might be a silly question, but I have no idea what else these may be called.

I would like to know what the implementation of such a machine would look like (for example, how control flow might be handled on such a machine, how expressive the instruction set might be, etc.). A link to a Wikipedia page or some other reference would be really cool too.

While Forth, JVM bytecode, and others are heavily "stack-based", their program memory is not because the executable is always "there" like in a constant array, and if you want to branch to a different location you simply adjust the program counter.

On the other hand, in the hypothetical machine with a stack-instruction set you always execute the next instruction on the top of the stack. As Winston suggests, conditionals could be implemented by pushing various instructions onto the instruction stack.

For instance, you could have a PRINTFOR instruction that takes the number from the top of the data stack and puts that many PRINT instructions at the top of the execution stack.

For instance, if your original program was (in Forth style):

```<code>1 3 2 PRINTFOR
</code>```

At some point you will have:

Program Stack: PRINTFOR

Data Stack:    2 3 1

Then you will have:

Program Stack: PRINT PRINT

Data Stack:    3 1

And you will see

```<code>3
1
</code>```

on stdout.

I was curious as to what a "fully featured language" that takes on this kind of approach might look like.

@Mark Booth, I might just be asking an impractical question, and I might only have thought of this because of my inexperience. I'll try to explain why I wanted such an architecture.

I had worked through the Lex and Yacc tutorial Lex & Yacc Tutorial by Tom Niemann.

When I got to the part where he implements the calculator on a hypothetical stack-based machine, I spent some time implementing a VM myself.

However, I felt that at a couple of points the design could be easier for me to implement. In order to manage control flow, the machine uses some form of goto, and label. However, this would mean that in order to run an instruction, my machine would have to be aware of all the goto's all over the place. In some sense each instruction wouldn't be "context-free", and I was afraid this was bound to be more work than the alternative.

Instead of using a label, I could have goto take an instruction location (or an offset) so that I could simply set the pc to goto's operand. But this still seemed kind of messy to me. It still felt like the goto had to "know" stuff about the other instructions (and where they were) and the implementation could be cleaner.

I thought putting the operands on a stack was really cool, because it took away a lot of choices I didn't really care about when I dealt with registers. I figured maybe somebody has done something similar for instruction memory.

The benefit of such a system might be that each instruction is in some sense, "context-free", that is, when I implement the individual instructions, I don't have to worry about how many instructions there are, all I have to worry about are what the previous instructions have done (that is, the result of the data stack(s)), and what the instructions in the future are going to do (that is, the stuff left on the instruction stack). An interesting consequence would be that even in the middle of a while loop, all instructions you are going to perform in the future is considered an instruction "down the stack".
i.e.

If I have:

```<code>int x = 0;
while (True) {
  x++;
  if (x > 100) break;
  print(x);
}
</code>```

The "print" statement is physically placed below the "x++" statement, and it gets executed after the "x++" statement. However, when we reach the "print" statement, it can't forget about all the instruction that came before it. We still have to remember that the while loop closes the ending brace.

Furthermore, we don't know exactly which of the previous statements we are going to execute. In a stack-based instruction set, we can forget any instruction that has come before, and simply claim "We're going to do everything that's left in the instruction stack." This way it also becomes easier to see a program as the composition of other programs.

I'm afraid that some experienced coders might find that this really silly, because the design might end up imposing severe limitations that can only be overcome by doing things the old way, or I'm just making the classic way of implementing a VM harder than it is. However if this is the case, it would be cool if you could leave some comments to help me understand. On the other hand, I'm having trouble on how the idea might blow into a full instruction set, so even if it were possible, I'm not sure how it might be done.

答:
From a CPU point of view, the closest architecture I know of to what you describe is the transputer. It used a pair of stacks instead of data registers, but from your first edit I see that's not what you are looking for. However, the transputer instruction set also used a prefix mechanism for it's op-codes, like a mini instruction stack where complex instructions were built up by pushing values into an operand register.

All machine code instructions on the transputer were 8bits long. These instructions were composed of a 4 bit operand and a 4 bit operation. The 31 most used instructions could be executed with 1 byte. If you wanted to access less frequently used instructions you would use a prefix instruction to load additional nibbles into the higher order bits of the operand register, just like pushing bits of the operation onto an operation stack.

This had the interesting effect that transputer instruction set was effectively huffman encoded, resulting in very small executables. Unfortunately it also meant that the most popular implementations of the transputer architecture (T2/4/800 series) only instructions which could be encoded in a single byte could run in a single cycle. when highly pipe-lined super-scaler CPU's came along, the transputers stack based architecture really couldn't take advantage in the same way as traditional CISC and RISC architectures could.

Many of these problems were solved in the design for the T9000 in the 1990's, but this CPU took so to develop that it had been overtaken by other technologies before it went into production. It turned out that the benefit of smaller object code was too slight to make much of an impact on real-world performance (amongst other issues).

Title: Stack-instructions machines


问:
Should I intentionally break the build when a bug is found in production?
It seems reasonable to me that if a serious bug is found in production by end-users, a failing unit test should be added to cover that bug, thus intentionally breaking the build until the bug is fixed. My rationale for this is that the build should have been failing all along, but wasn't due to inadequate automated test coverage.

Several of my colleagues have disagreed saying that a failing unit test shouldn't be checked in. I agree with this viewpoint in terms of normal TDD practices, but I think that production bugs should be handled differently - after all why would you want to allow a build to succeed with known defects?

Does anyone else have proven strategies for handling this scenario? I understand intentionally breaking the build could be disruptive to other team members, but that entirely depends on how you're using branches.

答: In our test automation team, we check in failing tests as long as they fail due to a defect in the product rather than a defect in the test. That way we have proof for the dev team that hey, they broke it. Breaking the build is highly frowned upon, but that's not the same as checking in perfectly compilable but failing tests. </p>

ContentLicense: CC BY-SA 3.0


问:
Image color/grayscale classification
I am trying to classify a set of images into grayscale or color groups. I have been using ImageMagic to do that, comparing the color image to a grayscale version of itself and then using the Peak Error to determine if it is a grayscale image, as shown here:

http://www.imagemagick.org/Usage/compare/#type_general

This is working, however, it is producing false results for a lot of back and white images. I have tracked this issue down and I believe it is being caused by pseudo-black pixels (e.g.: rgb(0,0,5)). These psuedo black pixels appear as full color, because they technically are.

Is there a better way to classify these images?

What would you suggest I do to get rid of these false results?

答: Convert the images to another color space like HSV and than just check the S component. S stands for saturation and the saturation should be (nearly) 0 for all grayscale images. Here is the documentation from ImageMagick: http://www.imagemagick.org/script/color.php</p>

Title: Image color/grayscale classification


问:
Degree after BSc in Computer Science: Marketing, MBA, Techno-MBA, HCI?
Since a year I am a graduated Computer Engineer, and am now working in named field since 2 years. However, I'd like to get a Masters in a "softer" field and was thinking over the following choices:

MBA: Master of Business Administration, to bridge the business world with the world of computer science. Would give me an interesting job, travel potential, high salary etc.

Techno-MBA: Sort of an MBA, but aimed at people who already have a degree in Computer Science.

HCI: Human Computer Interaction degree, something I have been very interested in, but feel like it doesn't have the growth potential of MBA/Techno-MBA

Marketing: My most recent brainchild is a degree in Marketing, is this at all a good idea given my background? Growth potential?

Main priority: Gaining a skill, and gaining a job allowing me to use my social skills. Which path has the best "career potential"? (Controversial I know)

Any thoughts? Any feedback welcome.

Edit: DOH. Realized that the first sentence makes no sense. Was running my own semi-successful business during last year of school.

答:
Knowing everything I do now, I'd go for an MBA.

I studied Software Engineering at university and we spent a tremendous amount of time on esoteric things that we really interesting but I've never used. Technology has moved on, but each new thing can be learned, usually on-the-job.

Conversely, it is quite difficult to learn business skills while doing a software engineering job. Taking time out specifically to follow an MBA would give you the breathing space to be able to absorb the important concepts properly. The nature of businesses may evolve (international, online-only, etc) but generally it doesn't move that fast, so what you learn in an MBA will be relevant for some time to come.

If you need more evidence, look up what educational background big CEO/CTO's have in our industry.

ContentLicense: CC BY-SA 2.5


问:
Do you know any scenario where asp.net mvc can outperform asp.net?
Do you know any scenario where asp.net mvc can outperform asp.net? Because while comparing these two, people always say that each of them are different beasts and may be a better choice depending upon the scenario.</p>

答:
ASP.Net MVC is ASP.Net - they're the same thing. MVC is one set of handlers, WebForms is another or you could even write your own.

In terms of raw performance they'll be exactly the same, deep down ASP.Net is doing the same actions regardless of the handler.

However, in general MVC apps tend to be much quicker. This is because WebForms abstracts away the underlying HTTP model - developers are thinking in terms of components and their events, rather than in terms of HTTP request and response. It hides parts of the web model that are inconvenient, for instance the lack of actual state model is hidden by WebForms having a massive ViewState object that's sent back and forth with each request.

However all that keeps WebForms apps easy. Desktop developers can build a page, drag in buttons and controls, subscribe their click events and so on using the UI.

MVC deals much more directly with the HTTP pattern, so developers deal in links launching URL actions (which is what the web does), rather than components firing events (which is an abstraction hooked up as the response is processed). You're far less likely to have large hidden form variables and huge scripts added to the page by components, but they also tend (at least at first) to be more work.

So MVC apps are more simple. IMHO that generally means quicker and much more maintainable, but it also means more of a barrier to getting started, especially for desktop devs. They need to understand the request/response model pretty well, there's no decent WYSIWYG UI and they'll spend as much time in Javascript as they do in C#/VB.Net.

All that said nothing matters as much as how good your devs are.


问:
What should be the "depth of design"?
We all know that the process of creating a design and the whole architecture of the software is very important before writing the code. But how deep should be dive into the design stuff - should we start from the general architecture and go down til the names of the classes or should be just designate common parts and start coding?</p>

答:
I'll point you to the Chapter 9 of the book Python Programming: An Introduction to Computer Science
by John M. Zelle, Ph.D. were he introduce the top-down design bottom-up implementation strategy and says that the analysis process eventually bring problems small enough to be trivial to solve.

I would say you should apply the same strategy and go deep were is trivial to solve the problem. But, when is trivial? it depends on your capabilities.

Title: What should be the "depth of design"?


答:
This is driven by the development life cycle as well as the various project-level and product-level attributes. There's no single right answer that applies to all projects. Some projects tend to create a system architecture up front, and then enter into detailed design for portions of the system, either iteratively or concurrently. Other projects simply progress from architecture and continually refine the design, which is completed and baselined prior to starting implementation. Other projects might not need a formal design or architecture, and decisions and the current state of the project are captured informally.

There are a number of factors that can help you choose a development methodology, ranging from the amount of risk faced by the project, the amount of visibility desired by both management and the customer, the team's familiarity with the domain and technology, the volatility of the requirements, and so on. Steve McConnell's Rapid Development: Taming Wild Software Schedules has an entire chapter on choosing the appropriate methodology.

Title: What should be the "depth of design"?

Body: We all know that the process of creating a design and the whole architecture of the software is very important before writing the code. But how deep should be dive into the design stuff - should we start from the general architecture and go down til the names of the classes or should be just designate common parts and start coding?</p>


问:
Why should I not always pass a Django request context in a view?
According to the relevant Django documentation, a request context offers more than a normal context in that it merges request data into the context.

It is hence necessary for views that perform form submission in Django.

However, I am wondering why one cannot just always pass a request context for every view. After all, a request context offers more than a normal context.

Why not create a helper function called, say, render() that automatically passes a request context? Is there a performance disadvantage?

答: There is a performance disadvantage. It should be faster to render a template with an small context than with big context (i.e. the request context).</p>


问:
Do you write bad code when under pressure?
When you are under pressure, the deadline is approaching, and a manager is breathing down your neck do you find yourself starting to write bad code? Do TDD and best practices slip by the wayside in order to get things done? What do you do in situations like that? What were your experiences?</p>

答: Yes.  But it always comes back to haunt me later.</p>


答:
First, the following assertion you made isn't true.

We all know the process of creating a design and the whole
  architecture of the software is very important before writing the
  code.

Many, and arguably most development shops have come to the realization that doing a lot of design work up front is not beneficial. The problem is that at the start of the project, everyone (stakeholders, developers, etc.) know the LEAST they are ever going to know about what needs to be built (See Cone of Uncertainty). That is not the time to be making major decisions that are written in stone.

My advice is to do the least amount of design you can get away with before you start coding. After you have done a few rounds of prototypes, flesh out the designs with more detail.

Disclaimer: This advice mostly applies to development efforts where the problem is not that well defined up front and still feels very fuzzy. If you know exactly what you need to build and there isn't a lot of uncertainty, bu all means go deeper on your designs. That said, remember above all that your deliverable is working code, not a design document. Do only as much as you need to get the job done.

Title: What should be the "depth of design"?


答:
I would argue that the failing test should be added, but not explicitly as "a failing test."

As @BenVoigt points out in his answer, a failing test doesn't necessarily "break the build."  I guess the terminology can vary from team to team, but the code still compiles and the product can still ship with a failing test.

What you should ask yourself in this situation is,

What are the tests meant to accomplish?

If the tests are there just to make everyone feel good about the code, then adding a failing test just to make everyone feel bad about the code doesn't seem productive.  But then, how productive are the tests in the first place?

My assertion is that the tests should be a reflection of the business requirements.  So, if a "bug" has been found that indicates a requirement is not properly met, then it is also an indication that the tests do not properly or fully reflect the business requirements.

That is the bug to be fixed first.  You're not "adding a failing test."  You're correcting the tests to be a more accurate reflection of the business requirements.  If the code then fails to pass those tests, that's a good thing.  It means the tests are doing their job.

The priority of fixing the code is to be determined by the business.  But until the tests are fixed, can that priority truly be determined?  The business should be armed with the knowledge of exactly what is failing, how it is failing, and why it is failing in order to make their decisions on priority.  The tests should indicate this.

Having tests which don't fully pass isn't a bad thing.  It creates a great artifact of known issues to be prioritized and handled accordingly.  Having tests which don't fully test, however, is a problem.  It calls into question the value of the tests themselves.

To say it another way... The build is already broken.  All you're deciding is whether or not to call attention to that fact.

Title: Should I intentionally break the build when a bug is found in production?

Body:
It seems reasonable to me that if a serious bug is found in production by end-users, a failing unit test should be added to cover that bug, thus intentionally breaking the build until the bug is fixed. My rationale for this is that the build should have been failing all along, but wasn't due to inadequate automated test coverage.

Several of my colleagues have disagreed saying that a failing unit test shouldn't be checked in. I agree with this viewpoint in terms of normal TDD practices, but I think that production bugs should be handled differently - after all why would you want to allow a build to succeed with known defects?

Does anyone else have proven strategies for handling this scenario? I understand intentionally breaking the build could be disruptive to other team members, but that entirely depends on how you're using branches.


问:
How important are daily builds?
One of the criteria of the Joel Test is daily builds. The idea is that if the build is broken, whoever broke it is around to fix it up. If the build cannot be fixed, everyone will have to check out an old version and work on that. I can understand how this can be pretty bad on centralised version control where it is important to avoid merging and branching as much as possible, but this only sounds like a minor nuisance for distributed version control. Do you agree with this? Are there other reasons why daily builds are important?</p>

答:
Daily builds I believe are very important. If you have a distributed team in different time-zones then it is best to find time which is roughly 'end-of-day' for most of the team. In addition if the daily builds have a automated test component then it is more desirable.

In the days of central source control systems, I would advocate continuous builds running every 5-10 minutes when anything is changed in source code. Since
a compilation error has a potential of slowing most of the team.
For organisations running distributed source control systems, a continuous
build might not be needed as much since developers touch the 'pristine'
code-base directly less often.

Title: How important are daily builds?


问:
 Why do so many developers do this in their HTML?
```<code> <body>
  <!-- wrapper -->
  <div id="wrapper">
   <!-- title -->
   <div id="title"><img src="title.png" alt="" /></div>

   <!-- form wrapper -->
   <div id="form_wrapper">

    <!-- form -->
    <form action="thankyou.php" method="POST">
     <!-- ... ... -->
    </form>
    <!-- /form -->
   </div>
   <!-- /form wrapper -->
  </div>
  <!-- /wrapper -->
 </body>
</code>```

I can almost understand the  at the end, because it's so far from the start of the tag/pair...  but seriously, what's the point of the opening comment lines?  I wouldn't ask the question if I didn't see this all the time.

I feel as if I'm missing something.  Maybe there's some unwritten best-practice involved, though I fail to comprehend what it could possibly be.  More than likely it's just obsessive-compulsive behavior.

How do you guys normally comment your markup, if at all?

答:
I believe this comes from documents that do not have proper indention. So, if you can't tell where you are from the column you are in - then next best thing is to look at the comments. It seems to have evolved from this dilemma.

Personally, I would get on the people who are not indenting code.

Title: <!-- open --> Why do so many developers do this in their HTML? <!-- /close -->


问:
How should XML subtree manipulation be handled in a public API?
I'm working on an API whereby a specific call would replace a subtree of an XML document—rooted at some element—with another subtree.

The two options I'm considering for a response to this call are:

Return the DOM

Return the modified subtree

In the interests of developing a standardized, stable API, I'd like to get this right. Is there a best way to handle this type of scenario? What are the benefits and drawbacks of doing it one way over the other? Would it make sense to offer both these options to API consumers?

答:
Ideally, based on your description, the method shouldn't return anything. </p>

<p>The only reason you might want to return something is when you know for sure that it is a very common occurrence that callers need to use what you are returning right away. Look at it from the perspective of the caller. Do I need the entire DOM or just the updated branch? If you cannot easily decide, don't return anything.  </p>

Body:
Ideally, based on your description, the method shouldn't return anything.

The only reason you might want to return something is when you know for sure that it is a very common occurrence that callers need to use what you are returning right away. Look at it from the perspective of the caller. Do I need the entire DOM or just the updated branch? If you cannot easily decide, don't return anything.


答:
I can only think of one valid use case for this: partial HTML templates.

If it's a full HTML page, then you should indent properly to make it easy to identify when elements start and end.  Decent editors also highlight the opposite ends of tags.  In these cases, extraneous comments are annoying.

If it's a partial template (header and footer, for example), then if you are opening up some page containers, it may be useful to show in the footer where it ends.

header

```<code><div id="header">
    ...
</div>
<div id="contentContainer">
    <div id="content">
</code>```

footer

```<code>    </div> <!-- /#content -->
</div> <!-- /#contentContainer -->
<div id="footer">
    ...
</div>
</code>```

In (perhaps more complex) cases like this, having the comments are quite helpful to see what tag it is supposed to be closing.    This is the only case I've come across where I don't mind these comments, though, they still feel dirty.

Body:
```<code> <body>
  <!-- wrapper -->
  <div id="wrapper">
   <!-- title -->
   <div id="title"><img src="title.png" alt="" /></div>

   <!-- form wrapper -->
   <div id="form_wrapper">

    <!-- form -->
    <form action="thankyou.php" method="POST">
     <!-- ... ... -->
    </form>
    <!-- /form -->
   </div>
   <!-- /form wrapper -->
  </div>
  <!-- /wrapper -->
 </body>
</code>```

I can almost understand the  at the end, because it's so far from the start of the tag/pair...  but seriously, what's the point of the opening comment lines?  I wouldn't ask the question if I didn't see this all the time.

I feel as if I'm missing something.  Maybe there's some unwritten best-practice involved, though I fail to comprehend what it could possibly be.  More than likely it's just obsessive-compulsive behavior.

How do you guys normally comment your markup, if at all?

Body:
I can only think of one valid use case for this: partial HTML templates.

If it's a full HTML page, then you should indent properly to make it easy to identify when elements start and end.  Decent editors also highlight the opposite ends of tags.  In these cases, extraneous comments are annoying.

If it's a partial template (header and footer, for example), then if you are opening up some page containers, it may be useful to show in the footer where it ends.

header

<div id="header">
    ...
</div>
<div id="contentContainer">
    <div id="content">

footer

    </div> <!-- /#content -->
</div> <!-- /#contentContainer -->
<div id="footer">
    ...
</div>

In (perhaps more complex) cases like this, having the comments are quite helpful to see what tag it is supposed to be closing.    This is the only case I've come across where I don't mind these comments, though, they still feel dirty.


问:
SVN: Working with branches using the same working copy
We've just moved to SVN from CVS. We have a small team and everyone checks in code on the trunk and we have never ever used branches for development.

We each have directories on a remote dev server with the codebase checked out. Each developer works on their own sandbox with an associated URL to pull up the app in a browser (something like the setup here: Trade-offs of local vs remote development workflows for a web development team).

I've decided that for my current project, I'll use a branch because it would span multiple releases. I've already cut a branch out, but I am using the same directory as the one originally checked out (i.e. for the trunk).

Since it's the same directory (or working copy) for both the branch and the trunk, if for e.g. a bug pops up in the app I switch to the trunk and commit the change there, and then switch back to my branch for my project development.

My questions are:

Is this a sane way to work with branches?

Are there any pitfalls that I need to be aware of?

What would be the optimal way to work with branches if separate working copies are out of the question?

I haven't had issues yet as I have just started doing this way but all the tutorials/books/blog posts I have seen about branching with SVN imply working with different working copies (or perhaps I haven't come across an explanation of mixed working copies in plain English).

I just don't want to be sorry three months down the road when its time to integrate the branch back to the trunk.

答:
No

It's not a sane way to work with branches.  If you have uncommitted changes on the branch, and then switch your working directory to the trunk, those changes will still be present.  If those same files were patched on the trunk, then you will have merge conflicts.  It won't be long before you will commit a change to the trunk that was intended for the branch.

Disk space costs about ten cents per Gigabyte.  Checkout the trunk and branch separately.

I do occasionally use svn switch as follows:

checkout tagged release to reproduce problem

create patch branch

svn switch to patch branch.  The workspace should not change.

commit fix

create new tag

I also build on production systems from SVN checkouts.  There I use svn switch to update to a new release, rather than getting a fresh checkout.  I never toggle a single workspace between two separate branches.


问:
Is software testing actually done on professional projects?
I've been involved with many projects in several companies because I've been a developer for a long time and I'm a contractor.

I estimate that less than 20% of projects are methodically tested. With methodically tested I mean any testing beyond ad-hoc no plan testing.

I also estimate that less than 10% of projects are thoroughly methodically tested where they have dedicated testers as part of the team, test plan document, where developers write automated tests and then they also track test coverage and measure results.

Two questions

What are your percentage estimates about this issue?

What's your professional experience regarding software testing?

Additional note

Since methodical testing question may get quite biased answers (people like to brag about being superior to others) I encourage other developers (those that're not exposed to methodical testing) to provide their answer as well, because otherwise it will look like testing is being done everywhere... except at your company.

答:
In the last twenty or so years of my career through eight or so companies, I've never worked on a project that didn't do testing. The amount of testing differed at each company, but every professional development project I've ever worked on did formal testing. This applies equally to both small and middle sized companies (where "small" means less than 10 employees, and "middle sized" means a couple thousand employees or less).

Some companies didn't have much automated testing, some didn't have much manual testing, but they had at least one or the other.


问:
Git workflow for multiple teams
We are going to start using Git (not using it yet), and I want to define the workflow.

We have 4 teams at 4 different global locations, developing together the same product. Each team owns a part of the product's code, but sometimes they also have to make changes in the code owned by other teams.

Is there a recommendation for a Git workflow for such an environment?

I have already seen this article, but the approach here is "we create additional branches as seldom as possible", and I believe more in "branch for each user story" approach.

Also, this article presents a nice approach.

I had in mind having a master branch, a permanent branch per each team periodically merging to master, and a per-user-story branches merging to the teams' branches. Does it make sense, or it wouldn't work?

答:
Take a look at Successful Git Branching Model, which has a nice branching strategy for feature development across releases.

You could implement something similar with one extra level for team branches between the 'develop' branch and the 'feature branches'.  Having team branches would also allow two teams to collaborate more effectively by merge between their team branches.

OwnerDisplayName: Igor Oks

ContentLicense: CC BY-SA 4.0

Title: Git workflow for multiple teams


答:
We all know that the process of creating a design and the whole architecture of the software is very important before writing the code.

This is a false dichotomy.

Code is just detailed design.  Nothing more.

The hoped-for distinction between "design design" and "code design" is the presence of executable code.

However, this distinction becomes murky when we have UML-to-code generators.  If we create detailed UML, it becomes the code.

If we have a high-level, formal design language -- some kind of DSL that translates high level design or architecture into code -- then that DSL becomes the real code.

For example.  C++ used to be translated to C which was translated to an architecture-neutral intermediate form from which "code" was finally generated.  That means the C++ could be called a high-level design language.  It sure isn't very close to code.

If we use a high-level GUI generator and IDE to drag and drop icons which create code, what is that?  Is it design?  But it creates code, doesn't it?

I think the distinction between "design" and "code" isn't terribly helpful.

Which leads to the answer to your question.

should we start from the general architecture and go down til the names of the classes or should be just designate common parts and start coding?

It depends on what your audience needs.  You write design at one level so that they can take the design to the next level of detail.

Do they need classes?

Or do they only need design patterns into which the fill in the classes?

Or do they need method names?

It depends on your audience.

Title: What should be the "depth of design"?


答:
This is useful if the page is rendered by multiple different files/templates, etc.

Something like this:

```<code><?php

echo "<!-- sidebar -->\n";
include("sidebar.php");
echo "<!-- /sidebar -->";
# Or better yet, put the HTML comments *inside* sidebar.php
?>
</code>```

That way if you notice some strangeness in your rendered HTML, you can quickly track down the code that made it.

Body:
This is useful if the page is rendered by multiple different files/templates, etc.

Something like this:

<?php

echo "<!-- sidebar -->\n";
include("sidebar.php");
echo "<!-- /sidebar -->";
# Or better yet, put the HTML comments *inside* sidebar.php
?>

That way if you notice some strangeness in your rendered HTML, you can quickly track down the code that made it.


答:
It depends on the bug, of course, but generally if something went wrong that wasn't identified during manual or automated testing, then that implies there is a gap in your coverage. I would definitely encourage figuring out the root cause and slapping a unit test case on top of the problem.

If it's a production issue that is planned for a hot fix from a maintenance branch, you also need to ensure that the fix works on the mainline, and that a developer can't erroneously blow away the fix with an over-zealous merge conflict resolution.

Additionally, depending on your release policy, the presence of newly updated unit tests can help confirm that a developer has actually fixed the problem, rather than merely changing it [(the problem or the tests?)], although this depends on having encoded the correct requirements in the new unit tests.


答:
Your problem is setting the margin of error too strictly for classifying an image as black and white.  The trick is to not go too far the other way and falsely classify color images as black and white.

Do some research on Bayes classification.  Basically, you do the classification manually for a sample of your images.  That will give you the total probability of an image being black and white in your collection, as well as the probabilities of an average saturation in any given black and white image.  Then, you use a formula to compare the probability of a new unknown image being a black and white image versus the probability of it being color, given its average saturation.

For example, say 10% of the images in your collection are black and white, 20% of black and white images have an average saturation of 5, but only 1% of color images have an average saturation of 5.

```<code>black and white posterior for saturation of 5 = 0.1 * 0.2 = 0.02
color posterior for saturation of 5 = 0.9 * 0.01 = 0.009
</code>```

So you would classify an image with saturation of 5 as black and white.

The nice thing about Bayes classification is that you can use more than one factor in your determination, if you find another feature that you think is useful in addition to saturation.  Maybe maximum saturation works better than average, or you can combine the two.  Also, you don't have to guess at the right cutoff point, because it's based on your training set.

Title: Image color/grayscale classification

Body:
I am trying to classify a set of images into grayscale or color groups. I have been using ImageMagic to do that, comparing the color image to a grayscale version of itself and then using the Peak Error to determine if it is a grayscale image, as shown here:

http://www.imagemagick.org/Usage/compare/#type_general

This is working, however, it is producing false results for a lot of back and white images. I have tracked this issue down and I believe it is being caused by pseudo-black pixels (e.g.: rgb(0,0,5)). These psuedo black pixels appear as full color, because they technically are.

Is there a better way to classify these images?

What would you suggest I do to get rid of these false results?

Body:
Your problem is setting the margin of error too strictly for classifying an image as black and white.  The trick is to not go too far the other way and falsely classify color images as black and white.

Do some research on Bayes classification.  Basically, you do the classification manually for a sample of your images.  That will give you the total probability of an image being black and white in your collection, as well as the probabilities of an average saturation in any given black and white image.  Then, you use a formula to compare the probability of a new unknown image being a black and white image versus the probability of it being color, given its average saturation.

For example, say 10% of the images in your collection are black and white, 20% of black and white images have an average saturation of 5, but only 1% of color images have an average saturation of 5.

black and white posterior for saturation of 5 = 0.1 * 0.2 = 0.02
color posterior for saturation of 5 = 0.9 * 0.01 = 0.009

So you would classify an image with saturation of 5 as black and white.

The nice thing about Bayes classification is that you can use more than one factor in your determination, if you find another feature that you think is useful in addition to saturation.  Maybe maximum saturation works better than average, or you can combine the two.  Also, you don't have to guess at the right cutoff point, because it's based on your training set.


问:
Why is 'void' not allowed as a generic type in C#
What were the design decisions that argued in favour of void not being constructable and not being allowed as a generic type? After all it is just a special empty struct and would have avoided the total PITA of having distinct Func and Action delegates.

(C++ allows explicit void returns and allows void as a template parameter)

答:
The fundamental problem with "void" is that it does not mean the same thing as any other return type. "void" means "if this method returns then it returns no value at all." Not null; null is a value. It returns no value whatsoever.

This really messes up the type system. A type system is essentially a system for making logical deductions about what operations are valid on particular values; a void returning method doesn't return a value, so the question "what operations are valid on this thing?" don't make any sense at all. There's no "thing" for there to be an operation on, valid or invalid.

Moreover, this messes up the runtime something fierce. The .NET runtime is an implementation of the Virtual Execution System, which is specified as a stack machine. That is, a virtual machine where the operations are all characterized in terms of their effect on an evaluation stack. (Of course in practice the machine will be implemented on a machine with both stack and registers, but the virtual execution system assumes just a stack.) The effect of a call to a void method is fundamentally different than the effect of a call to a non-void method; a non-void method always puts something on the stack, which might need to be popped off. A void method never puts something on the stack. And therefore the compiler cannot treat void and non-void methods the same in the case where the method's returned value is ignored; if the method is void then there is no return value so there must be no pop.

For all these reasons, "void" is not a type that can be instantiated; it has no values, that's its whole point. It's not convertible to object, and a void returning method can never, ever be treated polymorphically with a non-void-returning method because doing so corrupts the stack!

Thus, void cannot be used as a type argument, which is a shame, as you note. It would be very convenient.

With the benefit of hindsight, it would have been better for all concerned if instead of nothing whatsoever, a void-returning method automatically returned "Unit", a magical singleton reference type. You would then know that every method call puts something on the stack, you would know that every method call returns something that could be assigned to a variable of object type, and of course Unit could be used as a type argument, so there would be no need to have separate Action and Func delegate types. Sadly, that's not the world we're in.

For some more thoughts in this vein see:

https://docs.microsoft.com/en-us/archive/blogs/ericlippert/the-void-is-invariant

https://docs.microsoft.com/en-us/archive/blogs/ericlippert/never-say-never-part-one

https://docs.microsoft.com/en-us/archive/blogs/ericlippert/why-have-a-stack


问:
Should we test all our methods?
So today I had a talk with my teammate about unit testing. The whole thing started when he asked me "hey, where are the tests for that class, I see only one?". The whole class was a manager (or a service if you prefer to call it like that) and almost all the methods were simply delegating stuff to a DAO so it was similar to:

```<code>SomeClass getSomething(parameters) {
    return myDao.findSomethingBySomething(parameters);
}
</code>```

A kind of boilerplate with no logic (or at least I do not consider such simple delegation as logic) but a useful boilerplate in most cases (layer separation etc.). And we had a rather lengthy discussion whether or not I should unit test it (I think that it is worth mentioning that I did fully unit test the DAO). His main arguments being that it was not TDD (obviously) and that someone might want to see the test to check what this method does (I do not know how it could be more obvious) or that in the future someone might want to change the implementation and add new (or more like "any") logic to it (in which case I guess someone should simply test that logic).

This made me think, though. Should we strive for the highest test coverage %? Or is it simply an art for art's sake then? I simply do not see any reason behind testing things like:

getters and setters (unless they actually have some logic in them)

"boilerplate" code

Obviously a test for such a method (with mocks) would take me less than a minute but I guess that is still time wasted and a millisecond longer for every CI.

Are there any rational/not "flammable" reasons to why one should test every single (or as many as he can) line of code?

答:
It's a tricky question.

Strictly speaking I would say that it is not necessary. You are better off writing BDD style unit and system level tests that insure business requirements function as intended in positive and negative scenarios.

That said if your method is not covered by these test cases then you have to question why it exists in the first place and if it is needed, or if there are hidden requirements in the code that are not reflected in your documentation or user stories which should be encoded in a BDD style test case.

Personally I like to keep coverage by line at around 85-95% and gate check-ins to mainline to insure existing unit test coverage per line hits this level for all code files and that no files are uncovered.

Assuming best testing practices are being followed this gives plenty of coverage without forcing developers to waste time trying to figure out how to get additional coverage on hard to exercise code or trivial code simply for the sake of coverage.

Title: Should we test all our methods?


答:
I think it should be daily build, test and deploy to staging server.

The idea behind 'daily build' is to always have something ready which testers and project managers can run so that everyone has an idea of what the real state of the project is.

In the past with desktop apps after the 'daily build' a tester or project manager can immediately run the app so no deploy step had to be mentioned.

Title: How important are daily builds?

Body: One of the criteria of the Joel Test is daily builds. The idea is that if the build is broken, whoever broke it is around to fix it up. If the build cannot be fixed, everyone will have to check out an old version and work on that. I can understand how this can be pretty bad on centralised version control where it is important to avoid merging and branching as much as possible, but this only sounds like a minor nuisance for distributed version control. Do you agree with this? Are there other reasons why daily builds are important?</p>


问:
How can I reuse generic code for consulting between companies?
I am employed full time for company X and approached by company Y to do consulting services to write embedded C for them. While I know the basics of conflicts of interests and the big no-no's of sharing proprietary information, company knowledge and proprietary algorithms, I do have some questions regarding basic generic items that I need to reuse:

Software architecture: I have a personal preference of layering application, abstraction layer and hardware drivers. I don't want to have to do something different and it is not proprietary to the company. Would this be a problem if shared?

Generic functions: table look ups, sine/cosine functions, parsers, etc. I wrote all this code myself. Can I copy-paste this or do I have to rewrite, insert random spaces, change indentation, var names, table sizes, etc?

Function naming: I use a specific naming convention, e.g. MATH_Sin(). However, compiled to a DLL, company X can find a MATH_Sin() function available in company Y's DLL and assume that I copied their code. Do I need to rename all functions to hide any similarities?

Public knowledge turned into source code: say you find an algorithm on an paper that describes how to search for a pattern in a string and you turned the paper content into source code. Again, would a copy-paste be a no-no here too? Rewrite changing a few things or completely dismiss and find for another way to do it? In the end it is an implementation of public knowledge.

I asked around my peers and I cannot get a straight answer on what to do. Software is digital and very traceable and can always be traced back to the developer.

Thanks.

Update: I have approached my manager and HR and they strongly discouraged me to pursue this. They claimed that by using the same skill set (embedded programming or programming in general) for another company, there will be always the opportunity for company X to challenge myself or company Y. I asked then what would NOT be considered a conflict of interest and they answered "You could invest in a restaurant...". Seriously?

Company X is a very large corporation. There is no negotiation between employer and company, there is no acceptance of open source/licensed code and it seems they believe they own me and my skill set. While I do agree with some of their reasoning, I do not agree that they own my education and, while employed for them, I can't make use of my basic skills for other endeavors. Therefore I have decided to follow the advice below and open source all my personal code that does not belong to the company nor was written using company equipment or company time. I won't be making money or signing contracts, but at least I can keep my personal code and continue developing my career outside this restrictive environment.

Thanks for all answers. Hope this serves as a reference for others pursuing the same goal.

答:
If you billed the time for developing some code to a particular company, then you're stuck - that code belongs to them and you can't take it with you.

If you have built up a library of your own code on your own time, and you want to be able to reuse it in different projects to boost your efficiency, one solution is to release that code under a permissive license, which you can do by just writing "License: LGPL" or whatever in a comment in the header.

You might think that this would lose you your competitive advantage, because someone else might just pick up your code and start using it, but

You will always be the one best able to make use of your own code, and

Just because the code is licensed for free use doesn't mean you have to post it on your website somewhere for the whole world to steal.

OwnerDisplayName: PaulG

OwnerDisplayName: Russell Zahniser


答:
Daily Builds are okay. You definietly need them if you have nothing else but to be honest I think Joel's test is a little out dated these days.

In my opinion you should be building continuously through out the day, running your unit, system and functional level test cases and ideally packaging and deploying to a stage like environment at the same time while verifying that any DB and environment versioning mechanisms you have in place are working as expected.

If build or deployment times are excessive then consider optomizing away some of these problems with physical or software ram disks, faster internet connections, parallellizing builds, etc. The time you will save by rapidly identifying build breaks is going to amoratize the hardware cost pretty rapidly.

Title: How important are daily builds?


问:
Handling extremely large numbers in a language which can't?
I'm trying to think about how I would go about doing calculations on extremely large numbers (to infinitum - intergers no floats) if the language construct is incapable of handling numbers larger than a certain value.

I am sure I am not the first nor the last to ask this question but the search terms I am using aren't giving me an algorithm to handle those situations. Rather most suggestions offer a language change or variable change, or talk about things that seem irrelevant to my search. So I need a little guideance.

I would sketch out an algorithm like this:

Determine the max length of the integer variable for the language.

If a number is more than half the length of the max length of the variable split it in an array. (give a little play room)

Array order [0] = the numbers most to the right [n-max] = numbers most to the left

Ex. Num: 29392023 Array[0]:23, Array[1]: 20, array[2]: 39, array[3]:29

Since I established half the length of the variable as the mark off point I can then calculate the ones, tenths, hundredths, etc. Place via the halfway mark so that if a variable max length was 10 digits from 0 to 9999999999 then I know that by halfing that to five digits give me some play room.

So if I add or multiply I can have a variable checker function that see that the sixth digit (from the right) of array[0] is the same place as the first digit (from the right) of array[1].

Dividing and subtracting have their own issues which I haven't thought about yet.

I would like to know about the best implementations of supporting larger numbers than the program can.

答:
You are looking for an arbitrary precision arithmetic (also called "multiple precision" or "big num") library for the language you are working with. For instance, if you are working with C you can use the GNU Bignum Library -> http://gmplib.org/ </p>

<p>If you want to understand how it works you can also write your own big num library and use it. The simplest way to handle this is with arrays, where each element is a digit of the number you are working with. After that you need to implement all the functions to add, subtract, multiply, divide, exponentiate and so on. </p>

Body:
You are looking for an arbitrary precision arithmetic (also called "multiple precision" or "big num") library for the language you are working with. For instance, if you are working with C you can use the GNU Bignum Library -> http://gmplib.org/

If you want to understand how it works you can also write your own big num library and use it. The simplest way to handle this is with arrays, where each element is a digit of the number you are working with. After that you need to implement all the functions to add, subtract, multiply, divide, exponentiate and so on.


答:
No, it is not sane.

First, your guys should really be working locally. If it is too hard to recreate an environment to run the app then you should address that.

Second, in scenarios where I was doing things in multiple long-running branches using SVN, the best / cleanest way to handle it I've found was to keep multiple working directories. Need to work on the trunk? Great, work in trunk folder. Need to work on the release branch? Great, just switch folders. Main issue was sometimes SVN would not like to switch and one would typically end up paving and re-checking out. This issue tended to crop up when one was often working in both branches. Was lots easier to just switch folders.

Then we went to hg and we don't have these problems . . .

Title: SVN: Working with branches using the same working copy

Body:
We've just moved to SVN from CVS. We have a small team and everyone checks in code on the trunk and we have never ever used branches for development.

We each have directories on a remote dev server with the codebase checked out. Each developer works on their own sandbox with an associated URL to pull up the app in a browser (something like the setup here: Trade-offs of local vs remote development workflows for a web development team).

I've decided that for my current project, I'll use a branch because it would span multiple releases. I've already cut a branch out, but I am using the same directory as the one originally checked out (i.e. for the trunk).

Since it's the same directory (or working copy) for both the branch and the trunk, if for e.g. a bug pops up in the app I switch to the trunk and commit the change there, and then switch back to my branch for my project development.

My questions are:

Is this a sane way to work with branches?

Are there any pitfalls that I need to be aware of?

What would be the optimal way to work with branches if separate working copies are out of the question?

I haven't had issues yet as I have just started doing this way but all the tutorials/books/blog posts I have seen about branching with SVN imply working with different working copies (or perhaps I haven't come across an explanation of mixed working copies in plain English).

I just don't want to be sorry three months down the road when its time to integrate the branch back to the trunk.


问:
Website Country Detection
I have a web crawler, and I'm looking for hints that will help me automatically detect a website country of origin.

And by country of origin I generally mean the country the website is targeting. For example:

http://www.spiegel.de/ -> Germany

http://www.lemonde.fr/ -> France

http://publico.pt/ -> Portugal

http://www.elpais.es/ -> Spain

I know there's not a foolproof way of doing it, so I will likely rely on a scoring system.

The domain name;

The content language;

The server's IP address;

Whois information;

What additional parameters would you use?

For the previous examples a combination of domain and content language will do, but many websites have a .com domain and a language spoken in more than one country...

答:
Don't remember that? xkcd - map of online communities 2, in 3D

Internet is about user groups, not their realworld political or geographical relations. Thus, you'll not gaining much from knowing anything about all sites larger than a school page or a yellowpages list. All options now are "filter by hosting IP", "filter by page language" and "[x] detect specific language district patterns" .

However, if you still need more detailed info, well.. think of imageshack.us, tinypic/imgur or any other picture hosting. They know both the client IPs and the referring addresses of sites which hotlink to the hosted images, and they can tell, how much visitors from which country have seen the image hosted at some page.

So if you want that tracking - start an image hosting, attack the resource under research with picture postings, links and/or 1x1 hidden transparent GIF/PNG images hotlinked with unique URI, and voila, you have that visitor map.

Title: Website Country Detection


答:
It is a well known problem: Arbitrary precision arithmetic

When the language you are using doesn't resolve this problem, first try to find a third party library that does. If you don't find it or you are curious, try to implement it; the wikipedia article has a good references to classical implementations.

Title: Handling extremely large numbers in a language which can't?

Body:
I'm trying to think about how I would go about doing calculations on extremely large numbers (to infinitum - intergers no floats) if the language construct is incapable of handling numbers larger than a certain value.

I am sure I am not the first nor the last to ask this question but the search terms I am using aren't giving me an algorithm to handle those situations. Rather most suggestions offer a language change or variable change, or talk about things that seem irrelevant to my search. So I need a little guideance.

I would sketch out an algorithm like this:

Determine the max length of the integer variable for the language.

If a number is more than half the length of the max length of the variable split it in an array. (give a little play room)

Array order [0] = the numbers most to the right [n-max] = numbers most to the left

Ex. Num: 29392023 Array[0]:23, Array[1]: 20, array[2]: 39, array[3]:29

Since I established half the length of the variable as the mark off point I can then calculate the ones, tenths, hundredths, etc. Place via the halfway mark so that if a variable max length was 10 digits from 0 to 9999999999 then I know that by halfing that to five digits give me some play room.

So if I add or multiply I can have a variable checker function that see that the sixth digit (from the right) of array[0] is the same place as the first digit (from the right) of array[1].

Dividing and subtracting have their own issues which I haven't thought about yet.

I would like to know about the best implementations of supporting larger numbers than the program can.


答:
In my experience there are two parts to this question.

How detailed should the architecture be?

When should a certain level of detail be specified?

Answer to the first part, how detailed should the architecture be...

The architecture should have the least amount of detail that still ensures desired properties are appropriately promoted or inhibited by the system design.  Lower level details can be deferred to downstream designers (might be folks writing code, or perhaps another architect user of the system).  Remember that as an architect, your main focus is on system properties, the key quality attributes.  Depending on the property, you may need to design parts of the system to different levels of detail.

As an example, depending on the size of the system and the properties that you care about, for an architect overseeing a project with many teams, worrying about class names is too low level.  On the other hand, class names might be considered high-level design for a team lead responsible for implementing only a piece of the system.  (Aside: for small teams that do it all, you'll trade these hats daily.)

Answer to the second part, when should a level of detail be specified is a little more tricky...

One man's architecture is another man's detailed design - it all depends on your perspective of the system and the properties you are responsible for overseeing.  The only aspect of design that really needs to happen first is defining the boundaries between elements and layers of abstraction.  Once these are clearly defined, different elements can be designed at different levels of detail, generally (there are exceptions) concurrently.

When a level of detail must be specified could depend on a myriad of factors including...

Cost

Priority or value to the customer

availability (as are the people available to create it)

risk and uncertainty

technical dependencies

schedule

experience

and a lot more...

Title: What should be the "depth of design"?


问:
When and why should one create classes at runtime?
I have read many articles on the creation of dynamic types and classes at run time. For example, the TypeBuilder class in C# lets one create dynamic types. Python has this type function by which one can create dynamic classes. I have certainly good information on how I should create a class at run time, but I don't find enough information on why I should do this.

What is a scenario where one would be forced to create types at runtime?

答:
In Python you would create a class and/or type (metaclass) whenever you have a situation where you cannot generate said class or type when writing the code.

The two examples that spring to mind are database classes (one class per table, and you don't know the table layout ahead of time), and allowing user code in your application.

It's basically one more (advanced) tool to work with, but if you have the option of writing the class ahead of time, it's best to do it that way.


答:
When dealing with large numbers, probably one of the most fundamental design decisions is how am I going to represent the large number?

Will it be a string, an array, a list, or custom (homegrown) storage class.

After that decision is made, the actual math operations can be broken down in smaller parts and then executed with native language types such as int or integer.

I've included a very rudimentary ADDITION example in C# .Net that stores the resulting large number as a string.  Incoming "numbers" are also strings, so one should be able to send in very "large" numbers.  Keep in mind that the example is only for whole numbers to keep it simple.

Even with strings there is a limit in the number of characters or "numbers" in the number, as indicated here:

What is the maximum possible length of a .NET string?

But you could add some really big numbers, way beyond int32 or int64 native types for .Net.

Anyway, here's a string storage implementation.

///
/// Adds two "integers".  The integers can be of any size string.
///
/// <param name="BigInt1">The first integer</param>
/// <param name="BigInt2">The second integer</param>
/// <returns>A string that is the addition of the two integers passed.</returns>
/// <exception cref="Exception">Can throw an exception when parsing the individual parts     of the number.  Callers should handle. </exception>
public string AddBigInts(string BigInt1, string BigInt2)
{
    string result = string.Empty;

    //Make the strings the same length, pre-pad the shorter one with zeros
    int length = (BigInt1.Length > BigInt2.Length ? BigInt1.Length : BigInt2.Length);
    BigInt1 = BigInt1.PadLeft(length, '0');
    BigInt2 = BigInt2.PadLeft(length, '0');

    int remainder = 0;

    //Now add them up going from right to left
    for (int i = (BigInt1.Length - 1); i >= 0; i--)
    {
        //If we don't encounter a number, this will throw an exception as indicated.
        int int1 = int.Parse(BigInt1[i].ToString());
        int int2 = int.Parse(BigInt2[i].ToString());

        //Add
        int add = int1 + int2 + remainder;

        //Check to see if we need a remainder;
        if (add >= 10)
        {
            remainder = 1;
            add = add % 10;
        }
        else
        {
            remainder = 0;
        }

        //Add this to our "number"
        result = add.ToString() + result;
    }

    //Handle when we have a remainder left over at the end
    if (remainder == 1)
    {
        result = remainder + result;
    }

    return result;
}
```

I hope that gives you some ideas on your own implementation.  Please note, that the sample code probably isn't optimized or anything like that.  It is meant to give some ideas of how it could be done.

Body:
When dealing with large numbers, probably one of the most fundamental design decisions is how am I going to represent the large number?

Will it be a string, an array, a list, or custom (homegrown) storage class.

After that decision is made, the actual math operations can be broken down in smaller parts and then executed with native language types such as int or integer.

I've included a very rudimentary ADDITION example in C# .Net that stores the resulting large number as a string.  Incoming "numbers" are also strings, so one should be able to send in very "large" numbers.  Keep in mind that the example is only for whole numbers to keep it simple.

Even with strings there is a limit in the number of characters or "numbers" in the number, as indicated here:

What is the maximum possible length of a .NET string?

But you could add some really big numbers, way beyond int32 or int64 native types for .Net.

Anyway, here's a string storage implementation.

/// <summary>
/// Adds two "integers".  The integers can be of any size string.
/// </summary>
/// <param name="BigInt1">The first integer</param>
/// <param name="BigInt2">The second integer</param>
/// <returns>A string that is the addition of the two integers passed.</returns>
/// <exception cref="Exception">Can throw an exception when parsing the individual parts     of the number.  Callers should handle. </exception>
public string AddBigInts(string BigInt1, string BigInt2)
{
    string result = string.Empty;

    //Make the strings the same length, pre-pad the shorter one with zeros
    int length = (BigInt1.Length > BigInt2.Length ? BigInt1.Length : BigInt2.Length);
    BigInt1 = BigInt1.PadLeft(length, '0');
    BigInt2 = BigInt2.PadLeft(length, '0');

    int remainder = 0;

    //Now add them up going from right to left
    for (int i = (BigInt1.Length - 1); i >= 0; i--)
    {
        //If we don't encounter a number, this will throw an exception as indicated.
        int int1 = int.Parse(BigInt1[i].ToString());
        int int2 = int.Parse(BigInt2[i].ToString());

        //Add
        int add = int1 + int2 + remainder;

        //Check to see if we need a remainder;
        if (add >= 10)
        {
            remainder = 1;
            add = add % 10;
        }
        else
        {
            remainder = 0;
        }

        //Add this to our "number"
        result = add.ToString() + result;
    }

    //Handle when we have a remainder left over at the end
    if (remainder == 1)
    {
        result = remainder + result;
    }

    return result;
}

I hope that gives you some ideas on your own implementation.  Please note, that the sample code probably isn't optimized or anything like that.  It is meant to give some ideas of how it could be done.


问:
Is it possible to write software that doesn't need to be continually modified?
I have written a lot of software in many different languages, and I've also "written" hardware for use with FPGAs using Verilog and VHDL.

I tend to enjoy writing hardware more than software, and I think one of the primary reasons is that it is possible to write hardware that is "done" and never needs to be modified: you define the interfaces and the functionality, write a test bench, implement the hardware module, then test the heck out of it using a simulator. Then you can rely on that hardware module as a building block to create something bigger and better: if you need to add a feature to that module, you create a second module and add the functionality there. You never throw away the original module since it is working just fine and can still be useful.

One of my main frustrations with software is that it is never "done". There is always another feature to add. Often when adding a feature it introduces a bug somewhere else that was working just fine before. This doesn't happen in hardware as long as the interfaces are not violated.

To be clear, I'm not advocating building one version of something with a list of features and that's it forever: I'm in favor of iterations and multiple releases over time to add new features. I just don't want to poke the code on the left and find a bug on the right, and this seems to happen after adding a new feature.

Is it possible to write software in a similar way in which hardware is "written"?  Is there a good software development methodology that allows forward progress to always be made and allows new functionality to be added without needing to rewrite existing code and introduce new bugs?

答:
I would also point out that software bugs in hardware can often kill people. So there is more care taken to thoroughly determine the requirements and extensively test them up front. And those requirements dont need to change until the hardware does. And since new hardware may require a rewrite, I suspect the cruft doesn't build up so much either.

Business requirements on the other hand change constantly, sometimes you can hardly get one requirement into production before a change is asked for. Sometimes, I've had the requirement change multiple times before it does get to production. This is a result of several things. First the project stakeholder on the business side is often less interested in spending the time to thoroughly define what he wants because he is "busy" and "important" and people won't die and the families sue him or get him thrown in jail if he blows off his part of the process. Second, the project stakeholders tend to actually have a better idea of what they want the hardware to do as it is less abstract to them. They really don't know what they want until they see it. Which is less of aproblem with Hardware.


答:
it is possible to write hardware that
  is "done" and never needs to be modified: you define the interfaces
  and the functionality, write a test bench, implement the hardware
  module, then test the heck out of it using a simulator. Then you can
  rely on that hardware module as a building block to create something
  bigger and better: if you need to add a feature to that module, you
  create a second module and add the functionality there. You never
  throw away the original module since it is working just fine and can
  still be useful.

In the software world, we call that "module" a library, and we use it just the same way.  Many libraries are built to the point that they function well, and then sit contentedly doing their jobs with no change until Something Important leads to the next revision.  Think of them as software that's been potted with epoxy :-)

One of my main frustrations with software is that it is never "done".
  There is always another feature to add. Often when adding a feature it
  introduces a bug somewhere else that was working just fine before.
  This doesn't happen in hardware as long as the interfaces are not
  violated.

Hogwash.  Perhaps you're personally better than many other non-soldering-iron "hardware" people, but I've seen any number of bad circuit designs, failing chips (e.g., the famous Intel "f00f" problem), but that doesn't speak to the field as a whole.  And as faux-hard ware becomes "softer", the problems become more difficult to prevent.

Is it possible to write software in a similar way in which hardware is
  "written"? Is there a good software development methodology that
  allows forward progress to always be made and allows new functionality
  to be added without needing to rewrite existing code and introduce new
  bugs?

Yes.  We just don't use those methodologies much.  They tend to be extremely expensive to operate, and most programmers don't enjoy working within their restrictions.  But when human life is involved, for example, well, yeah, we try not to kill the users.

One last point: Software has a different financial model from hardware, even programmed hardware.  Most non-consumer software, and some consumer software also, is sold in a manner that encourages change.  When you can tell a business "Pay us $10,000 now plus 18% a year", you can essentially re-sell the product every few years.  But to justify that fee, you need to give the customer the changes they want.  Hmm ... thinking of Apple's hardware-obsolescence curve, perhaps this isn't a difference after all - hardware just makes you really re-buy it!

Title: Is it possible to write software that doesn't need to be continually modified?

Body:
I have written a lot of software in many different languages, and I've also "written" hardware for use with FPGAs using Verilog and VHDL.

I tend to enjoy writing hardware more than software, and I think one of the primary reasons is that it is possible to write hardware that is "done" and never needs to be modified: you define the interfaces and the functionality, write a test bench, implement the hardware module, then test the heck out of it using a simulator. Then you can rely on that hardware module as a building block to create something bigger and better: if you need to add a feature to that module, you create a second module and add the functionality there. You never throw away the original module since it is working just fine and can still be useful.

One of my main frustrations with software is that it is never "done". There is always another feature to add. Often when adding a feature it introduces a bug somewhere else that was working just fine before. This doesn't happen in hardware as long as the interfaces are not violated.

To be clear, I'm not advocating building one version of something with a list of features and that's it forever: I'm in favor of iterations and multiple releases over time to add new features. I just don't want to poke the code on the left and find a bug on the right, and this seems to happen after adding a new feature.

Is it possible to write software in a similar way in which hardware is "written"?  Is there a good software development methodology that allows forward progress to always be made and allows new functionality to be added without needing to rewrite existing code and introduce new bugs?


问:
Recommend a text that explains the physical implementation of C (stack, heap, etc)
One of the most popular questions on stackoverflow.com is this one:

https://stackoverflow.com/questions/4025768/what-do-people-find-difficult-about-c-pointers

Many of the answers seem to gravitate toward the fact that students often don't get a good understanding of what is physically going on when code executes... the very most basic part of this seems to be stack/heap.

I've read through K&R twice and finally have a good understanding of the language, but I don't think that is enough.  Nearly every tough question here has the work "stack" or "heap" in the answer, and while I have a limited understanding of what those mean just from context and wikipedia searches, I prefer the comprehensive approach of a textbook.  So, please recommend a textbook which explains things like stack, heap, memory allocation, etc from a physical standpoint, as it relates to C programming.

I tried asking this question on stackoverflow and apparently it was not the right place to ask it.  So I hope this site is a better location.  If not, please consider migrating it to the proper stackexchange site.  Thanks.

答:
Answering my own question.  This may not be the best book for an explicit understanding of C, but it is an excellent book for learning how memory (and all hardware) work with your software.  It's helped me immensely.  Once I finish it I will tackle some of the other books suggested by the other responders (thanks!).

The Elements of Computing Systems:
Building a Modern Computer from First Principles

It's a book/course with the nickname "from NAND to tetris in 12 steps" which teaches you how to build a modern computer with high level applications starting from very basic digital building blocks. Projects in the book include building hardware (gates, adders, ALU, registers, RAM, ROM, CPU, and eventually an entire computer) and then software for it, starting with native machine instructions, then writing an assembler, virtual machine, compiler, OS, and applications. There's really nothing else like it, an entire top to bottom view of a computing system in one digest!


问:
Maintainability of Boolean logic - Is nesting if statements needed?
Which of these is better for maintainability?

```<code>if (byteArrayVariable != null)
    if (byteArrayVariable .Length != 0)
         //Do something with byteArrayVariable
</code>```

OR

```<code>if ((byteArrayVariable != null) && (byteArrayVariable.Length != 0))
  //Do something with byteArrayVariable
</code>```

I prefer reading and writing the second, but I recall reading in code complete that doing things like that is bad for maintainability.

This is because you are relying on the language to not evaluate the second part of the if if the first part is false and not all languages do that.  (The second part will throw an exception if evaluated with a null byteArrayVariable.)

I don't know if that is really something to worry about or not, and I would like general feedback on the question.

Thanks.

答: The second style can backfire in VBA since if the first test is if the object generated, it will still do the second test and error out.  I've just got in the habit in VBA when dealing with object verification to always use the first method.</p>


答:
Is it possible to write software in a similar way in which hardware is "written"? Is there a good software development methodology that allows forward progress to always be made and allows new functionality to be added without needing to rewrite existing code and introduce new bugs?

I recommend you look into "formal methods" for verifying the correctness of designs and software. The simulator tools you use for hardware design are trying to do something close. I do not believe that tools for formal methods are anywhere close to being useful in industry at this time, and the only industries that have strong incentives to be defect-free are avionics and medicine (interestingly enough, the FDA clearly says "software is different from hardware" on that link). Furthermore, if you are developing with Verilog/VHDL, then you are sticking with binary logic. This drastically reduces complexity. There isn't going to be a hardware equivalent to a Y2K issue.

The big problem is that things are complex. And you cannot eliminate complexity, you can only move it around.


问:
What should I be looking for when evaluating unit testing libraries and tools?
I'm in the process of choosing new unit testing tools for soon to be started project. There are plenty of them!

The basic requirements I have would be that it can run tests on at least Windows and Linux, it is C++/C++03 compatible, it can execute tests in parallel (e.g., to take advantage of multi-core processors), and it is able to be run from the command line. But these are pretty broad requirements, and haven't narrowed down the field.

To try and do that, I'm looking into potential gotchas and pitfalls of different types of implementations. For example, if I wanted to use a unit testing engine in  higher level language like Python, would it still produce output formatted like C unit tests? My main intent here is to use the same storage and report tools for both C++ and Python results tests.

I'm also wondering if it's necessary to have a specific engine to run the tests, or is it enough to have them integrated into our continuous integration engine (buildbot).

Are these two concerns above valid? What else should I be concerned about when evaluating unit testing engines?

答:
My experiences involve CruiseControl.NET and Team Foundation Build. I'm a .NET developer myself. These come from my experiences, and only include the experiences where we had testing as part of the build process, so if they don't match your environment, sorry.

I'm also wondering if it's necessary to have a specific engine to run the tests, or is it enough to have them integrated into our continuous integration engine

If you are doing a build every check-in, it is possible to have builds triggered before the previous build is finished running. How do you want to handle situations like this? For example, if it takes 30 minutes to run through the entire test suite, and code gets checked in every 15 minutes, do you want to skip a few builds? Skip some tests? Stack them up, build them in order and get back to Bob that he broke the build with his check-in 5 hours ago?

Team Foundation Build can use multiple cores for builds and tests with 2010 (previous versions could only use multiple cores for C++ builds). CruiseControl.NET can run separate threads, but reading the documentation, it appears that each project can be on its own thread, but that you can't have multiple threads per project (I may be wrong). We've never had a multi-core machine for builds in the environments I've worked in, so I can't speak to how good/fair/bad they are (or wrong I am).

At one previous employer, we included Python scripts in the build, but we didn't have any testing set up to test the Python. NANT was used for the .NET components.

I'm also wondering if it's necessary to have a specific engine to run the tests

I never had time to do it, but at a previous employer (we sold "shrinkwrap" software), we had many bugs that were operating system specific (and sometimes service pack specific), so one of my goals was to set up multiple test machines with different OSes (both 32 + 64 bits and all the various flavors of desktop and server Windows from XP onwards). The build machines were simple and older WinXP machines (or virtuals) because that was all the "hardware" we were allowed by the managers. Instead, all tests ran on the build machine. We also set up validation suites as collections of unit tests, although these were not run for minor updates.


问:
How should repetitive calendar tasks be stored in the database?
This is for a small personal project for micro-management. Basically, I store tasks in a SQLite3 database that looks like this:

```<code>    id INTEGER PRIMARY KEY AUTOINCREMENT
    label TEXT
    deadline INTEGER
</code>```

So each task has a due date (deadline) that is stored as a Unix Time Stamp. So far so good, I can do entries such as "tomorrow: visit grandma" and a new row gets created with "visit grandma" as the label and tomorrow transformed as Unix time for deadline.

Now I would like to enter new type of tasks: routines - tasks repeated on a time pattern, like "everyday: clean kitchen". How can such tasks be stored or modeled?

For the moment, I am thinking that, in the case of a task that needs to be done everyday, to generate new rows in my table that would have the same label, and the deadline field incremented by one day. In this case, I need to fix a limit in the future. For example, if I create a routine for every day, it creates a new row for everyday of the remaining year.

Is there a simpler way to do this? Am I missing some obvious database design principles?

答:
You can use two tables: one for the description of the tasks, the other for their status (done/not done, and other information: time spent, exit status, location of the log file, etc.)
The description table would contain the name of the task, and the date or frequency at which it should be run: there would be only one row per task.
Every day, a process would populate the status table for the tasks to do today, from the description table (you could populate one week or one month in advance).

Generating the status table programmatically gives you all the flexibility you want for the frequency (e.g., "every weekday except bank holidays for country X" -- it could even be stored as a string). Having a status table allows you to check if or how often the tasks fail (for instance: "I was supposed to run every day: how often did I have time to do it?").


问:
Best practice to query data from MS SQL Server in C#?
What is the best way to query data from a MS SQL Server in C#?

I know that it is not good practice to have an SQL query in the code.

Is the best way to create a stored procedure and call it from C# with parameters?

```<code>using (var conn = new SqlConnection(connStr))
using (var command = new SqlCommand("StoredProc", conn) { CommandType = CommandType.StoredProcedure }) {
   conn.Open();
   command.ExecuteNonQuery();
   conn.Close();
}
</code>```

答:
Using stored procedures is one way, and has been in widespread use for many years.

A more modern way to interact with SQL Server databases from C# (or any .NET language) is to use Entity Framework. The advantage of Entity Framework is that it provides a higher level of abstraction.

To quote from Microsoft (https://msdn.microsoft.com/en-us/data/jj590134 ):

The ADO.NET Entity Framework enables developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. The goal is to decrease the amount of code and maintenance required for data-oriented applications. Entity Framework applications provide the following benefits:

Applications can work in terms of a more application-centric
conceptual model, including types with inheritance, complex members,
and relationships.

Applications are freed from hard-coded dependencies on a particular
data engine or storage schema.

Mappings between the conceptual model and the storage-specific schema
can change without changing the application code.

Developers can work with a consistent application object model that
can be mapped to various storage schemas, possibly implemented    in
different database management systems.

Multiple conceptual models can be mapped to a single storage schema.

Language-integrated query (LINQ) support provides compile-time syntax
validation for queries against a conceptual model.

The use of an ORM vs Stored Procedures involves tradeoffs, particularly in terms of security and where the logic resides.

The "classic" approach to development with SQL Server is to have the application logic reside in stored procedures and programs only given security rights to execute stored procedures, not update tables directly. The concept here is that stored procedures are the business logic layer for the application(s). While the theory is sound, it has tended to fall out of favor for various reasons, being replaced by implementing the business logic in a programming language like C# or VB. Good applications are still implemented with a tiered approach, including separation of concerns etc. but are more likely to follow a pattern like MVC.

One downside of implementing logic in the ORM rather than the database is ease of debugging and testing data integrity rules by those responsible for the database (DA or DBA). Take the classic example of transferring money from your checking to savings account, it is important that this be done as an atomic unit of work, in other words sandwiched in a transaction. If this sort of transfer is only allowed to be done through a stored procedure it is relatively easy for the DA and auditors to QA the stored procedure.

If on the other hand this is done via an ORM like Entity Framework and in production it is discovered that on rare occasions money is taken from checking but not put into savings debugging may be far more complex, particularly if multiple programs are potentially involved. This would most likely be an edge case, perhaps involving peculiar hardware issues that need to occur in a particular sequence etc. How does one test for this?


问:
How important are daily builds?
One of the criteria of the Joel Test is daily builds. The idea is that if the build is broken, whoever broke it is around to fix it up. If the build cannot be fixed, everyone will have to check out an old version and work on that. I can understand how this can be pretty bad on centralised version control where it is important to avoid merging and branching as much as possible, but this only sounds like a minor nuisance for distributed version control. Do you agree with this? Are there other reasons why daily builds are important?</p>

答: Daily builds aren't important.  Daily builds that always are successful are (or ones where it's only broken for an hour).  Having CI when the build is broken 70% of the time isn't very useful, because if the thing is mostly broken it doesn't help you identify an error.

Title: How important are daily builds?


答:
Your answer on this depends on your philosophy (believe it is Chicago vs London? I'm sure someone will look it up).  The jury is still out on this on the most time-effective approach (because, after all that's biggest driver of this- less time spent on fixes).

Some approaches say test only the public interface, others say test the order of each function call in every function.  Plenty of holy wars have been fought.  My advice is to try both approaches.  Pick a unit of code and do it like X, and another like Y.  After a few months of test and integration go back and see which one fit your needs better.

Title: Should we test all our methods?

Body:
So today I had a talk with my teammate about unit testing. The whole thing started when he asked me "hey, where are the tests for that class, I see only one?". The whole class was a manager (or a service if you prefer to call it like that) and almost all the methods were simply delegating stuff to a DAO so it was similar to:

```<code>SomeClass getSomething(parameters) {
    return myDao.findSomethingBySomething(parameters);
}
</code>```

A kind of boilerplate with no logic (or at least I do not consider such simple delegation as logic) but a useful boilerplate in most cases (layer separation etc.). And we had a rather lengthy discussion whether or not I should unit test it (I think that it is worth mentioning that I did fully unit test the DAO). His main arguments being that it was not TDD (obviously) and that someone might want to see the test to check what this method does (I do not know how it could be more obvious) or that in the future someone might want to change the implementation and add new (or more like "any") logic to it (in which case I guess someone should simply test that logic).

This made me think, though. Should we strive for the highest test coverage %? Or is it simply an art for art's sake then? I simply do not see any reason behind testing things like:

getters and setters (unless they actually have some logic in them)

"boilerplate" code

Obviously a test for such a method (with mocks) would take me less than a minute but I guess that is still time wasted and a millisecond longer for every CI.

Are there any rational/not "flammable" reasons to why one should test every single (or as many as he can) line of code?


答: It depends on the needs of the customer.  In a contract situation there are probably acceptance tests.  In-house is usually a slapjob with little testing.  Consumer stuff is usually highly covered in frequent functionality but rough around the edges.</p>

Title: Is software testing actually done on professional projects?

Body:
I've been involved with many projects in several companies because I've been a developer for a long time and I'm a contractor.

I estimate that less than 20% of projects are methodically tested. With methodically tested I mean any testing beyond ad-hoc no plan testing.

I also estimate that less than 10% of projects are thoroughly methodically tested where they have dedicated testers as part of the team, test plan document, where developers write automated tests and then they also track test coverage and measure results.

Two questions

What are your percentage estimates about this issue?

What's your professional experience regarding software testing?

Additional note

Since methodical testing question may get quite biased answers (people like to brag about being superior to others) I encourage other developers (those that're not exposed to methodical testing) to provide their answer as well, because otherwise it will look like testing is being done everywhere... except at your company.


问:
How do you decide how much your software will cost?
If you are a solo developer, or have a leading role in a software company, you might have to decide how much your software will cost one or another day...  What is your experience with calculating how much your software costs for your customer? Why does this method it work for you?</p>

答:
Keep in mind that your price also will reflect the quality of your software in the eyes of potential buyers.  There is a psychological effect that if product A is priced higher than product B, product A will be seen as higher quality than B even without any supporting information.  This is true from canned beans to cars to houses.

Ultimately your business case for this software will define your price point (is this a one-off, extension of something existing, a loss-leader to gain new customers? etc.)


问:
Reengineering the project from scratch

Possible Duplicate:

  When do you rebuild an application or keep on fixing the existing one

I am currently working on a project that has been in development for the last few years used throughout the organization but the way the project has been coded the maintainability of it is completely shot.

Reading the code presents with pages and pages of Anti-Patterns and trying to identify the path of a business workflow takes on occasion days.  At this point I would probably classify the software in its current state as "Working by accident" rather then as intended.  So I am looking for some wisdom as to the following:

At what point would you consider simply dumping the project into an abandonware pile and starting from scratch?

P.S.  I understand that in a lot of cases organization would consider it cheaper to maintain the existing project.

答:
Keep in mind that in 10 years your code will be seen by someone as "a horribly architected mess that must be rewritten to save maintenance time."  And then 10 years after that, that design will be seen as a mess.  This is just the natural behavior of programmers.

Developers very frequently think everyone else's design and code is crap.  An unlike an industry where you bend steel and have even bigger things that do the bending, one person can go muck up the entire product and "redesign it," so we have this phenomenon in software engineering.

All that said, a successful business won't rewrite code that works, remember that 10 year old code might be a nightmare, but it also has 10 years of testing and bug fixes which won't be had on any new design.  The absolute worst is when a rewrite is committed to and never matches the functionality of the original (so people say "we used to be able to do that").  Sad but it happens.  If it is contract software it's a nearly impossible sell ("I'm going to pay you 300k for... the exact same thing I have now?  Do you think I'm stupid?").

Do not rewrite.  The inclination to rewrite everything from scratch is a frequent tendency in inexperienced developers.  Resist the urge, there is almost always no business sense in it.

Title: Reengineering the project from scratch


问:
typedefs and #defines
We all have definitely used typedefs and #defines one time or the other. Today while working with them, I started pondering on a thing.

Consider the below 2 situations to use int data type with another name:

```<code>typedef int MYINTEGER
</code>```

and

```<code>#define MYINTEGER int
</code>```

Like above situation, we can, in many situations, very well accomplish a thing using #define, and also do the same using typedef, although the ways in which we do the same may be quite different. #define can also perform MACRO actions which a typedef cannot.

Although the basic reason for using them is the different, how different is their working? When should one be preferred over the other when both can be used? Also, is one guaranteed to be faster than the other in which situations? (e.g. #define is preprocessor directive, so everything is done way earlier than at compiling or runtime).

答: Don't forget the implications of this in your debugger.  Some debuggers don't handle #define very well.  Play around with both in the debugger you use.  Remember, you'll spend more time reading it than writing it.</p>

Title: typedefs and #defines


问:
Date as software version number
Software developers don't typically use date as version number, though YYYYMMDD format (or its variances) looks solid enough to use. Is there anything wrong with that scheme? Or does it apply to limited 'types' of software only (like in-house productions)?</p>

答:
Problem with using Dates as Version Numbers

The answers here are good, but I didn't see anyone address this concern with using dates:  The user cannot determine how often modifications have been made.

What I am trying to say is that I can tell that Windows 3.1 and Windows 7 are far apart... and perhaps are incompatible.  Windows 95 and Windows 2000 tells me nothing more than the year in which the product was introduced.

For example, with Python, I know that version 2.7.2 has evolved from 2.4.6.  If I look further, I see that version 2.4.6 was released on December 19, 2008; and that version 2.7.2 was released on June 11, 2011.  From this, I can form an opinion about the stability (i.e., frequency of release) of a product.

If, instead, Python had used release dates, I cannot know how these products might be connected.  Further confusion would result, because Python 3.1.4 was also released on June 11, 2011 (the same as Python 2.7.2).

In short, I don't think that, by itself, date-versioning is valuable.

Title: Date as software version number