问:
Is it a good idea to measure the performance of a method by using unit test timeout?
In a project where there are non-functional requirements which specify the maximum execution time for a specific action, QA must check the performance of this action on a dedicated machine using precise hardware under precise load, both hardware and load being specified in the requirements.

On the other hand, some erroneous changes to the source code may severely impact the performance. Noticing this negative impact early, before the source code reaches source control and is verified by QA department, could be beneficial in terms of time lost by QA department reporting the issue, and by the developer fixing it several commits later.

To do this, is it a good idea:

To use unit tests to have an idea of the time spent executing the same action² n times,

To use per-test timeout through [TestMethod, Timeout(200)] attribute in C#?

I expect several problems with this approach:

Conceptually, unit tests are not really for that: they are expected to test a small part of a code, nothing more: neither the check of a functional requirement, nor an integration test, nor a performance test.

Does unit test timeout in Visual Studio measure really what is expected to be measured, taking in account that initialization and cleanup are nonexistent for those tests or are too short to affect the results?

Measuring performance this way is ugly. Running a benchmark on any machine¹ independently of the hardware, load, etc. is like doing a benchmark that shows that one database product is always faster than another. On the other hand, I don't expect those unit tests to be a definitive result, nor something which is used by the QA department. Those unit tests will be used just to give a general idea about the expected performance, and essentially to alert the developer that his last modification broke something, severely affecting performance.

Test Driven Development (TDD) is impossible for those tests. How would it fail, in the first place, before starting to implement code?

Too many performance tests will affect the time required to run the tests, so this approach is limited to short actions only.

Taking in account those problems, I still find it interesting to use such unit tests if combined with the real performance metrics by QA department.

Am I wrong? Are there other problems which makes it totally unacceptable to use unit tests for this?

If I'm wrong, what is the correct way to alert the developer that a change in source code severely affected performance, before the source code reaches source control and is verified by QA department?

¹ Actually, the unit tests are expected to run only on developer PCs having comparable hardware performance, which reduces the gap between the fastest machines which will never be able to fail the performance test, and the slowest machines which will never succeed at passing it.

² By action, I mean a rather short piece of code which spends a few milliseconds to run.

答: I think you're doing fine. This is exactly the point of having unit test timeouts: to check if something is taking way, way longer than it should. There are limitations to this approach, but you seem to be aware of them already, so as long as you keep those limitations in mind, I don't see a problem.


问:
Why is there such limited support for Design by Contract in most modern programming languages?
I recently discovered Design by Contract (DbC) and I find it an extremely interesting way to write code. Among other things, it would seem to offer:

Better documentation. Since the contract is the documentation, it's impossible for one to be out of date. Additionally, because the contract specifies exactly what a routine does, it helps to support reuse.

Simpler debugging. Since program execution stops the moment a contract fails, errors can't propagate, and the specific assertion violated will presumably be highlighted. This offers support during development and during maintenance.

Better static analysis. DbC is basically just an implementation of Hoare logic, and the same principles should apply.

The costs, in comparison seem to be rather small:

Extra finger-typing. Since the contracts have to be spelled out.

Takes some amount of training to get comfortable with writing contracts.

Now, being familiar with Python primarily, I realize that it is in fact possible to write up preconditions (just throwing exceptions for inappropriate input) and it's even possible to use assertions to test again certain postconditions. But it's not possible to simulate certain features such as 'old' or 'result' without some extra magic that would ultimately be considered un-Pythonic. (In addition, there are a few libraries that offer support, but ultimately I get the vibe it would be wrong to use them, as most developers don't.) I assume that it's a similar problem for all other languages (except of course, Eiffel).

My intuition tells me that the lack of support must be a result of some kind of rejection of the practice, but searching online has not been fruitful. I'm wondering if someone can clarify why most modern languages seem to offer so little support? Is DbC flawed or overly expensive? Or is it just obsolete due to Extreme Programming and other methodologies?

答:
Arguably they are supported in virtually every programming language.

What you need are "assertions".

These are easily coded as "if" statements:

```<code>if (!assertion) then AssertionFailure();
</code>```

With this, you can write contracts by placing such assertions at the top of your code for input constraints; those at the return points are output constraints.  You can even add invariants throughout your code (although aren't really part of "design by contract").

So I argue they aren't widespread because programmers are too lazy to code them, not because you can't do it.

You can make these a little more efficient in most languages by defining a compile-time boolean constant "checking" and revising the statements a bit:

```<code>if (checking & !Assertion) then AssertionFailure();
</code>```

If you don't like the syntax, you can resort to various language abstraction techniques such as macros.

Some modern languages give you nice syntax for this, and that's what I think you mean by "modern language support". That's support, but its pretty thin.

What most of even the modern languages don't give you is "temporal" assertions (over arbitrary previous or following states [temporal operator "eventually"], which you need if you want to write really interesting contracts.   IF statements won't help you here.

ContentLicense: CC BY-SA 3.0

Body:
Arguably they are supported in virtually every programming language.

What you need are "assertions".

These are easily coded as "if" statements:

if (!assertion) then AssertionFailure();

With this, you can write contracts by placing such assertions at the top of your code for input constraints; those at the return points are output constraints.  You can even add invariants throughout your code (although aren't really part of "design by contract").

So I argue they aren't widespread because programmers are too lazy to code them, not because you can't do it.

You can make these a little more efficient in most languages by defining a compile-time boolean constant "checking" and revising the statements a bit:

if (checking & !Assertion) then AssertionFailure();

If you don't like the syntax, you can resort to various language abstraction techniques such as macros.

Some modern languages give you nice syntax for this, and that's what I think you mean by "modern language support". That's support, but its pretty thin.

What most of even the modern languages don't give you is "temporal" assertions (over arbitrary previous or following states [temporal operator "eventually"], which you need if you want to write really interesting contracts.   IF statements won't help you here.


问:
Who does test-driven development?
I've been working in the enterprise space for the past 4½ years and have noticed that generally speaking, enterprises are not conducive environments for the test-first style of development. Projects are usually fixed-cost, fixed-timeline and waterfall style. Any unit testing, if done at all, usually comes after development in the QA phase and done by another team.

Prior to working for an enterprise, I consulted for many small to medium sized companies, and none of them were willing to pay for a test-first style of development project. They usually wanted development started immediately, or after a short design stint: i.e., something more akin to Agile, though some clients wanted everything mapped out similar to waterfall.

With what types of shops, companies, and clients does test-driven development work
best? What types of projects tend to be conducive to TDD?

答:
Bear with me, as this will have a distinctively .Net flavour :p

With regard to types of projects that are amenable to the test-first approach, some things I'd look out for:

are you dealing with an existing code base? It's often prohibitively expensive to retrofit that a test suite in. Get an idea of how much inherited technical debt is there

certain platforms and frameworks are inherently test-unfriendly. Recent experience that is seared into my mind - SharePoint, for example is very hard (but not impossible) to TDD. For stuff like this, you may have to resort to a commercial isolator product like TypeMock can help.

certain implementation approaches lend themselves better to TDD than others. For example, ASP.Net with code-behinds - not so testable. ASP.Net MVC - testable. Silverlight with code-behinds - not so testable. Silverlight with MVVM - testable.

Ultimately, while "the organization" can do a lot to support the move to test-first, the key shift that needs to happen is in the developers' minds. I've given up on the "thou shalt write thine tests first" approach and instead look for teachable moments.

+1 on mpenrow's comment about not telling mgmt if they have an issue with it :p

Title: Who does test-driven development?

ContentLicense: CC BY-SA 2.5


问:
What license/EULA do I need for free to use software?
I am not sure what exactly I am looking for here, but here are the facts:

I will be offering a free to use software, free as in $0 cost only(not OSS). I need a piece of text included in the installer with agree/disagree, that would protect my rights. Specifically that I don't guarantee anything and shouldn't be held liable for their losses that the software might cause. I want to allow them to use the software for anything they like, but not allow to redistribute, sell, or reverse engineer it.

I am not even sure whether this text is technically a license, disclaimer, or end user license agreement. I doubt there is a ready to go template for what I am looking for, but any pointers would be greatly appreciated.

答: µTorrent is a free program - but not OSS - you should take a look at its EULA.</p>


问:
Can I use the database structure of an open source project?
I found a database structure for a CMS system and I want to copy it with the EF that this database is done in, is it OK to copy the database structure of open source software which is under GNU v2 lisence?

I don't want the rest of the software only the database structure.

答:
The easy answer is "Yes, if your software will be distributed under GPL v2".  Likewise, if you do not intend to distribute your software (e.g., you're coding for a company's internal use only), the GPL allows you use it however you want.

The question gets difficult if you intend to distribute the software and not under GPL v2, because then you have to determine whether the database design is sufficiently creative that it would be copyrightable and thus protected under the GPL.  The only safe answer, unless you've got good intellectual property lawyers, is "No".


答:
Went through the GNU V2 License copy and found nothing that may restrict your usage of the the db structure. But your end result should have the GNU V2 License as well. That is you must not restrict the source of your code.

Again this answer of mine comes without any warranty whatsoever.

GO here for more details.

Title: Can I use the database structure of an open source project?

Body:
I found a database structure for a CMS system and I want to copy it with the EF that this database is done in, is it OK to copy the database structure of open source software which is under GNU v2 lisence?

I don't want the rest of the software only the database structure.


答:
The way I read the GPL v2 Section 1:

You may copy and distribute verbatim copies of the Program's source
  code as  you receive it, in any medium, provided that you
  conspicuously and  appropriately publish on each copy an appropriate
  copyright notice and  disclaimer of warranty; keep intact all the
  notices that refer to this  License and to the absence of any
  warranty; and give any other recipients of  the Program a copy of this
  License along with the Program.

and Section 2:

You may modify your copy or copies of the Program or any portion of
  it,  thus forming a work based on the Program, and copy and distribute
  such modifications or work under the terms of Section 1 above,
  provided that you also meet all of these conditions:

You can do this because what you are doing is basically taking a copy of the entire software distributed under GPL v2 and removing all portions except the database structure which is part of software.  The only thing is that anything you will distribute that has this as part of your software will be distributed under GPL v2 license.


问:
How should I implement my chosen software license?
I have always kind of wondered, but never took my time to actually ask these questions regarding licensing. Most of these questions are presumably pretty basic, but I have no idea what I'm dealing with here.

The thing that baffles me the most is how exactly you "implement" the license for your OSS. Is just saying in the post you're publishing the code on, "by the way, this is licensed under GPL" enough? Or should something more delicate take place, like registering the software somewhere? Also,

If I just say I use a particular license, is that enough?

Do I add a copy of the license to the distributed code?

Am I required to add a header on every file detailing the licensing information? Do I manage this with my version control system (e.g. Subversion)?

Is the above not enough?

What are the most commonly used software licenses?

Are there any gotchas/licenses that are better left alone?

答:
My apology for being so long but I think this is one such question(s) which bothers first to most people and I didn't quite get a comprehensive compilation of this.

Actually many questions: I am trying to answer them one by one.

how exactly you "implement" the license for your OSS

Basically, the minimum need to define the terms of use in the license and put it along with the source. Understand the copyright (essentially authorship) on code is something different from license (to use and redistribute). But given this, you still leave upto the other person to be honest and not misuse the code and violate the license.  [More on this later, below].

If I just say I use a particular license, is that enough?

Perhaps no.

If I add a copy of the license to the distributed code?

Yes. That's perfectly fine.

Am I required to add a header on every file detailing the licensing
  information? (do I manage this with subversion?)

You don't have to add license information everywhere. You may have more than one license or change license. However, to identify exactly which all files are covered under the given license declaration, it is important to put your copyright notice everywhere on top or bottom (top is only due to convenience). It's like any other book, with first page printed like Copyright 2012 - Nico. Nothing else is much needed. See this: Do you have to include a license notice with every source file?

or should something more delicate take place, like registering the
  software somewhere?

There is no concept of registration with any license. If you have provided the license along with the code, only if there is a dispute,

What are the most commonly used software licenses?

I think the answer by mikera does a good job here so I won't repeat.

Now for the most intriguing (and implied) question:

So how do you enforce? How do you ensure that people don't violate the
  license and don't lie! After all it is too much to ask for that from
  people when already the code cannot control itself?

The simple bad news is - you can't quite do that with a mechanism like lock-n-key. Even if you believe that you can put someone in the court to bring judgement, each court has a jurisdiction (area of influence) and you might need to fight all people everywhere. Even if you have time and energy for this, you need to prove that they have indeed taken your code and violated! That's almost hard to do given that your code is available from the source.

Don't get upset. There are things you can do. It all depends on the context and purpose.

First off, you want to open your code for open source usage, so you are typically fine (and want) that people use your code.

Suppose, you want people to use your code for tinkering or research but pay for the commercial use, you can have dual license.

In general, if your code is well known in the industry - people who will tend to use your derived code - should also typically known to you. For example, given that ffmpeg is so famous - if anyone would claim they have a new codec to offer me, I would put a ref check to see if they are not just compiling and giving me. So potentially people wouldn't violate if you are a known player in the industry.  This is also another point why being on GitHub or SourceForge to distribute code makes sense (apart from the tools they help you with).

If you know the market well - you can actually check that someone is using this library, you case use - tool like strings that can produce object trace and can pick up your variables, routines name, enough to know that your code is being copied.  This is possible to outsmart though, but might just work in some cases. Of course, there is a theoretical limit to attain justice if people change all lines of code still keeping the logic - there is an interesting read here: Is it possible to rewrite every line of an open source project in a slightly different way, and use it in a closed source project?

Another funny measure (if you genuinely know someone is using your code and violating) - ffmpeg keeps what is known as Hall-of-shame as a public listing on who is violating their license.

Last but most critical - what if another open source take your code, wrap it up and make it freely available with a license that permits arbitrary commercial usage? Maybe the same group with another use will start using this in their own product. For this, you need strong license like GPL or MPL.

Another such issue is, what if someone actually use your name and do something that becomes harmful to society and you end up being on the wrong side of the court? For this, you need at least No warranty clause (and also sometimes no patent infringement clauses).

If you have more complex needs, you can do dual license. It's not complicated as much but out of scope from this answer. There are good answers on this subject on this very forum.

I think at this stage, if you have quite a bit of curiosity - just read a different clauses of these licenses, you can have some good understanding about it. I am not a lawyer, and most such question in P.SE are answered with i-am-not-lawyer tag; but they are not so obfuscated either - you can actually read the text and make quite a sense out of it. Once you read this, it might clear many of your doubt.

ContentLicense: CC BY-SA 4.0


问:
Max. SMS length that will reach all users
I'm building a grants management system where we're trying to find a list of lost users using a number of different means.

The first attempt is email but if we do not have an email address, we will try SMS.

Just wondering, before we get our business guys to start thinking up SMS messages, is there a maximum length or something which I should stay within to reach every phone with SMS capability?

Taking also in account that whilst we won't be sending an SMS to international numbers, a lot of the users will be from foreign countries and may have a foreign cell phone.

Also, messages will only ever be in English.

答:
SMS is 140 ascii characters or 70 ut16 characters  http://en.wikipedia.org/wiki/SMS#Message_size

Transmission of short messages between the SMSC and the handset is done whenever using the Mobile Application Part (MAP) of the SS7 protocol. Messages are sent with the MAP MO- and MT-ForwardSM operations, whose payload length is limited by the constraints of the signaling protocol to precisely 140 octets (140 octets = 140 * 8 bits = 1120 bits). Short messages can be encoded using a variety of alphabets: the default GSM 7-bit alphabet, the 8-bit data alphabet, and the 16-bit UCS-2 alphabet. Depending on which alphabet the subscriber has configured in the handset, this leads to the maximum individual short message sizes of 160 7-bit characters, 140 8-bit characters, or 70 16-bit characters. GSM 7-bit alphabet support is mandatory for GSM handsets and network elements, but characters in languages such as Arabic, Chinese, Korean, Japanese, or Cyrillic alphabet languages (e.g., Russian, Serbian, Bulgarian, etc.) must be encoded using the 16-bit UCS-2 character encoding...


问:
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>

答:
When I am under a stress situation, my code is meant to get the work done. Thats it. I do not concentrate on efficiency and other issues, which is bad, in my opnion.

I will work on it though.


问:
Is it good practice to keep the main function separate in its own file?
Is it good practice to have a main.c file that just has the main function in it and no other functions so that all other functions can be interfaced?

If there is no definitive rule, when is it good to do so and not to do so?

答:
Ideally, all work which can be thought of as part of re-usable code, should be created in the form of library. The balance work, is application which should be separate where main() will reside.

But main() alone doesn't have to sit in isolation. Functions like parse_arguments(argc,argv)  should be along with main rather then separate.


答:
We are using this approach as well, i.e. we have tests that measure runtime under some defined load scenario on a given machine. It may be important to point out, that we do not include these in the normal unit tests. Unit tests are basically executed by each developer on a developer machine before commiting the changes. See below for why this doesn't make any sense for performance tests (at least in our case). Instead we run performance tests as part of integration tests.

You correctly pointed out, that this should not rule out verification. We do not assume our test to be a test of the non-functional requirement. Instead, we consider it a mere potential-problem-indicator.

I am not sure about your product, but in our case, if performance is insufficient, it means a lot of work is required to "fix" that. So the turn-around time, when we leave this entirely to QA is horrible. Additionally, the performance fixes will have severe impacts on a large part of the code-base, which renders previous QA work void. All in all, a very inefficient and unsatisfying workflow.

That being said, here are some points to your respective issues:

conceptually: it is true, that this is not what unit tests are about. But as long as everyone's aware, that the test is not supposed to verify anything that QA should do, it's fine.

Visual Studio: can't say anything about that, as we do not use the unit test framework from VS.

Machine: Depends on the product. If your product is something developed for end-users with custom individual desktop machines, then it is in fact more realistic to execute the tests on different developers' machines. In our case, we deliver the product for a machine with a given spec and we execute these performance tests only on such a machine. Indeed, there is not much point in measuring performance on your dual-core developer machine, when the client ultimately will run 16 cores or more.

TDD: While initial failure is typical, it's not a must. In fact, writing these tests early makes it serve more as a regression test rather than a traditional unit test. That the test succeeds early on is no problem. But you do get the advantage, that whenever a developer adds functionality that slows down things, because s/he was not aware of the non-functional performance requirement, this TDD test will spot it. Happens a lot, and it is awesome feedback. Imagine that in your daily work: you write code, you commit it, you go to lunch and when you're back, the build system tells you that this code when executed in a heavy load environment is too slow. That's nice enough for me to accept, that the TDD test is not initially failed.

Run-time: As mentioned, we do not run these tests on developer machines, but rather as part of the build system in a kind of integration test.

Title: Is it a good idea to measure the performance of a method by using unit test timeout?

Body:
In a project where there are non-functional requirements which specify the maximum execution time for a specific action, QA must check the performance of this action on a dedicated machine using precise hardware under precise load, both hardware and load being specified in the requirements.

On the other hand, some erroneous changes to the source code may severely impact the performance. Noticing this negative impact early, before the source code reaches source control and is verified by QA department, could be beneficial in terms of time lost by QA department reporting the issue, and by the developer fixing it several commits later.

To do this, is it a good idea:

To use unit tests to have an idea of the time spent executing the same action² n times,

To use per-test timeout through [TestMethod, Timeout(200)] attribute in C#?

I expect several problems with this approach:

Conceptually, unit tests are not really for that: they are expected to test a small part of a code, nothing more: neither the check of a functional requirement, nor an integration test, nor a performance test.

Does unit test timeout in Visual Studio measure really what is expected to be measured, taking in account that initialization and cleanup are nonexistent for those tests or are too short to affect the results?

Measuring performance this way is ugly. Running a benchmark on any machine¹ independently of the hardware, load, etc. is like doing a benchmark that shows that one database product is always faster than another. On the other hand, I don't expect those unit tests to be a definitive result, nor something which is used by the QA department. Those unit tests will be used just to give a general idea about the expected performance, and essentially to alert the developer that his last modification broke something, severely affecting performance.

Test Driven Development (TDD) is impossible for those tests. How would it fail, in the first place, before starting to implement code?

Too many performance tests will affect the time required to run the tests, so this approach is limited to short actions only.

Taking in account those problems, I still find it interesting to use such unit tests if combined with the real performance metrics by QA department.

Am I wrong? Are there other problems which makes it totally unacceptable to use unit tests for this?

If I'm wrong, what is the correct way to alert the developer that a change in source code severely affected performance, before the source code reaches source control and is verified by QA department?

¹ Actually, the unit tests are expected to run only on developer PCs having comparable hardware performance, which reduces the gap between the fastest machines which will never be able to fail the performance test, and the slowest machines which will never succeed at passing it.

² By action, I mean a rather short piece of code which spends a few milliseconds to run.


答:
I am mostly inline with your thinking. Just putting up my reasoning with independent flow.

1. Make it work before making it better/faster

Before the code provides any performance measure (let alone guaranteeing) it should be first made correct i.e. make it functionally working. Optimizing code which is functionally wrong is not only waste of time, but puts impediments in development.

2. Performance of a system make sense only on full system

Typically, any meaningful performance always depend on a given infrastructure and it should only been seen under a full system. For example, during the mock test if the module receives answers from a local text files but in production environment it fetches from database, your earlier

3. Performance scaling should be done by objective

Once you have the functional system, you need to analyse performance of the system and find bottlenecks to understand where you need to scale up performance. Blindly trying to optimize every method even before you know the performance of a full system may incur useless amount of work (optimizing methods which doesn't matter) and may create your code unnecessarily bloated.

I am not quit aware of Visual studio functionality, but generally you need broader profiling tool.


问:
Why is Scala more scalable than other languages?
Scala is billed as a scalable language, a feature that's even included in its name:

The name Scala is a portmanteau of "scalable" and "language", signifying that it is designed to grow with the demands of its users.

What does "scalable" mean in the context of Scala? What makes Scala more scalable than, say, Java?

答:
That's not necessary the language itself that is more scalable than Java, as you say both languages can produces same bytecode.

But the Actor model and functional programming style can enhance scalability (by -in a nutshell- simplifying correct concurrency programming and reducing synchronization needs).

To get a better insight take a look at the actor model and compare it with traditional multi-threaded java application:

http://en.wikipedia.org/wiki/Actor_model

You can even use the Akka framework to create highly scalable Java application without coding in Scala:

http://akkasource.org/

OwnerDisplayName: prasonscala

OwnerDisplayName: Alois Cochard


答:
What limits Java's scalability in practice is not the JVM, it's the difficulty of writing correct concurrent code. Scala makes this easier through its support for functional programming, and the actor model.

Java can be very scalable when concurrency is easy, such as in web servers (each request is almost completely independant). But when it comes to parallelizing a single long-running task, it can be a real struggle to get right.

Title: Why is Scala more scalable than other languages?

Body:
Scala is billed as a scalable language, a feature that's even included in its name:

The name Scala is a portmanteau of "scalable" and "language", signifying that it is designed to grow with the demands of its users.

What does "scalable" mean in the context of Scala? What makes Scala more scalable than, say, Java?

OwnerDisplayName: Michael Borgwardt


答:
What Odersky says is (Slide 11, http://www.slideshare.net/rawwell/scalaliftoff2009pdf):

"Scala is deep where other languages are broad."

This means, scalable is meant in terms of flexibility and expressiveness. You can create your own control structures. E.g. the actors frameworks is a library, but it looks like it uses language features.

This means that Scala will scale according to the needed abstraction, not necessarily in terms of "answering 1.000.000 requests in a second" (but Scala is here strong, too).


答:
Scala stands for scalable language, it has nothing to do with performance characteristics.
You can find a better explanation here: http://www.artima.com/scalazine/articles/scalable-language.html

OwnerDisplayName: llemieng


答:
When Martin Odersky talks about scala as a scalable language choice, what he means is that the language itself is appropriate for:

scripting stuff

writing applications

writing monster "enterprise" (for the want of a better word) applications

He is most certainly not referring to scalability from the perspective of performance!

The fact that he can claim that scala is as appropriate for quick'n'dirty scripting as it is for large-scale enterprise deployment is roughly as follows:

Scripting

Scala is great for scripting because its type inference and functional style make it both concise and great for slicing and dicing collections etc.

Applications

Scala is great for writing applications because it is a statically type checked language with some great features for working in both functional and imperative styles. Scala is compatible with Java and hence you can leverage an enormous ecosystem of libraries.

Enterprise Deployment

Scala compiles to bytecode and runs on the Java Virtual Machine, a stable system with great performance, when compared to (so-called) dynamically typed (i.e. untyped) languages. Again, the fact that it is statically typed means that refactoring is made much easier on large codebases.


答:
I've had similar task some time ago and the final solution was somewhere in the middle between unit-testing and full-blown automated performance testing.

Some considerations in no particular order, which may be useful:

Performance testing by QA was labor-intensive and had it's own schedule (say, once in the iteration), so hitting source control was not a problem.

Our system was large and modular, unit-tests were too granular for our needs, and we've created special "fat" unit-tests carefully crafted to trigger performance problems in the specific areas of interest (they were categorized also, but this is an implementation detail).

Usual constraints for unit-tests still apply: they should be small, fast and to the point.

To exclude test framework influence, they were running by a special wrapper, so we knew exactly how much time the given operation take.

It is possible to write them before the actual implementation is complete (results may be irrelevant or useful, depending on the process, maybe the developers still experimenting with the implementation and would like to see how it's going overall).

They were running by CI server after each build, so total run time should be kept relatively short (if this is not so, it becomes considerably harder to pinpoint the exact change triggered the problem).

The CI server was powerful and had it's hardware fixed, so we counted this as dedicated machine (it is possible to use really dedicated server by using a remote build agent).

The test wrapper collected all relevant information (hardware specs, test names/categories, system load, elapsed time, etc.) and exported it as the reports or to the database.

We've had a gadget for JIRA pulling those reports and drawing nice charts by name/category/build number with some controls (overlay previous release to current, etc.), so the developers can quickly see their impact and managers can get an overview (some red, all green, you know, it's important for them).

It was possible to analyze how the project is going over time by using the collected statistics.

So, in the end, we had scalable, flexible and predictable system which we can quickly tune for our special requirements. But it required some effort to implement.

Returning to the questions. Conceptually unit-tests are not for that, but you can leverage features of your testing framework. I've never regarded test timeouts as a means to measure, it's just a safety net for hangs and such things. But if your current approach works for you, then continue to use it, be practical. You can always go fancy later if the need arises.


问:
Is there a general method to evaluate the optimality of an optimization algorithm?
is there a general method to evaluate the optimality of an optimization algorithm, for example an algorithm solving an otherwise NP-hard or NP-complete problem?

The only method I came up so far is comparing the results of the algorithm against already known optimal solutions.

If not, are there specific methods for some special problems?

EDIT To clarify: By optimality I mean how close the result is to an optimal solutions result.

答:
It depends on the kind of problem.

If there is a polynomial-time approximation scheme (PTAS) for the problem (e.g. Euclidian TSP), then you can get a solution that's arbitrarily close to the optimal solution in polynomial time. That means, for every e > 0, there is a polynomial time algorithm that will find an approximate solution to your problem, that is guaranteed to be within (1+e) of the optimal solution. In that case, you would just compare the runtime/memory complexity for two algorithms for the same values of e. If one algorithm can make the same "optimality guarantees" than the other, but at a lower running time/memory cost, then it's probably the better algorithm.

If the problem is APX, but not PTAS, i.e. if there are polynomial time approximation algorithms that are guaranteed to produce solutions that are within a constant factor of the optimal solution, then you can compare that constant factor. The one with the lower factor will produce the better solutions (but often at the cost of higher running time/memory costs)

If the problem is in neither of those classes, then I think the best you can do is to compare their solutions for a set of random problems, or for problems with known optimal solutions.


问:
Software to organize and maintain project documentation, specification?
I'm looking for software to organize and maintain projects internal documentation, specification, requirements, etc. Currently we store all documentation as lots of MS Word DOC files in a source control repository, which gives us version control, and that's nice. But you can't search this information, create links between them, categorize, collaborate.

Requirements, preferences:

Zero install on client side (WEB based).

Document version control.

Document annotations.

Document linking.

Full search (all documentation).

MS Word (*.doc) import\export.

WYSIWYG text editor.

Systems I have discovered and tried so far:

MediaWiki

XWiki

Confluence

答:
It is always better to keep specification and documentation under version control as it would give you the biggest leverage though the learning curve would be a bit steep. In case of a knowledge engine, I recommend the following

Trac - Easy to use bug-tracking system and knowledge engine. Written in Python and extensible, you would be up and running in a few minutes

MoinMoin - Full-fledged wiki engine. Again Python with a lot of features

Both have minimal interfaces, supports most of the wiki structures , fairly easy to deploy and maintain, support revisions, has a good WYSIWYG editor and you can even keep your documentation and specification also. Unless your projects are really huge, you could choose any of the above.


问:
How do you manage your knowledge base?
As programmers we have a lot of inputs:

Ebooks

Code snippets

Interesting emails

Documents

Web articles

Blog posts

StackOverflow questions

Podcasts
...

Which tools do you use to store, organize, search and consult all of this stuff?

Is there a silver bullet solution to handle this huge amount of data?

答: Something like Trello could be handy for this. It has checklists for notes, you can reorder notes, tag notes, add links, images, etc.</p>

Title: How do you manage your knowledge base?


问:
Open-source or closed-source for SaaS?

Possible Duplicate:

  Does making source code available affect your ability to generate revenue?

Initially I was going closed-source all the way, or at least until we
have a good reputation, and open-sourcing will only improve that rep.

Recently though, I've been thinking about open-sourcing the entire solution.

Various popular SaaS solutions have open-sourced under AGPL and are
generating revenue. For instance, Gitorious
(http://gitorious.com/subdomain) is AGPL but they make profit. OpenERP
 makes profit using the same sort of mechanism as Gitorious, advertising that they maintain the servers and keep servers online.

I am building an ecommerce solution, and am considering offering free
use of part of the system, pay per/month to use the entire system.

By making the solution open-source, couldn't a competitor just
download my project and offer it at a cheaper fee per/month? If I open-source, will that increase or decrease my revenue?

答: I am personally an open source advocate however when it comes to a product you wish to profit from I would not release source. However, still allow the users to interact with your application via hooks or an API so that they feel the flexibility and customisation factors of your application.</p>

Title: Open-source or closed-source for SaaS?


问:
How can I motivate myself to start learning more?
I've been interested in programming for a while now, and have been slowly, slowly, slowly working on things over the years. However, I don't feel like I've learned much.

I've only really stuck with familiar languages (Java, C# and I've tried a little bit of PHP). The problem is that in those languages, I've only brushed upon the surface of them and have restricted myself to doing fairly simple things.

For example, as a Java project, I've downloaded the source code for some game and changed a few things to my liking, but nothing terribly difficult. In C#, I've made a few WinForm and console projects to do some repetitious or routine tasks for me, which is nice, but again nothing too complicated.

I've just barely begun to grasp the concept of classes, multithreading and some basic but essential tools that are required in modern object-oriented programming. ("Why can't I just shove everything into one monster-sized class?" "Why can't I just run everything in one thread?" are questions I used to wonder about)

I've never made a large project by myself. Ultimately, my kind of "dream" hobby project is that I would like to create a game using DirectX technology. I say that because I've used XNA but it requires the user to install a framework to get it running, and I also feel that if I use the framework, that a lot of the back-end work is being obscured from me. (DirectX or OpenGL seem to be about as close to the machine as I can get without going overboard in complexity. DirectX is also installed on most [if not all] Windows machines that plan on running games.)

But I haven't even begun to even think about starting that. The amount of things I need to know to undertake a task is absolutely overwhelming. I wouldn't know where to begin. Likewise, I also feel inadequate because I've restricted myself to [what I see as] easy languages. I feel like I should start learning some scripting language or learn this or learn that, which is quite daunting.

--

tl;dr: I've been slowly teaching myself to program for a while now, but have been restricting my knowledge to limited languages and only scratching the surface of what I can do. I want to learn more and possibly start a decent-sized project (I can only make so many text-based RPGs and calculators), but the massive amount of knowledge I'll need is very intimidating.

One of my concerns is that I know so little about programming languages in general. Is it better to learn several languages or to be able to delve deep into one single language?

How can I motivate myself to learn more?

Am I thinking about this the wrong way?

答:
As the others said, take baby steps. You make progress faster that way.

Also, you need inspiration. I got that from

Isaac Asimov, "I Robot"

Marvin Minsky, "Computation: Finite and Infinite Machines"


答:
If your product is novel, and you believe that you will be able to profit greatly from each innovative step that you take early in the process, then open source doesn't make much sense. There's no entrenched player that you're trying to catch up to, so you don't need to enlist the help of others.

The only reason to open source something when you are in a position to profit off each and every investment in the code base would be that it is not part of your core competency, and you know that it will not evolve and grow with other advances in technology. This is basically how Unix became dominant when produced by AT&T (Unix's license and the market was in such a state that it was basically like open source for the time, which is why for instance BSD Unix evolved out of said code base), because they did not want to be in the OS business. If they had productized it, some other OS would have made the necessary innovations to bring cross-platform computing and the resultant benefits to the computing world.

If, however, the advantage that you have over your competition is access to data in a timely manner, or extremely high caliber service, and you need to differentiate yourself from your competition, then it makes some sense to open source the bits that you want your users to be able to improve for themselves.

Personally I think in the SaaS world, this is often better accomplished through having a strong, well documented public API. Look at the success of Amazon's Web Services as a perfect example for that.

Title: Open-source or closed-source for SaaS?

Body:
Possible Duplicate:

  Does making source code available affect your ability to generate revenue?

Initially I was going closed-source all the way, or at least until we
have a good reputation, and open-sourcing will only improve that rep.

Recently though, I've been thinking about open-sourcing the entire solution.

Various popular SaaS solutions have open-sourced under AGPL and are
generating revenue. For instance, Gitorious
(http://gitorious.com/subdomain) is AGPL but they make profit. OpenERP
 makes profit using the same sort of mechanism as Gitorious, advertising that they maintain the servers and keep servers online.

I am building an ecommerce solution, and am considering offering free
use of part of the system, pay per/month to use the entire system.

By making the solution open-source, couldn't a competitor just
download my project and offer it at a cheaper fee per/month? If I open-source, will that increase or decrease my revenue?


问:
Is iterative documentation development possible, and does it deliver effective documentation?
I have a project for university which I won't be starting immediately, but have been thinking about for a reasonably long amoung of time. I understand that University project development isn't like industry (I'm currently an intern myself) so the situation that I'll be pointing out at the moment will probably seem somewhat ridiculous to actual software developers. ^^'

The project itself requires that we document a lot of our work. So, besides delivering code, which counts toward some of the marks, we have to deliver documents including:

A Requirements Analysis Document

A Project Plan

A planned list of Use Cases, Object and Dynamic Models and Acceptance Tests

Documentation of the testing process and how successful the tests were

Some other discussions and analyses of time usage, etc.

These deliverables are to be delivered in the following manner:

RAD first

Followed by Project Plan, Use Cases, Models and Tests (approximately 3 weeks later)

Lastly, the documentation of the actual program, the testing process, etc. + the actual programming itself (approximately 5 weeks later)

So, from what I understand, this is really geared towards a Waterfall-style approach to the project. The only problem (in my opinion) is that this is a University project, and students already have enough pressure as it is with trying to develop projects at the end of semester during project week. I don't really want to be coding/developing/testing everything at the end of semester, when I'll be panicking with however many other assessments I have to deal with.

I'd like to at least try and do some sort of iterative development cycle that means we can start coding/prototyping early, have a continuous development cycle that isn't focused on doing everything at the last minute and not have so much pressure at the end of the semester to finish this project. And now comes my actual question(s):

Can I somehow reconcile having to deliver all that documentation with a fast, iterative/prototyping development cycle?

Are there strategies for generating documentation in an iterative manner?

Am I being entirely unreasonable asking this and expecting it to be do-able in University?

Also, I understand that this question is extremely localised, so I'd like to ask the same questions that I asked above in terms of industry, and whether or not a lot of these kind of problems that agile processes face are different for each team or company.

Anyway, sorry about how long this is, and if you have finished reading all the way down, thank you! If you could take the time to answer, I'd be very grateful! Thank you!

答:
The main concern (I have a similar problem with my job) is that if "The Process" demands that you deliver certain artifacts at certain times, and no one is allowed to challenge the almighty "The Process", then if you try, you will loose! It's not just a simple matter of it being a better way (Which iterative doc development is).

So what you need to do is work within the process, but find a way to work the way you want to as well. For instance, does your process allow document modification once submitted? If not, then no iterative develpment is possible. If so, then you need to think about the cost of delivery (In terms of your time, your credibilty etc), and manage that cost. If, for instance, its a file copy and nothing more, then go for it. If (like me) it's a peer review, revision release, impacts dozens of people and costs thousands of dollars, then think carefully and make sure the new document really adds value.

A common way to work is a bare essentials, minimum document that meets the needs of "The Process" at the start, followed later by a final "as built" update that not only reflects reality, but has the details where needed, and is brief where the code speaks for itself.


答:
Our coding standard requires that main() is in main.c. Other methods in main.c tend to be high level error handlers and helper functions for main (refer @Dipan answer "parse_arguments", as well as things like "display_help" etc.

A good rule to go by is when a funcion starts to do more than support the running application and start doing business logic, it's time it was out of main.c

Title: Is it good practice to keep the main function separate in its own file?

Body:
Is it good practice to have a main.c file that just has the main function in it and no other functions so that all other functions can be interfaced?

If there is no definitive rule, when is it good to do so and not to do so?


问:
Can cross-platform development be speeded by really specific, complete pre-coding design?
I'm green at programming but not entirely noobish. I taught myself some Java about five years ago, and I learnt me some Objective-C recently.

I was talking with a Unix guy a while back, and he said that if you do your object architecture and design very completely and correctly, cross-platform development becomes really easy. All you have to do is take the description of each element and implement it. Since your design is so complete, each individual element is composed of relatively simple tasks.

I'd like to get some feedback on that concept. In theory it makes sense, but programming is about execution.

And if you agree with the concept, can you point me to some material that would help me understand how to build those kind of complete, specific designs?

答:
Big upfront design is proved to be not useful for any project. You can design as much as you want, you will never get to a point when you will be able to specify everything so detailed and so clear that porting to another operating system will be very easy.

Don't get me wrong, design is necessary, but not in very much detail. It is usually impossible to know upfront all the problems you will encounter on your way to plan for multiplatform deployment.

However, other practices and principles can and will help you achieve a design that is easy enough to be modified for any reason.

Look for these:
- SOLID principles
- Design Patterns
- Clean Code
- Orthogonality, Decoupling, etc
- Test Driven Development + Unit Testing & Use Cases

These techniques, even it takes some time to learn, will help you much more. Basically, what you essentially need is a code sufficiently decoupled and enough orthogonal so it will allow you to do implement the modifications.

There are also some classic design patterns when you have to interact differently with different systems (check out Gateway, Adapter, Facade patterns ... as first thoughts).

OwnerDisplayName: Le Mot Juiced

OwnerDisplayName: Patkos Csaba


问:
How can I sell a legacy program rewrite to the business?
We have a legacy classic ASP application that's been around since 2001.  It badly needs to be re-written, but it's working fine from an end user perspective.

The reason I feel like a rewrite is necessary is that when we need to update it (which is admittedly not that often) then it takes forever to go through all the spaghetti code and fix problems.  Also, adding new features is also a pain since it was architect-ed and coded badly.

I've run cost analysis for them on maintenance but they are willing to spend more for the small maintenance jobs than a rewrite.  Any suggestions on convincing them otherwise?

答:
First, create a category for typical changes in terms of SLOC (and function points if it involves changes to UI elements.)

Then look at previous code changes and see where they fit in the category model described above.

Do the same for new features (that is, treat code changes and new features differently unless a new feature involves significant change/cost on the existing code base.) If integrating a new feature is trivial, separate it from code changes. If its integration with existing code base is significantly costly, lump it with the code changes.

Then, for each categorized code change (or new feature), determine 1) how long it took to complete, 2) how long was it supposed to take to complete, 3) how many people were actually involved in the completion, and 4) how many people were initially thought to be required for its completion.

So now you should have a tabular presentation of delivered artifacts (code changes and new features), each with columns indicating estimated and actual resources (hours, people) consumed.

You can then assume a ballpark average engineer salary/hour (say $40/hr). Multiply that by 2 to indicate total cost of engineer/hour (an estimation of hourly salary, electricity, office amenities and rental, etc.) It doesn't have to be accurate, just realistic enough.

For each delivered artifact A, you can compute the following:

```<code>estimated_cost(A) := avg_hr_salary * estimated_hours(A) * estimated_people(A)

approx_cost(A) := avg_hr_salary * (actual_hours(A) + estimated_hours(A))/2 * (actual_people(A) + estimated_people(A)/2

max_cost(A) := avg_hr_salary * actual_hours(A) * actual_people(A)
</code>```

With these relations (which must be based on actual code changes or new items... otherwise they are meaningless), you can can calculate (per category size), what is the % of a code change of that size to deviate from the estimated size (a % of failure), the approximate cost as well as the % the code change might actually reach a max. cost.

Chances are the % for maximally deviating from the estimated (minimal) cost resembles more and more a exponential distributation the larger the code change is.

With that date, you can tell your customer the following:

You to your customer:

This change you are requesting (A)
  might take 10K SLOC, on the old code
  base. Historical data indicates that
  it might take 2 people at a minimum
  (estimate_people), possibly escalating
  up to 3 people (actual_people). The
  probability of the change to cost
  (estimate_cost) is A%; B% for
  approx_cost, and %C for max_cost.

Now, this is key. You have to do the same computations for new requests (the type whose integration with the old code base involves not-significant changes on the later).

If you find that the estimated, approx and max costs for new requests of a given size is (hopefully) significantly less than the costs of old codebase changes of the same size, THEN you have an argument for a code rewrite. You have given sufficient evidence that the old code base is expensive to change compared to changes of the same magnitude in new code.

But if the costs of new code requests do not greatly diverge from old code changes of the same magnitude, you will have a hard time justifying  a code rewrite (and it might indicate that the problems are not only to the code base, but also in your development practices.)

Body:
First, create a category for typical changes in terms of SLOC (and function points if it involves changes to UI elements.)

Then look at previous code changes and see where they fit in the category model described above.

Do the same for new features (that is, treat code changes and new features differently unless a new feature involves significant change/cost on the existing code base.) If integrating a new feature is trivial, separate it from code changes. If its integration with existing code base is significantly costly, lump it with the code changes.

Then, for each categorized code change (or new feature), determine 1) how long it took to complete, 2) how long was it supposed to take to complete, 3) how many people were actually involved in the completion, and 4) how many people were initially thought to be required for its completion.

So now you should have a tabular presentation of delivered artifacts (code changes and new features), each with columns indicating estimated and actual resources (hours, people) consumed.

You can then assume a ballpark average engineer salary/hour (say $40/hr). Multiply that by 2 to indicate total cost of engineer/hour (an estimation of hourly salary, electricity, office amenities and rental, etc.) It doesn't have to be accurate, just realistic enough.

For each delivered artifact A, you can compute the following:

estimated_cost(A) := avg_hr_salary * estimated_hours(A) * estimated_people(A)

approx_cost(A) := avg_hr_salary * (actual_hours(A) + estimated_hours(A))/2 * (actual_people(A) + estimated_people(A)/2

max_cost(A) := avg_hr_salary * actual_hours(A) * actual_people(A)

With these relations (which must be based on actual code changes or new items... otherwise they are meaningless), you can can calculate (per category size), what is the % of a code change of that size to deviate from the estimated size (a % of failure), the approximate cost as well as the % the code change might actually reach a max. cost.

Chances are the % for maximally deviating from the estimated (minimal) cost resembles more and more a exponential distributation the larger the code change is.

With that date, you can tell your customer the following:

You to your customer:

This change you are requesting (A)
  might take 10K SLOC, on the old code
  base. Historical data indicates that
  it might take 2 people at a minimum
  (estimate_people), possibly escalating
  up to 3 people (actual_people). The
  probability of the change to cost
  (estimate_cost) is A%; B% for
  approx_cost, and %C for max_cost.

Now, this is key. You have to do the same computations for new requests (the type whose integration with the old code base involves not-significant changes on the later).

If you find that the estimated, approx and max costs for new requests of a given size is (hopefully) significantly less than the costs of old codebase changes of the same size, THEN you have an argument for a code rewrite. You have given sufficient evidence that the old code base is expensive to change compared to changes of the same magnitude in new code.

But if the costs of new code requests do not greatly diverge from old code changes of the same magnitude, you will have a hard time justifying  a code rewrite (and it might indicate that the problems are not only to the code base, but also in your development practices.)


答:
The intent of this license is to share developement and its benefits so you can copy what you wish from the GPL software but the "output" needs to also be released as GPL. The license clearly states that you are granted the right to make modifications under the terms of GPL

You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License

This term doesn't apply to "separated" parts of the program. But the database design isn't separated (like, for example some external library). The database scheme is protected under copyright (as a whole) i don't see any reason why it should not be. I bet if we spoken about copying some part of paid software no one would have such doubts.


答: All GSM handsets must support the 7 bits alphabet from GSM 03.38. As the payload is 140 bytes, that translates into 160 characters.

Title: Max. SMS length that will reach all users

Body:
I'm building a grants management system where we're trying to find a list of lost users using a number of different means.

The first attempt is email but if we do not have an email address, we will try SMS.

Just wondering, before we get our business guys to start thinking up SMS messages, is there a maximum length or something which I should stay within to reach every phone with SMS capability?

Taking also in account that whilst we won't be sending an SMS to international numbers, a lot of the users will be from foreign countries and may have a foreign cell phone.

Also, messages will only ever be in English.


问:
MVVM Reporting App Approach ? Data Access Layer?
I'm trying to follow the MVVM pattern in a reporting / statistics application that I'm making in C# / WPF.

I have made many model classes to hold properties as a starting point. Some of these models are made to encapsulate different statistics so that I can present data that can be cross refrenced.

I'm thinking the next step is to create a data access layer with classes and methods to connect to a database and grab the values to populate these models.

I was thinking of creating a connection and query passing class. Then other classes for each specific set of data that I will need for the models. (constructing queries to pass)

From what I understand I will be calling these data access layer methods from the view model to populate instances of my models. Which I will present with the view.

Is my approach in theory the correct standard way to approach this problem? Any suggestions? Or Reference Material?

答:
From what I have learned with MVVM you should only allow the Model to access the data layer and then the ViewModel can interact with the Model to get the information it needs. the ViewModel can then pass on this information through to the View.

Have you considered using any MVVM frameworks to lighten the load of developing?

If not, may I suggest using Caliburn.Micro with Unity?

These will both help you get started with MVVM and are very useful.


问:
Optimistic work sharing on sparsely distributed systems
What would a system like BOINC look like if it were written today?
At the time BOINC was written, databases were the primary choice for maintaining a shared state and concurrency among nodes.

Since then, many approaches have been developed for tasking with optimistic concurrency (OT, synchronization primitives like vector clocks, virtual synchrony, shared iterators etc.)

Is there a paradigm for optimistically distributing units of work on sparsely distributing systems which communicate through message passing?

Sorry if this is a bit vague.

P.S.
The concept of Tuple-spaces is great, but locking is inherent to its definition.

Edit2:

The entire system is sparsely distributed - they can communicate only through WAN. And communication can be slow and faulty. The question is about how to best distribute units of work among them without a central co-ordinator and with as little consensus as possible (because consensus is expensive).

The answers here seem to be talking about databases - data isn't the problem. The problem is in distributing work.

Edit:

I already have a federation system which works well. I'm looking to extend it to get clients to do units of work.

答:
You're asking if programming is like clothing industry so if you won't redesign the system each 2 weeks your friends will laugh at you because you lost sync with fashion? :)

If it was written today probably marketing team would stick a big "cloud" banner to it, it'd require 20 amazon nodes to run at decent speed and would break at least 5 times daily because of using latest-and-greatest "nosql storage". Then you'd face scalability problems because those cloud systems usually don't scale out of the box as they promise, and you'd be forced to re-think the design.

Today it's for sure a little different. You could for example manage the state using some mature nosql solution like memcached for staging and then just put the data into SQL. What's wrong with the old approach if you can get a server with 64GB Ram and 24 cores for something like $300-$500.


问:
What license/EULA do I need for free to use software?
I am not sure what exactly I am looking for here, but here are the facts:

I will be offering a free to use software, free as in $0 cost only(not OSS). I need a piece of text included in the installer with agree/disagree, that would protect my rights. Specifically that I don't guarantee anything and shouldn't be held liable for their losses that the software might cause. I want to allow them to use the software for anything they like, but not allow to redistribute, sell, or reverse engineer it.

I am not even sure whether this text is technically a license, disclaimer, or end user license agreement. I doubt there is a ready to go template for what I am looking for, but any pointers would be greatly appreciated.

答:
The price you charge (0$) is an economic consideration, not (directly*) a legal one. That means you don't need a special kind of license. A normal EULA will suffice.

* When it does matter in legal matters, it will be to your advantage. Your users are not entitled to high expectations given the low price - but that would still hold if you'd charge $0.99, again free is not special.


问:
What legal considerations do I need to have when programming?
Recently I worked with a group to create a logging system for tutoring labs to track Tutor hours, and usage of the labs. We had to change the design a fair amount to be in compliance with FERPA. </p>

<p>My question stems from the curiosity that in my course of study there has never been a real mention of how people in this field have to deal with complying with the law in their work. So I would like to know how much programmers have to consider the law in the work they do. </p>

答: well, as my products are for the Public Safety sector (911 software, etc.) pretty much every day.</p>


问:
Is it best to minimize using pointers in C?
I think most people would agree that pointers are a major source of bugs in C programs (if not the greatest source of bugs). Other languages drop pointers entirely for this reason. When working in C, then, would it be best to avoid using pointers whenever practicable? For example, I recently wrote a function like this:

```<code>void split (char *record, char *delim,
            int numfields, int fieldmax,
            char result[numfields][fieldmax]);
</code>```

While not as versatile as a dynamically allocated variable, in that it requires the programmer to know the number of fields in advance and anything over fieldmax is truncated (which is sometimes acceptable), it eliminates the need for memory management, and the potential for memory corruption. I think this is a pretty good trade, but I was wondering what the opinions of other programmers on this were.

答:
In principle you're right that only using pointers when necessary will result in fewer bugs. However, in C, almost all of the time, pointers ARE necessary.

For instance, I may be wrong, but I don't think your code sample works: I don't think the function can receive a dynamic array as an argument, so it will have to use "numfields" and "fieldmax" to calculate where to write the data -- which will scribble over random memory if the wrong sizes are passed.

And most of the time, deciding the return size in advance will be difficult. If you want to avoid pointer bugs, use C++, and use pointers only when you need to.


答: A clean entry point in a separated file makes the code flow to be easily understood and maintained. I have always have had this habit of keeping a very small and concise main() function in a different file from where onwards I can trace the program steps. Just for the sake of cleanliness it is good to keep it separate.</p>


问:
Why is there such limited support for Design by Contract in most modern programming languages?
I recently discovered Design by Contract (DbC) and I find it an extremely interesting way to write code. Among other things, it would seem to offer:

Better documentation. Since the contract is the documentation, it's impossible for one to be out of date. Additionally, because the contract specifies exactly what a routine does, it helps to support reuse.

Simpler debugging. Since program execution stops the moment a contract fails, errors can't propagate, and the specific assertion violated will presumably be highlighted. This offers support during development and during maintenance.

Better static analysis. DbC is basically just an implementation of Hoare logic, and the same principles should apply.

The costs, in comparison seem to be rather small:

Extra finger-typing. Since the contracts have to be spelled out.

Takes some amount of training to get comfortable with writing contracts.

Now, being familiar with Python primarily, I realize that it is in fact possible to write up preconditions (just throwing exceptions for inappropriate input) and it's even possible to use assertions to test again certain postconditions. But it's not possible to simulate certain features such as 'old' or 'result' without some extra magic that would ultimately be considered un-Pythonic. (In addition, there are a few libraries that offer support, but ultimately I get the vibe it would be wrong to use them, as most developers don't.) I assume that it's a similar problem for all other languages (except of course, Eiffel).

My intuition tells me that the lack of support must be a result of some kind of rejection of the practice, but searching online has not been fruitful. I'm wondering if someone can clarify why most modern languages seem to offer so little support? Is DbC flawed or overly expensive? Or is it just obsolete due to Extreme Programming and other methodologies?

答:
The reason that most mainstream languages don't have DbC features in the language is the cost to benefit ratio of implementing it is to high for the language implementer.

one side of this has already been looked at in the other answers, unit tests and other runtime mechanisms (or even some compile time mechanisms with template meta programming) can give you much of the DbC goodness already. Therefore, while there is a benefit it is likely seen as quite modest.

The other side is the cost, retro fitting DbC into an existing language is likely too big a breaking change and very complex to boot. Introducing new syntax in a language without breaking old code is hard. Updating your existing standard library to use such a far reaching change would be expensive. Therefore we can conclude that implementing DbC features in an existing language has a high cost.

I'd also note that concepts which are pretty much contracts for templates, and therefore somewhat related to DbC,  were dropped from the latest C++ standard as even after years of work on them it was estimated they still needed years of work. These sort of big, broad, sweeping changes to languages are just too hard to get implemented.


答:
Think extremely carefully before any rewrite. Read Joel Spolsky's blog post, Things you should never do.

There's a subtle reason that programmers always want to throw away the code and start over. The reason is that they think the old code is a mess. And here is the interesting observation: they are probably wrong. The reason that they think the old code is a mess is because of a cardinal, fundamental law of programming:

        It’s harder to read code than to write it.

This is why code reuse is so hard. This is why everybody on your team has a different function they like to use for splitting strings into arrays of strings. They write their own function because it's easier and more fun than figuring out how the old function works...

The idea that new code is better than old is patently absurd. Old code has been used. It has been tested. Lots of bugs have been found, and they've been fixed. There's nothing wrong with it. It doesn't acquire bugs just by sitting around on your hard drive. Au contraire, baby! Is software supposed to be like an old Dodge Dart, that rusts just sitting in the garage? Is software like a teddy bear that's kind of gross if it's not made out of all new material?

...It's important to remember that when you start from scratch there is absolutely no reason to believe that you are going to do a better job than you did the first time. First of all, you probably don't even have the same programming team that worked on version one, so you don't actually have "more experience". You're just going to make most of the old mistakes again, and introduce some new problems that weren't in the original version.

The old mantra build one to throw away is dangerous when applied to large scale commercial applications. If you are writing code experimentally, you may want to rip up the function you wrote last week when you think of a better algorithm. That's fine. You may want to refactor a class to make it easier to use. That's fine, too. But throwing away the whole program is a dangerous folly...

Title: How can I sell a legacy program rewrite to the business?

Body:
We have a legacy classic ASP application that's been around since 2001.  It badly needs to be re-written, but it's working fine from an end user perspective.

The reason I feel like a rewrite is necessary is that when we need to update it (which is admittedly not that often) then it takes forever to go through all the spaghetti code and fix problems.  Also, adding new features is also a pain since it was architect-ed and coded badly.

I've run cost analysis for them on maintenance but they are willing to spend more for the small maintenance jobs than a rewrite.  Any suggestions on convincing them otherwise?


问:
Meaningful concise method naming guidelines
Recently I started releasing an open source project, while I was the only user of the library I did not care about the names, but know I want to assign clever names to each methods to make it easier to learn, but I also need to use concise names so they are easy to write as well.

I was thinking about some guidelines about the naming, I am aware of lots of guidelines that only care about letters casing or some simple notes. Here, I am looking after guidelines for meaningful but yet concise naming.

For example, this could be part of the guidelines I am looking after:

Use Add when an existing item is going to be added to a target, Use
Create when a new item is being created and added to a target.

Use Remove when an existing item is going to be removed from a target,
Use delete when an item is going to be removed permanently.

Pair AddXXX methods with RemoveXXX and Pair CreateXXX methods with
DeleteXXX methods, but do not mix them.

As the above samples show,I would like to find some online material helping me with naming methods and other item complying with English grammar and word meanings.

The above guidance may be intuitive for native English speakers, but for me that English is my second language I need to be told about things like this.

答:
Look at how others on your platform do it - some of the bigger players might even have code style and naming guidelines.

Some platforms prefer short names (for instance, in the Win32 C API _tcsstr is the function to find a string within a string - isn't it obvious?), others go for readability in favor of brevity (in Apple's Cocoa framework for Objective-C, the method to replace a substring in a string with another string and return the result as a copy is called stringByReplacingOccurrencesOfString: withString:). I find the latter vastly easier to understand, and only moderately harder to write (especially with code completion).

Since you read code more often than you write it (doubly true for open source libraries), and reading is harder than writing, optimize for reading. Optimize for brevity only last, and take only as much away as is possible without diluting clarity.


问:
thick client migration to web based application
This query is related to application design the technology that I should consider during migration.
The Scenario: I have a C#.net Winform application which communicates with a device. One of the main feature of this application is monitoring cyclic data(rate 200ms) sent from the device to the application. The request to start the cyclic data is sent only once in the beginning and then the application starts receiving data from the device until it sends a stop request.
Now this same application needs to be deployed over the web in a intranet.
The application is composed of a business logic layer and a communication layer which communicates with the device through UDP ports.

I am trying to look at a solution which will allow me to have a single instance of the application on the server so that the device thinks that it is connected as usual and then from the business logic layer I can manage the clients. I want to reuse the code of the business layer and the communication layer as much as possible.
Please let me know if webserives/WCF/ etc what i should consider to design the migration.

Thanks in advance.

答: WCF does not come with a UDP binding out of the box. You can write a custom UDP binding using this sample as a guide but I'd be wary of doing so. The code in the sample is closer to demo code than proven production quality code. Given that, you may want to go with a Windows service that handles the UDP interaction leveraging your existing code to populate an appropriate data store. Then the WCF service could be written as a conventional database interaction service.</p>

OwnerDisplayName: Sixto Saez


问:
Mission critical embedded language
Maybe the question sounds a bit strange, so I'll explain a the background a little bit.

Currently I'm working on a project at y university, which will be a complete on-board software for an satellite. The system is programmed in C++ on top of a real-time operating system. However, some subsystems like the attitude control system and the fault detection and a space simulation are currently only implemented in Matlab/Simulink, to prototype the algorithms efficiently. After their verification, they will be translated into c++.

The complete on-board software grew very complex, and only a handful people know the whole system. Furthermore, many of the students haven't program in C++ yet and the manual memory management of C++ makes it even more difficult to write mission critical software.

Of course the main system has to be implemented in C++, but I asked myself if it's maybe possible to use an embedded language to implement the subsystem which are currently written in Matlab. This embedded language should feature:

static/strong typing and compiler checks to minimize runtime errors

small memory usage, and relative fast runtime

attitude control algorithms are mainly numerical computations, so a good numeric support would be nice

maybe some sort of functional programming feature, matlab/simulink encourage you to use it too

I googled a bit, but only found Lua. It looks nice, but I would not use it in mission critical software. Have you ever encountered a situation like this, or do you know any language, which could satisfies the conditions?

EDIT: To clarify some things: embedded means it should be able to embed the language into the existing C++ environment. So no compiled languages like Ada or Haskell

答:
The language chosen for mission critical software is only one small part of the equation.  Testing of course is a huge part of it, many layers of testing by different groups of people.  the team writing the code does some testing but it needs a lot of testing by others not on that team, and then as the component is integrated into larger portions of the vehicle it is re-tested as part of that (sub-) system.

Back to the software team.  The lower level language you can stand without increasing human error is better, less things the compiler can do wrong.  Usually disable optimization completely, again take the compiler out of the loop as much as possible.  peer reviews, code walk through, justify and verify every line of code.  for mission critical code expect no more than one line of debugged code per day (from experienced developers) less than that for first timers, one line a week perhaps.  I am not joking that is how it is in that business.   You can cut that down yes by adding more people in the review process, instead of a few lines of code a year.

I would at least take a little time to examine the compiler output even if the compiler has been used for DO-178 work.

go with languages and compilers that have been used by the aerospace or automotive (or medical) industries.  ada being the traditional, but as mentioned, how many ada programmers are you going to find, and are they going to do a good job learning the language on their first project when that is a mission critical project?  no.  C or C++ has been used as well, one or both being the language of choice today for this type of work.

Title: Mission critical embedded language


答:
DbC would be used more extensively if the contracts could be checked at compile time so that it would not be possible to run a program that violated any contract.

Without compiler support, "DbC" is just anther name for "check invariants/assumptions and throw an exception if violated".

Title: Why is there such limited support for Design by Contract in most modern programming languages?

Body:
I recently discovered Design by Contract (DbC) and I find it an extremely interesting way to write code. Among other things, it would seem to offer:

Better documentation. Since the contract is the documentation, it's impossible for one to be out of date. Additionally, because the contract specifies exactly what a routine does, it helps to support reuse.

Simpler debugging. Since program execution stops the moment a contract fails, errors can't propagate, and the specific assertion violated will presumably be highlighted. This offers support during development and during maintenance.

Better static analysis. DbC is basically just an implementation of Hoare logic, and the same principles should apply.

The costs, in comparison seem to be rather small:

Extra finger-typing. Since the contracts have to be spelled out.

Takes some amount of training to get comfortable with writing contracts.

Now, being familiar with Python primarily, I realize that it is in fact possible to write up preconditions (just throwing exceptions for inappropriate input) and it's even possible to use assertions to test again certain postconditions. But it's not possible to simulate certain features such as 'old' or 'result' without some extra magic that would ultimately be considered un-Pythonic. (In addition, there are a few libraries that offer support, but ultimately I get the vibe it would be wrong to use them, as most developers don't.) I assume that it's a similar problem for all other languages (except of course, Eiffel).

My intuition tells me that the lack of support must be a result of some kind of rejection of the practice, but searching online has not been fruitful. I'm wondering if someone can clarify why most modern languages seem to offer so little support? Is DbC flawed or overly expensive? Or is it just obsolete due to Extreme Programming and other methodologies?


答:
You should look again at your requirements and conditions. While C++ is a fine language for the numeric processing parts of your application, trying to go to having everything in a single language is going to be troublesome anyway (different languages have peak expressivities on different classes of problem). You've identified some of the reasons why, especially the fact that your students don't know C++ when they start. You're also not going to get perfect safety through the use of a complex type system; there's always higher level problems that can trip you up given that total correctness proofs are really difficult.

What you would ideally have is some kind of development environment that mimics the environment of the satellite. (Well, without the problems with rebooting caused when everything goes wrong.) Once you've got such a situation, you can do some real testing of things before you put the software into deployment; that's got to be a good idea, yes?

You perhaps should look at using a multi-language solution, using a higher-level language to do major coordination of components and a lower-level language to provide implementations of those components. C++ is a reasonable language to write components in, but Lua is better suited to coordination (and of course you don't write everything in Lua; it's not meant to be used that way!). What's more, this multi-language approach is commonly used in industrial critical systems (e.g., control of heavy plant, running oil refineries) and that's an area where it really is important to get things right as lives are on the line.

(Lua is not the only candidate for an integration language: I know for a fact that Tcl is used quite a bit in this area and would be unsurprised at seeing either Python or Ruby used for this too. The other common languages for low-level components are probably C and Fortran, though anything conforming properly to the C ABI for functions is tractable here. I wouldn't recommend languages with very large runtimes — e.g., Java, C# — for component providers; they're nasty to integrate with unless you do everything within the runtime.)

Title: Mission critical embedded language

Body:
Maybe the question sounds a bit strange, so I'll explain a the background a little bit.

Currently I'm working on a project at y university, which will be a complete on-board software for an satellite. The system is programmed in C++ on top of a real-time operating system. However, some subsystems like the attitude control system and the fault detection and a space simulation are currently only implemented in Matlab/Simulink, to prototype the algorithms efficiently. After their verification, they will be translated into c++.

The complete on-board software grew very complex, and only a handful people know the whole system. Furthermore, many of the students haven't program in C++ yet and the manual memory management of C++ makes it even more difficult to write mission critical software.

Of course the main system has to be implemented in C++, but I asked myself if it's maybe possible to use an embedded language to implement the subsystem which are currently written in Matlab. This embedded language should feature:

static/strong typing and compiler checks to minimize runtime errors

small memory usage, and relative fast runtime

attitude control algorithms are mainly numerical computations, so a good numeric support would be nice

maybe some sort of functional programming feature, matlab/simulink encourage you to use it too

I googled a bit, but only found Lua. It looks nice, but I would not use it in mission critical software. Have you ever encountered a situation like this, or do you know any language, which could satisfies the conditions?

EDIT: To clarify some things: embedded means it should be able to embed the language into the existing C++ environment. So no compiled languages like Ada or Haskell


问:
A good schema to represent integer numbers from 0 to infinity, assuming you have infinite linear binary storage?
I would like a schema to represent integer numbers starting with 0, without any limit (assuming access to infinite linear storage).

Here's a schema that can represent numbers from 0 to 255:

Use the first byte of the storage (address 0) to store the integer.

Now, suppose I want to represent numbers larger than 255. Of course, I could use more than 1 byte to represent the integer, but as long as it's a fixed number, there will be eventually an integer so large that it cannot be represented by the original schema.

Here's another schema that should be able to do the task, but it's probably far from efficient.

Just use some sort of unique "end of number" byte, and use all the previous bytes to represent the number. Obviously, this "end of number" byte cannot be used anywhere in the number representation, but this can be achieved by using a base-255 (instead of base-256) numbering system.

However, that's slow and probably inefficient. I want to have a better one that performs better with low values and scales well.

Essentially, it's a UUID system. I want to see if it's possible to create a fast-performing UUID system that can theoretically scale to use for years, thousands of years, millions of years, without having to be redesigned.

答:
There is a whole lot of theory based around what you are trying to do. Take a look at wiki page about universal codes - there is rather exhaustive list of integer encoding methods (some of which are actually being used in practice).

In data compression, a universal code for integers is a prefix code that maps the positive integers onto binary codewords

Or you could just use first 8 bytes to store the number's length in some units (most likely bytes) and then put the data bytes. It would be very easy to implement, but rather inefficient for small numbers. And you would be able to code integer long enough to fill all data drives available to humanity :)


答:
UUID systems are based on finite (but large) computing power in a finite (but large) universe. The number of UUIDs is large even when compared to absurdly large things like the number of particles in the universe. The number of UUIDs, with any number of fixed bits, is small, however, compared to infinity.

The problem with using 0xFFFF to represent your end of number flag is that it makes your number encoding less efficient when numbers are large. However, it seems that your UUID scheme makes this problem even worse. Instead of one out of 256 bytes skipped, you now have the entire UUID space wasted. Efficiency of computation/recognition (instead of space) depends a lot on your theoretical computer (which, I assume you have if you are talking about infinity). For a TM with a tape and a finite state controller, any UUID scheme is impossible to scale efficiently (basically, the pumping lemma screws you from moving beyond a fixed-bit-length end marker efficiently). If you don't assume a Finite State controller, this might not apply, but you do have to think about where the bits go in the decoding/recognition process.

If you just want better efficiency than 1 out of 256 bytes, you can use whatever bit-length of 1s you were going to use for your UUID scheme. That's 1 out of 2^bit-length in inefficiency.

Note that there are other encoding schemes, though. Byte encoding with delimiters just happens to be the easiest to implement.

Title: A good schema to represent integer numbers from 0 to infinity, assuming you have infinite linear binary storage?

Body:
I would like a schema to represent integer numbers starting with 0, without any limit (assuming access to infinite linear storage).

Here's a schema that can represent numbers from 0 to 255:

Use the first byte of the storage (address 0) to store the integer.

Now, suppose I want to represent numbers larger than 255. Of course, I could use more than 1 byte to represent the integer, but as long as it's a fixed number, there will be eventually an integer so large that it cannot be represented by the original schema.

Here's another schema that should be able to do the task, but it's probably far from efficient.

Just use some sort of unique "end of number" byte, and use all the previous bytes to represent the number. Obviously, this "end of number" byte cannot be used anywhere in the number representation, but this can be achieved by using a base-255 (instead of base-256) numbering system.

However, that's slow and probably inefficient. I want to have a better one that performs better with low values and scales well.

Essentially, it's a UUID system. I want to see if it's possible to create a fast-performing UUID system that can theoretically scale to use for years, thousands of years, millions of years, without having to be redesigned.


答:
I'd suggest having a array of bytes (or ints or longs) and a length field that says how long the number is.

This is roughly the approach used by Java's BigInteger. The address space possible from this is massive - easily enough to give a different UUID to every individual atom in the universe :-)

Unless you have a very good reason to do otherwise, I'd suggest just using BigInteger directly (or its equivalent in other languages). No particular need to reinvent the big number wheel....


答: Why not just use 7 bits out of each byte, and use the 8th bit to indicate whether there is another byte to follow?  So 1-127 would be in one byte, 128 would be represented by 0x80 0x01, etc.</p>


Body:
An approach I've used:  count the number of leading 1 bits, say n.  The size of the number is then 2^n bytes (including the leading 1 bits).  Take the bits after the first 0 bit as an integer, and add the maximum value (plus one) that can be represented by a number using this encoding in 2^(n-1) bytes.

Thus,

                  0 = 0b00000000
                   ...
                127 = 0b01111111
                128 = 0b1000000000000000
                   ...
              16511 = 0b1011111111111111
              16512 = 0b11000000000000000000000000000000
                   ...
          536887423 = 0b11011111111111111111111111111111
          536887424 = 0b1110000000000000000000000000000000000000000000000000000000000000
                   ...
1152921505143734399 = 0b1110111111111111111111111111111111111111111111111111111111111111
1152921505143734400 = 0b111100000000000000000000000000000000000000000000 ...

This scheme allows any non-negative value to be represented in exactly one way.

(Equivalently, used the number of leading 0 bits.)