问:
How to manage a Closed Source High-Risk Project?
I am currently planning to develop a J2EE website and wish to bring in 1 developer and 1 web designer to assist me. The project is a financial app within a niche market.

I plan to keep the source closed. However, I fear that my would-be employees could easily copy the codebase and use it or sell it to a third party. The app development will take 4-6 months, perhaps more, and I may bring in additional employees after the app goes live.

But how do I keep the source to myself. Are there techniques companies use to guard their source?

I foresee disabling USB drives and DVD writers on my development machines, but uploading data or attaching the code in email would still be possible.

My question is incomplete. But programmers who have been in my situation, please advice. How should I go about this? Building a team, maintaining code-secrecy,etc.

I am looking forward to sign a secrecy contract with the employees if needed too.
(Please add relevant tags)

Update

Thank you for all the answers. I certainly won't be disabling all USB ports and DVD writers now. But I think I should be logging activity(How exactly should I do that?) I am wary of scalpers who would join and then run off with the existing code. I haven't met any, but I have been advised to be wary of them. I would include a secrecy clause, but given this is a startup with almost no funding and in a highly competitive business niche with bigger players in the field, I doubt I would be able to detect or pursue any scalpers.

How do I hire people I trust, when I don't know them personally. Their resume will be helpful but otherwise trust will develop only with time.

But finally even if they do run away with the code, it is service that matters after the sale is made. So I am not really worried for the long term.

答:
If these programmers can write the software in the first place, then...

THEY DON'T NEED TO STEAL IT.

They can just simply rewrite it in a fraction of the time it took to originally develop it. Yes, it's true, developers aren't complete idiots... once they figure out how to do something, they can often remember how they did it.

So, I guess you're just going to have to trust them, or write the software yourself.


问:
Teaching C++ to first time high school students: Where to draw the line?
I will be mentoring a team of high school students for the FIRST Robotics Competition, most teams here develop[ their robot software using C++. For many of the students on the team this will be their first introduction to programming. I wouldn't have chosen C++ for teaching programming to high schoolers (e.g. Python or Javascript would have been easier I think) but the choice is set.

I want to teach them proper C++ (i.e. avoid a mixed C/C++ dialect, i.e. C+) but I don't want to scare them either with needless complexity. For that matter:

Should I start using STL from day one, esp. vector or just stick with standard arrays? Arrays are easier to introduce but the pointer errors may be harder to catch.

For I/O, should I stick to cout, etc. or do you think printf would be easier to learn?

Are there any online resources for C++ that are suitable to use for such young learners?

Thanks!

EDIT: Thanks for so many excellent answers. In addition to Accelerated C++, which is suggested by many people, I have found that C++ For Everyone is an excellent text.

答:
I started teaching students C++ late last year and this summer also for our FIRST Robotics Team.

We are using Stroustrup's Programming -- Principles and Practice Using C++. I have found the book to be approachable, readable, and well organized. We have had about 6 students read through the chapters on their own. I am there to help them with terminology and questions. They do all of the exercises in the book.

I had the students work through chapter 14. Skipping the chapters on streams (not useful for FRC programming). Through chapter 14 is useful because they get an introduction to subclasses. However, they probably need to go farther in the book in order to better understand constructors and destructors related to subclasses.

Do not underestimate your students. The students are happy to have the book, read, learn and do the exercises; and this was during the summer on their own time! There are many students that won't understand. They should move on to something else; not everyone understands programming.

The largest barrier isn't the language or the book; it's the development environment. Visual Studio Express can be daunting to first time users. You can be valuable in helping the students focus on the programming rather than the environment. However, learning the environment is valuable as programmers spend a good deal of time adapting to new development systems.

Good Luck.

OwnerDisplayName: recipriversexclusion

ContentLicense: CC BY-SA 3.0


问:
How to design a system that allows for multiple parallel extensions of the same "component"?
As a player, I found the following problems about creating and using "extensions" (aka mods) for games:

1) Whenever the game is updated, all the mods break.

2) Most mods don't work with each other, so the player "has to choose"

3) If you ever de-install a mod, your "saved games" almost always become unusable.

I want to design a game in Scala/Java that does NOT exhibit those issues. I need help with point 2. I want to write it such that it is maximally extensible. My problem is I cannot nail down properly how I should do this, and since the whole design reside on top of the component/service/plugin architecture, than I can't move forward until I solved this problem.

The design qualities I want to achieve are:

1) For any "service", there should be a single object (at any given time) that
         implements it. Since it is a cycle-based simulation, I can safely
         "swap implementation" between the cycles.

2) It should be possible for a "third party" to create a "bundle" which either
         modifies or more likely extends the functionality of a "service", and "bind" it
         into the existing application at runtime, without recompilation.

3) It should be possible to load and unload those bundles at runtime, because they
         will be used in a long-running server.

4) Developing extensions should be easily possible, even for a "junior" programmer,
         without requiring extensive knowledge of some complex framework.

5) It should be possible for several bundles to extend/modify the same service at
         the same time, as long as they follow a certain set of rules preventing most
         conflicts.

I was first planning to use OSGi, but I can't really see how to get this to work. OSGi solution is to let many bundles register the same service and use a "filter" to choose one in the client code. Making the code aware that at any given time, there can be several objects that implements different variations of the same service, and that those instances can come and go, would make everything much too complicated and brittle.

My plan was to register every service as a generic "handle", which the user of the service can use to get the real instance and cast to what they want. The handle content could change over time, but the handle object itself would be valid for the duration of the program, therefore bypassing the constant querying of the registry, with associated filtering.

I think OSGi can solve 2 to 5, but only by using multiple instances of the same service, which is in contradiction to 1. I think that 1 an be achieved either by using composition, or by fusing all the different implementation of a service into a single object through byte-code manipulation. A look at Javaassist showed me that "rebasing" a class does not seem too difficult, if they all extend the same base-class and take the same constructor parameters. Composition, on the other hand, seem to put much more work on the hands of the third-party extensions developers, which is in contradiction to 4, and generally is a clunky solution at best.

If I implement the byte-code manipulation strategy, than I have to basically do almost everything myself, and loose most of the benefits of OSGi. Also, I cannot really create the fused service until all bundles have been activated, so they cannot register a "real" service instance at activation time, which is what OSGi is about (?). Do I even know from OSGi when it's "done"?

Is the only way of achieving those designs goal to create my own component framework, or can I still do it using OSGi, or some other system? Reinventing the wheel at that level sound like a stupid (and time consuming) idea, but I can't see how to solve those problems with OSGi. Maybe another service/plugin framework can do it? Or by using a specific well-defined design strategy?

UPDATE:
It will a be an Internet Client-Server (Cluster) model running on OpenGL. I am mostly "framework unencumbered", that is, I can choose whatever fits my needs, but I want to stick to the JVM. OSGi is an attempt at standardizing "components" (called bundles) for the JVM.

答:
Conceptually speaking, you want to deal with Component Programming,
in which a section of code, maybe replaced with another,
or new similar section of code may be added, removed or updated at runtime.

http://en.wikipedia.org/wiki/Component-based_software_engineering

I have read about several ways to do that, depending which programming language and which  programming framework you are using. I ignore how to do it with the "Java Framework" or "Scala Framework".

(I done something similar with C/C++ & Object Pascal (Delphi), and "Shared Libraries" on network Windowze)

Its your game or application going to be in a network, internet or stand alone desktop app. ?

It is intended to run on a web page (javascript), flash control, or desktop interface like Swing or SWT ?

The technology to implement a "component driven" application, its very different from one "platform" or enviroment, from another.

On the programming language side, most of this "bundles" or "components",
are objects that share the same class or implement the same interface.


问:
Reinventing the wheel because it doesn't exist
One of the languages I have to use at work is a very small, niche language called psl. One of the largest complaints I have about it as a language is that the libraries are very limited.

While that's understandable for a small language developed by a couple of guys, it does cause me some dilemmas. Specifically, I find myself "rewriting" functions that are standard in other languages because they don't exist here.

This is especially problematic when I'm attempting to write a function to solve a problem, and management doesn't want to spend the time to do so. They want me to use hard coded magic numbers instead, which I know will need to change multiple times over the life of the code.

This doesn't quite fit the antipattern reinventing the wheel because it didn't exist here in the first place. What kind of anti pattern would this fit?

答:
Not sure about going back and changing code, but it will definitely lead to breaking the DRY Principle.

Taken from the link above:

The DRY (Don't Repeat Yourself) Principle states:

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.


问:
What is the origin and meaning of the phrase “Lambda the ultimate?”
I've been messing around with functional programming languages for a few years, and I keep encountering this phrase. For example, it is a chapter of "The Little Schemer, which certainly predates the blog by this name. (No, the chapter doesn't help answer my question.)

I understand what lambda means, the idea of an anonymous function is both simple and powerful, but I fail to understand what "the ultimate" means in this context.

Places that I've seen this phrase:

The title of chapter 8 of The Little Schemer

A blog: http://lambda-the-ultimate.org/

A series of "Lambda the ultimate X" papers: http://library.readscheme.org/page1.html (archived)

I feel like I'm missing a reference here, can anyone help?

答:
I guess it's simply a reference to some papers written by Sussman and Steele between 1975 and 1980 called:

Lambda: The Ultimate Imperative

Lambda: The Ultimate Declarative

Lambda: The Ultimate GOTO

LAMBDA: The Ultimate Opcode

See Wikipedia article.

ContentLicense: CC BY-SA 4.0


答:
Java Swing handles this problem using action handlers.  Each component registers itself using one or more action handlers.  When a particular action happens, each component that registered gets an opportunity to perform some code in response to the action.

A similar idea is a messaging system.  A component registers to receive messages.  The component is responsible for responding to whichever messages that it chooses.

Both of these ideas rely on the component having access to the rest of the code base.  I'm not sure how you best make public all of the fields and instances of your game.  I suppose a well defined set of game programmers interfaces is the best way.

Title: How to design a system that allows for multiple parallel extensions of the same "component"?

Body:
As a player, I found the following problems about creating and using "extensions" (aka mods) for games:

1) Whenever the game is updated, all the mods break.

2) Most mods don't work with each other, so the player "has to choose"

3) If you ever de-install a mod, your "saved games" almost always become unusable.

I want to design a game in Scala/Java that does NOT exhibit those issues. I need help with point 2. I want to write it such that it is maximally extensible. My problem is I cannot nail down properly how I should do this, and since the whole design reside on top of the component/service/plugin architecture, than I can't move forward until I solved this problem.

The design qualities I want to achieve are:

1) For any "service", there should be a single object (at any given time) that
         implements it. Since it is a cycle-based simulation, I can safely
         "swap implementation" between the cycles.

2) It should be possible for a "third party" to create a "bundle" which either
         modifies or more likely extends the functionality of a "service", and "bind" it
         into the existing application at runtime, without recompilation.

3) It should be possible to load and unload those bundles at runtime, because they
         will be used in a long-running server.

4) Developing extensions should be easily possible, even for a "junior" programmer,
         without requiring extensive knowledge of some complex framework.

5) It should be possible for several bundles to extend/modify the same service at
         the same time, as long as they follow a certain set of rules preventing most
         conflicts.

I was first planning to use OSGi, but I can't really see how to get this to work. OSGi solution is to let many bundles register the same service and use a "filter" to choose one in the client code. Making the code aware that at any given time, there can be several objects that implements different variations of the same service, and that those instances can come and go, would make everything much too complicated and brittle.

My plan was to register every service as a generic "handle", which the user of the service can use to get the real instance and cast to what they want. The handle content could change over time, but the handle object itself would be valid for the duration of the program, therefore bypassing the constant querying of the registry, with associated filtering.

I think OSGi can solve 2 to 5, but only by using multiple instances of the same service, which is in contradiction to 1. I think that 1 an be achieved either by using composition, or by fusing all the different implementation of a service into a single object through byte-code manipulation. A look at Javaassist showed me that "rebasing" a class does not seem too difficult, if they all extend the same base-class and take the same constructor parameters. Composition, on the other hand, seem to put much more work on the hands of the third-party extensions developers, which is in contradiction to 4, and generally is a clunky solution at best.

If I implement the byte-code manipulation strategy, than I have to basically do almost everything myself, and loose most of the benefits of OSGi. Also, I cannot really create the fused service until all bundles have been activated, so they cannot register a "real" service instance at activation time, which is what OSGi is about (?). Do I even know from OSGi when it's "done"?

Is the only way of achieving those designs goal to create my own component framework, or can I still do it using OSGi, or some other system? Reinventing the wheel at that level sound like a stupid (and time consuming) idea, but I can't see how to solve those problems with OSGi. Maybe another service/plugin framework can do it? Or by using a specific well-defined design strategy?

UPDATE:
It will a be an Internet Client-Server (Cluster) model running on OpenGL. I am mostly "framework unencumbered", that is, I can choose whatever fits my needs, but I want to stick to the JVM. OSGi is an attempt at standardizing "components" (called bundles) for the JVM.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Real Programmers don't comment their code. If it was hard to write, it should be hard to understand.

    — Tom Van Vleck

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
Is there is a case when there is no any reasonable replacement for singleton design pattern?

Possible Duplicate:

  When is Singleton appropriate?

I've seen many explanations why is Singleton is evil. But is there really no such a case when Singleton is the only beautiful solution?

答:
I have never seen nor heard of any case which justifies limiting an object to just one instance.

Even in hardware, you can never guarantee what can happen in the next few years- for example, in 1990 or 1995 you might have said that a graphics driver might reasonably use one. But then, you get SLi invented. Whoops. The same occurred with printers. You can't justify the use of a Singleton just because it doesn't make sense - it has to be actively system-destroying. Such instances do not exist.


答:
It depends on what you call a Singleton.

edit> The link from Problematic in the question's comments might help to understand what I mean here : When is Singleton appropriate?

If the construction and destruction of the unique instance don't have to be explicit, then it's EVIL.

If not, then there are some specific cases where it's clearly a good solution. The main one I'm using is when the unique instance represent the state of a "system" that is "global", like a hardware api.

That said, if you're in this case, you could replace your singleton by free functions... if your language allows it. If not then I guess it's a reasonable choice.

Just keep in mind : global access means that if there is a problem with your singleton object, you might have propagated it everywhere it is used. That's why if you can remove the global accessibility, it would be far better.

In a more general way, when you start thinking that a singleton might be necessary, think twice or more. It can always be replaced. There is just a tradeof that might be (or not) too expensive for you. Now it don't mean you don't have to use it at all ever in your life. It might be worth sometimes. But it's rare. So, as a rule of thumb, just don't use it. Rules are made to be understood then to be broken when you understand when it's a good idea.

Title: Is there is a case when there is no any reasonable replacement for singleton design pattern?

Body:
Possible Duplicate:

  When is Singleton appropriate?

I've seen many explanations why is Singleton is evil. But is there really no such a case when Singleton is the only beautiful solution?


问:
Managing software projects - advice needed
I work for a large government department as part of an IT team that manages and develops websites as well as stand alone web applications.

We’re running in to problems somewhere in the SDLC that don’t rear their ugly head until time and budget are starting to run out.

We try to be “Agile” (software specifications are not as thorough as possible, clients have direct access to the developers any time they want) and we are also in a reasonably peculiar position in that we are not allowed to make profit from the services we provide. We only service the divisions within our government department, and can only charge for the time and effort we actually put in to a project. So if we deliver a project that we have over-quoted on, we will only invoice for the actual time spent.

Our software specifications are not as thorough as they could be, but they always include at a minimum:

Wireframe mockups for every form view

A data dictionary of all field inputs

Descriptions of any business rules that affect the system

Descriptions of the outputs

I’m new to software management, but I’ve overseen enough software projects now to know that as soon as users start observing demos of the system, they start making a huge amount of requests like “Can we add a few more fields to this report.. can we redesign the look of this interface.. can we send an email at this part of the workflow.. can we take this button off this view.. can we make this function redirect to a different screen.. can we change some text on this screen… can we create a special account where someone can log in and get access to X… this report takes too long to run can it be optimised.. can we remove this step in the workflow… there’s got to be a better image we can put here…” etc etc etc.

Some changes are tiny and can be implemented reasonably quickly.. but there could be up to 50-100 or so of such requests during the course of the SDLC. Other change requests are what clients claim they “just assumed would be part of the system” even if not explicitly spelled out in the spec.

We are having a lot of difficulty managing this process. With no experienced software project managers in our team, we need to come up with a better way to both internally identify whether work being requested is “out of spec”,  and be able to communicate this to a client in such a manner that they can understand why what they are asking for is “extra” work.

We need a way to track this work and be transparent with it.

In the spirit of Agile development where we are not spec'ing software systems in to the ground and back again before development begins, and bearing in mind that clients have access to any developer any time they want it, I am looking for some tips and pointers from experienced software project managers on how to handle this sort of "scope creep" problem, in tracking it, being transparent with it, and communicating it to clients such that they understand it.

Happy to clarify anything as needed.

I really appreciate anyone who takes the time to offer some advice.

Thanks.

答:
software specifications are not as thorough as possible

Being agile is not about not producing thorough documentation, but minimizing documentation that is wasteful. In other words, producing what you need, when you need it, in a "just good enough" form that can be evolved as the need implies. I would recommend reading Scott Ambler's article on agile documentation and make sure you are producing enough of the right kind of documentation. There are a lot of considerations that go into what documents to produce, so make sure you're accounting for the key points.

clients have direct access to the developers any time they want

This is generally a Bad Idea. The people in a developer role are paid to develop software. Some developers might have multiple roles, including a role that requires interfacing with client representatives. However, to maximize the time of everyone doing what their job is, only allow clients to talk to certain people. These people would be responsible for disseminating the information to the appropriate people on the team so that it can be acted on.

We are having a lot of difficulty managing this process. With no
  experienced software project managers in our team, we need to come up
  with a better way to both internally identify whether work being
  requested is “out of spec”, and be able to communicate this to a
  client in such a manner that they can understand why what they are
  asking for is “extra” work. We need a way to track this work and be
  transparent with it.

This is done by implementing a Change Control Board or a Change Review Board. These people are the ones who review all proposed changes, regardless of where they come from. A change could be a request from a client for a new feature, a defect report that comes from the QA/Testing team, or a task that a developer would like to do to make their job easier. The board examines each request with regards to scheduling, budget, and available resources, decides if it's a valid request, prioritizes it, and (depending on your process methodology) will assign it to a developer. If a feature is rejected or deferred, they explain why as well.


答:
Yes, it's simply a recurring phrase in the title of several papers, starting from a couple in the 70s, in which Sussman and Steele demonstrate the use of lambda calculus for programming, by means of a minimalist Lisp dialect named "Scheme" they devised for the purpose. You can find the papers themselves here; they're interesting and surprisingly relevant.

I'm not sure if this is ever explicitly stated, but it's clear (from context, having read the papers, and knowing the general background and research interests of the authors) that the phrase is simply a catchy slogan for their contention that lambda abstractions, as a computational primitive, are not only universal in the formal sense (of being able to encode any program in some fashion, however awkward), but universal in a practical sense that any and every construct present in other languages, even those that are baked-in from the ground up, can be reimplemented in a lambda-based language in a way that is both effective and natural to use.

The repeated phrase leads to the obvious generalized form "for all X, lambda is the ultimate X", which is the sense I've generally taken "Lambda the Ultimate" to mean as the blog name, noting that LtU is concerned with programming language design and theory. Ironically, LtU would probably also be one of the best places to find someone who could tell you about something for which lambda is not the ultimate implementation. :]

Note also that Sussman is one of the authors of SICP, a very influential textbook that also uses the Scheme language and spends a fair amount of time introducing lambda abstractions as a concept.

Title: What is the origin and meaning of the phrase “Lambda the ultimate?”

Body:
I've been messing around with functional programming languages for a few years, and I keep encountering this phrase. For example, it is a chapter of "The Little Schemer, which certainly predates the blog by this name. (No, the chapter doesn't help answer my question.)

I understand what lambda means, the idea of an anonymous function is both simple and powerful, but I fail to understand what "the ultimate" means in this context.

Places that I've seen this phrase:

The title of chapter 8 of The Little Schemer

A blog: http://lambda-the-ultimate.org/

A series of "Lambda the ultimate X" papers: http://library.readscheme.org/page1.html (archived)

I feel like I'm missing a reference here, can anyone help?


答:
I think you should not teach things from C++ point of view ("C++ hello world"), but from the problem domain - in this case, robotics - point of view. So, your hello world would be blinking a led or driving a motor.

Of course you could/should decompose each tiny robotics task in a subset of increasing conceptually meaningful C++ actions, involving types, functions and IO operations.

As for myself, I am not a professional programmer, and tried to learn Java, C++ and Python. I really started to achieve something (Python) when I had real (simple) problems to solve. That took me right to the point, avoiding excessive attention to incidental implementation details of the language itself.

So I would advice: don't read a language's manual, but instead learn to do things with your language of choice. That's what keep people motivated, I think.

Title: Teaching C++ to first time high school students: Where to draw the line?

Body:
I will be mentoring a team of high school students for the FIRST Robotics Competition, most teams here develop[ their robot software using C++. For many of the students on the team this will be their first introduction to programming. I wouldn't have chosen C++ for teaching programming to high schoolers (e.g. Python or Javascript would have been easier I think) but the choice is set.

I want to teach them proper C++ (i.e. avoid a mixed C/C++ dialect, i.e. C+) but I don't want to scare them either with needless complexity. For that matter:

Should I start using STL from day one, esp. vector or just stick with standard arrays? Arrays are easier to introduce but the pointer errors may be harder to catch.

For I/O, should I stick to cout, etc. or do you think printf would be easier to learn?

Are there any online resources for C++ that are suitable to use for such young learners?

Thanks!

EDIT: Thanks for so many excellent answers. In addition to Accelerated C++, which is suggested by many people, I have found that C++ For Everyone is an excellent text.


答:
want to hear a common myth?

"Singletons are a way to limit the number of instances of a certain class to one."

Yeah, right.

If that's how most people used singletons, the only thing I would have to say is "Well, why not just create ONE and stop there?"

But that's not the issue. The real problem here is that people use singletons to introduce global state to object-oriented programs, or just to shove in another (anti) pattern.

If you want to have a single instance of a certain class, that's perfectly fine. But why make it accessible from anywhere in your code? That's called opacity, my friend, and that's what you should watch out of.

Instead of using singletons, read up some more on dependency-injection and chain of construction (factories, etc). Depend on services (objects) you need. Don't try finding them by yourself (from the object's point of view) or access them globally.


问:
As a teen, how can I find "friends" for programming
I'm a teen who has been programming for about 3 years, I can do some basic Software and so, but I feel I can't do all by myself.

What can I do to find people interested in Programming ? None of my friends does, I only have a Cousin which is studying Software Engineering, but he is in another country.

I live in Spain, so It's more difficult that in USA.

答:
(From both a programmer and a "hobbyst psychologist")

The previous answers have already told you several ways to meet other guys of you same age.

It's good that you want to have friends related to computers & programming, but, its also good you may try to met other guys that aren't related to programming.

Maybe you already have friends that are not computer related, but, since there is a lot of geeks type guys that are not very social, Its very easy to think that you don't have.

I'm a person that learn programming some years ago, and programming wasn't very common, in my hometown, so when I was teenager I actually had to "hang out" with guys that weren't "geek". And it was fun.

There are also, a lot of "Open Source" projects, and "game" projects on the internet, where you can combine your programming skills, with making friends.

In the real world, there is a lot of programmers who want to achieve a program all by themselves, and if you want to make a game, for example, they just having a hard time.

Trying to make a small game, or extend and existing one, could be a good way to work with others.

Good Luck.


问:
How to manage a project in school?
I just started doing PhD and we are supposed to do a project for a class, there are 14 people taking the class and we are supposed to develop a system all together.

I was away from academia and working in the industry before, and I know it is very hard to manage even a couple of people towards the same goal.

We are going to make the first meeting in a couple of weeks. First, I will suggest using a version control system like SVN. Second, I will try to take the lead for the architecture of the system, because I think I am more experienced. Since the class is about computer vision and I anticipate that most of the people's background is research related so there is a big chance that I am more experienced. I will gladly hand architecture to someone else if he/she is more experienced.

What else should we do to progress without much hassle?

PS. You can assume every one of us is going to work remotely, and meet once in a week at it's best (not everyone will attend though). And the project needs to be finished in 2 months. It does not need to be a perfect, complete product, we just need to make a prototype.

PPS. The aspects of the group reminds me of open source project groups, maybe the answers will be helpful for those groups as well.

答:
A distributed VCS is a much better choice than SVN. Mercurial should fit your needs nicely - it's similarly powerful to Git, but it is much easier to wrap your head around it and it has nice documentation. However, if it turns out that most people in the team (or even just you!) are much more familiar with SVN and are not in the mood to learn a DVCS, I wouldn't push for it.

Get an issue tracker that is as light and easy to learn as possible. If the learning curve is too steep, people will not really use it, and you'll end up with no issue tracker at all. That's why I wouldn't advice JIRA or Bugzilla. Lighthouse has always worked great for me.

Introduce some sort of lightweight agilish process. Having a slightly better structured environment may help the team deliver the prototype.

14 people looks like a rather large team. Maybe you could subdivide yourself into 3 smaller teams responsible for different parts of the prototype?

However, try to enforce some sort of discipline when it comes to the non-essential (not directly related to research) parts of the project. After all, computer vision stuff is hard enough as it is - you don't want to fail because of a broken build system or something similar, right?

Last but not least: you shouldn't overdo the whole managing a project thing. After all, if I understand correctly, the goal of the project is to do science - not to have an industry level process. Try to keep all the tools as lightweight as possible - otherwise people will start working around them, and you'll end as if you were doing freestyle development (that's for example why I think Mercurial is a better choice than Git, even though I personally prefer the latter). Finally, remember that academia is more about Learning Cool Stuff on the Way than about Getting Things Done. Try to have fun!

Title: How to manage a project in school?


答:
It's not a C++ lecture series, but Richard Buckland's COMP1917 is an excellently-done lecture series on programming in C (followed with COMP1927, data structures).

In my own opinion, C++ is too much complexity for new students, but C is worlds simpler and provides a good foundation in systems programming that new C++ programmers all too often lack.


问:
Need advice on designing interactions between various parts of my application
I'm trying to design the "main" classe(s) of a Rich Desktop Application based on NetBeans Platform 7.
This application will consume HTTP services and, through a "push system" over TCP, will receive messages.

We are 3 developpers and we want to develop modules in parallel

Application will be layered (Data, Business, Presentation)

We'll use Presentation Model in order to separate responsibilites

Some granular data (a bean Person for example) will be shared by several screens (and possibly displayed on several screens at the same time)

...

We are able to develop individual screens, but We don't know exactly how to organize the whole application and define each module content.

So, have you any advice (a pattern / best practice / book / sample app) to coordinate/manage interactions inside of the whole application?

Any advice about how to define modules content?

Thanks!

Small example to illustrate what I want to build: A Foo User Management Application

Launch the application

At the left [explorer] we have a list of platforms (list is stored in a local file)

At the top we have button to add a new Platform (also available with right click)

By double-clicking on a platform, the app calls a HTTP service a retrieve a complete list of users. This list is displayed in the [editor] (in a JTable)

A background process is started: through a TCP connection we receive messages

It is possible to Add new user thanks to a button in a Toolbar

If the application is launched on another PC, and if the user is connected to the same platform, its User List will be updated dynamically (add/remove/status:{offline/online}) (thanks to messages)

In the future it a Chat Module will be provided.

My question is (in other words): any advice/best practice to decide on content of each module?
If PM (Presentation Model) is a good way to separate view/business and data and create screens, what is the best way to link several screens based on PM?
Imagine we develop the Chat Module, how to add an entry "Discuss with..." to the Context menu available with right click on User List?

答:
Given your requirement, to start with the core processing stuff should be made of Command Pattern and later you can use Template patterns for request-processors. And so on and on. There is nothing called a Master pattern. If there were, they wont need us anymore.

The idea is to have a design that will allow you to evolve with requirements.

I would start by creating a base module interface and give the interface to everyone and some utilities around it. Let everyone implement their own modules based on the base-module.

OwnerDisplayName: Destroyica

OwnerDisplayName: Suraj Chandran


问:
One-line functions that are called only once
Consider a parameterless (edit: not necessarily) function that performs a single line of code, and is called only once in the program (though it is not impossible that it'll be needed again in the future).

It could perform a query, check some values, do something involving regex... anything obscure or "hacky".

The rationale behind this would be to avoid hardly-readable evaluations:

if (getCondition()) {
    // do stuff
}
```

where getCondition() is the one-line function.

My question is simply: is this a good practice? It seems alright to me but I don't know about the long term...

答: In addition to readability (or in complement of it) this allows to write functions at the proper level of abstraction.</p>


答:
Yes.

When trying to shoehorn an app into some tiny, very memory and/or performance constrained, micro-controller.  One can even turn a singleton into a global var/struct/array, which the compiler can optimize into far fewer bytes of machine code.

For super high volume consumer items, beauty is often saving a few pennies or cubic mm.  Generality (portability, reusability, maintainability, etc.) has costs.  No need to pay if you aren't going to use the benefits that go with those costs.


问:
Is an architecture description document a violation of the DRY Principle?
The DRY Principle (Don't Repeat Yourself) states that "every piece of knowledge must have a single, unambiguous, authoritative representation within a system."  Most of the time this refers to code, but it is often extended to documentation also.

It is said that every software system has an architecture whether you chose it or not.  In other words, the software you build has a structure and that "as built" structure is the architecture of the software.  Since a built software system comes with an architecture, is creating an architecture description of that system a violation of the DRY Principle?  After all, if you need to know the architecture then you could always just look at the code...

答:
Does duplicating your thoughts into code violate DRY principle?

Geez, if you could just know the architecture by looking into code, there wouldn't be such things as "architecture description documents" in the first place.  It's not a repitition, it's another level of system description, which can't be trivially deduced from the code, and vice versa.  So it has its full right to exist even if you embrace DRY.


问:
Tdd on a datadriven webapp
How would one go about to use tdd/bdd on a mostly data driven webapp? For example a blog or a forum?</p>

答:
A blog or forum is absolutely perfect for a BDD approach.

If you can get your hands on The RSpec Book and you don't mind reading a bit of Ruby, do so. As it says in the foreword, it's not a book about Ruby, it's a book about behaviour-driven development which happens to use Ruby as a basis.

In short, it will tell you how to use a Gherkin-based syntax to define your behaviours and then drop down into a TDD cycle to design the code behind that behaviour.

It uses a Reddit-style model for its examples, but is very easily translated into both other types of data-driven site and other languages.

Title: Tdd on a datadriven webapp


问:
Warning-free Objective C code
I am currently creating my first iPhone app in Objective C and getting a lot of warnings because I've in many places taken advantage of the fact that Objective C is a dynamically typed language. I get a lot of 'class' may not respond to '-message:' warnings. Should I strive to remove all these warnings? If yes, then what's the benefit of having a dynamic language at your disposal?</p>

答:
I get a lot of 'class' may not respond to '-message:' warnings. Should
  I strive to remove all these warnings?

Yes, get rid of the warnings. If you're sending a message to an object, then you must be pretty confident that the object does, in fact, have a method by that name. Why not let the compiler know that as well? Mostly, this just means using appropriate types for your object pointers.

Say you have a pointer of type UIView*, but you know that any object that the pointer will ever point to will be an instance of UIControl, so it's safe to send a message like -allTargets. That'll work just fine, but the compiler will warn that UIView may not respond to -allTargets. The simple solution is to change the pointer type to UIControl*, since you know that will always be the case anyway.

Another situation is where you have several objects of different types that all happen to implement methods with the same name. In that case, changing the pointer type doesn't seem such a great option because you don't know what type of object you might be dealing with; you only know that any object you deal with supports the message your sending. In that case, declare a protocol containing whatever method or methods you're sending, and declare the pointer as a pointer to an object implementing that protocol, like:

```<code>UIView<MyProtocol> *myPointer;
</code>```

In both cases above, you don't lose any dynamism by fixing the warning. You're just sharing with the compiler your knowledge of the restrictions that already exist. You're also making your code more explicit, which makes it easier to maintain.

Most important, by eliminating these easy-to-fix warnings, you'll make it easier to spot other warnings that might alert you to a more significant problem.

If yes, then what's the benefit of having a dynamic language at your
  disposal?

'Dynamic' here really just means that the ability of an object to respond to a message isn't known until run time. If you were writing in, say, C++, you'd get an error instead of a warning during compilation because the compiler would know for certain that class X does not implement method Y. In Objective-C, you still have to make sure that objects can respond to the messages you send them, but the error you get if you fail in that regard doesn't come until you run the program.

Title: Warning-free Objective C code

Body:
I get a lot of 'class' may not respond to '-message:' warnings. Should
  I strive to remove all these warnings?

Yes, get rid of the warnings. If you're sending a message to an object, then you must be pretty confident that the object does, in fact, have a method by that name. Why not let the compiler know that as well? Mostly, this just means using appropriate types for your object pointers.

Say you have a pointer of type UIView*, but you know that any object that the pointer will ever point to will be an instance of UIControl, so it's safe to send a message like -allTargets. That'll work just fine, but the compiler will warn that UIView may not respond to -allTargets. The simple solution is to change the pointer type to UIControl*, since you know that will always be the case anyway.

Another situation is where you have several objects of different types that all happen to implement methods with the same name. In that case, changing the pointer type doesn't seem such a great option because you don't know what type of object you might be dealing with; you only know that any object you deal with supports the message your sending. In that case, declare a protocol containing whatever method or methods you're sending, and declare the pointer as a pointer to an object implementing that protocol, like:

UIView<MyProtocol> *myPointer;

In both cases above, you don't lose any dynamism by fixing the warning. You're just sharing with the compiler your knowledge of the restrictions that already exist. You're also making your code more explicit, which makes it easier to maintain.

Most important, by eliminating these easy-to-fix warnings, you'll make it easier to spot other warnings that might alert you to a more significant problem.

If yes, then what's the benefit of having a dynamic language at your
  disposal?

'Dynamic' here really just means that the ability of an object to respond to a message isn't known until run time. If you were writing in, say, C++, you'd get an error instead of a warning during compilation because the compiler would know for certain that class X does not implement method Y. In Objective-C, you still have to make sure that objects can respond to the messages you send them, but the error you get if you fail in that regard doesn't come until you run the program.


问:
What is the best way to INSERT a large dataset into a MySQL database (or any database in general)
As part of a PHP project, I have to insert a row into a MySQL database. I'm obviously used to doing this, but this required inserting into 90 columns in one query. The resulting query looks horrible and monolithic (especially inserting my PHP variables as the values):

```<code>INSERT INTO mytable (column1, colum2, ..., column90)
VALUES
('value1', 'value2', ..., 'value90')
</code>```

and I'm concerned that I'm not going about this in the right way. It also took me a long (boring) time just to type everything in and testing writing the test code will be equally tedious I fear.

How do professionals go about quickly writing and testing these queries? Is there a way I can speed up the process?

答:
If you have a csv file, you can use the LOAD DATA INFILE... to import the data.

If you have to use 'INSERT' queries, then doing bulk inserts will speed up the process. Instead of running an 'INSERT' query for every single row, group the rows, say 100 and run the query. Something like this:

```<code>INSERT INTO theTable (col1, col2, col3,....., col89, col90)
VALUES
(val11, val12, val13, ........, val189, val190),
(val21, val22, val23, ........, val289, val290),
.......
......
(val101, val102, val103, ........, va1089, val1090);
</code>```

Body:
If you have a csv file, you can use the LOAD DATA INFILE... to import the data.

If you have to use 'INSERT' queries, then doing bulk inserts will speed up the process. Instead of running an 'INSERT' query for every single row, group the rows, say 100 and run the query. Something like this:

INSERT INTO theTable (col1, col2, col3,....., col89, col90)
VALUES
(val11, val12, val13, ........, val189, val190),
(val21, val22, val23, ........, val289, val290),
.......
......
(val101, val102, val103, ........, va1089, val1090);


答:
I've done this exact thing just recently in an application that I've been refactoring, to make explicit the actual meaning of the code sans comments:

protected void PaymentButton_Click(object sender, EventArgs e)
    Func<bool> HaveError = () => lblCreditCardError.Text == string.Empty && lblDisclaimer.Text == string.Empty;

    CheckInputs();

    if(HaveError())
        return;

    ...
}
```

Title: One-line functions that are called only once

Body:
Consider a parameterless (edit: not necessarily) function that performs a single line of code, and is called only once in the program (though it is not impossible that it'll be needed again in the future).

It could perform a query, check some values, do something involving regex... anything obscure or "hacky".

The rationale behind this would be to avoid hardly-readable evaluations:

if (getCondition()) {
    // do stuff
}
```

where getCondition() is the one-line function.

My question is simply: is this a good practice? It seems alright to me but I don't know about the long term...


问:
Arguments for or against using Try/Catch as logical operators
I just discovered some lovely code in our companies app that uses Try-Catch blocks as logical operators.

Meaning, "do some code, if that throws this error, do this code, but if that throws this error do this 3rd thing instead".

It uses "Finally" as the "else" statement it appears.

I know that this is wrong inherently, but before I go picking a fight I was hoping for some well thought out arguments.

And hey, if you have arguments FOR the use of Try-Catch in this manner, please do tell.

For any who are wondering, the language is C# and the code in question is about 30+ lines and is looking for specific exceptions, it is not handling ALL exceptions.

答:
Try Catch should only be used for exception handling. More so, especific exception handling. Your try catch should catch only expected exceptions, other wise it is not well formed. If you need to use a catch all try catch, then you are probably doing something wrong.

EDIT:

Reason: You can argue that if you use try catch as a conditional operator, How are you going to account for REAL exceptions?


答:
Exception handling tends to be an expensive way to handle flow control (certainly for C# and Java).

The runtime does quite a lot of work when an exception object is constructed - getting the stack trace together, figuring out where the exception is handled and more.

All this costs in memory and CPU resources that do not need to be expanded if flow control statements are used for flow control.

Additionally, there is a semantic issue. Exceptions are for exceptional situations, not for normal flow control. One should use exception handling for handling unanticipated/exceptional situations, not as normal program flow, because otherwise, an uncaught exception will tell you much less.

Apart from these two, there is the matter of others reading the code. Using exceptions in such a manner is not something most programmers will expect, so readability and how understandable your code is suffer. When one sees "Exception", one thinks - something bad happened, something that is not supposed to happen normally. So, using exceptions in this manner is just plain confusing.

Title: Arguments for or against using Try/Catch as logical operators

Body:
I just discovered some lovely code in our companies app that uses Try-Catch blocks as logical operators.

Meaning, "do some code, if that throws this error, do this code, but if that throws this error do this 3rd thing instead".

It uses "Finally" as the "else" statement it appears.

I know that this is wrong inherently, but before I go picking a fight I was hoping for some well thought out arguments.

And hey, if you have arguments FOR the use of Try-Catch in this manner, please do tell.

For any who are wondering, the language is C# and the code in question is about 30+ lines and is looking for specific exceptions, it is not handling ALL exceptions.


答: My main argument is that using try/catch for logic breaks the logical flow. Following "logic" through non-logic constructs is (to me) counter-intuitive and confusing. I'm used to reading my logic as "if Condition then A else B". Reading the same statement as "Try A catch then execute B" feels weird. It would be even weirder if statement A is a simple assignment, requiring extra code to force an exception if condition is false (and doing that would probably require an if-statement anyway).


答: Exception are for when Exceptional thing happen.  Is the program functioning according to regular workflow exceptional?</p>


答:
I've seen this pattern used several times.

There are 2 major problems:

It's extremely expensive (instantiation of the exception object, gathering the call stack etc.). Some compilers might actually be able to optimize it away, but I wouldn't count on that in this case, because exceptions are not intended for such use, therefore you can't expect people to optimize for it.

Using exceptions for control flow is in fact a jump, much like a goto. Jumps are considered harmful, for a number of reasons. They should be used, if all the alternatives have considerable disadvantages. In fact, in all my code I recall only 2 cases, where jumps were clearly the best solution.


答:
It is a bad habit, but I do it from time to time in python.  Like instead of checking to see if a file exists I just try and delete it.  If it throws an exception, I catch and just move on knowing that it wasn't there. <==(not necessarily true if another user owns the file, but I do it in a user's home directory so this SHOULDN'T happen).

Still, overused it's a bad practice.


答:
The old game Dark Forces 2: Jedi Knight did not have this issue.  Essentially, all game assets were stored in a place.  You could add additional assets and use them(as long as they weren't overriding assets...for example replacing skins) and all was honky-dory.  You just had to reference custom stages/assets by unique name.  It's just proper design and including the pack-name as part of the asset ID.

If I'm grossly mis-understanding your question let me know, but I think this is a valid approach to what you're facing.


问:
Removing elements of an 'at least one' association
let's assume - regardless from technology and programming languages - you have a type and the type has an association to another type. This association has the complexity of 'at least one' (1..n). How would you specify the behavior, when removing elements from this association based on a predicate? Say, the predicate fits to all elements, thus the removal would violate the 1..n constraint, would you remove all elements but one or would you rather not remove any element in this case (and have a transactional-like behavior)?</p>

答:
I would simply not allow removal of all elements. Do not expose such an option in your domain model.

A RemoveAllBut(element) method might be acceptable, though it will need to check that the element is indeed in the collection.


问:
Is there a specific design strategy that can be applied to solve most chicken-and-egg problems while using immutable objects?
Coming from a OOP background (Java), I'm learning Scala on my own. While I can readily see the advantages of using immutable objects individually, I'm having a hard time seeing how one can design a whole application like that. I'll give an example:

Say I have objects that represents "materials" and their properties (I'm designing a game, so I actually really have that problem), like water and ice. I would have a "manager" that owns all such materials instances. One property would be the freezing and melting point, and what the material freezes or melts to.

[EDIT] All material instances are "singleton", kind of like a Java Enum.

I want "water" to say it freezes to "ice" at 0C, and "ice" to say it melts to "water" at 1C. But if water and ice are immutable, they cannot get a reference to each other as constructor parameters, because one of them has to be created first, and that one could not get a reference to the not-yet-existing other as constructor parameter. I could solve this by giving them both a reference to the manager so that they can query it to find the other material instance they need every time they are being asked for their freezing/melting properties, but then I get the same problem between the manager and the materials, that they need a reference to each other, but it can only be provided in the constructor for one of them, so either the manager or the material cannot be immutable.

Is their just no way around this problem, or do I need to use "functional" programming techniques, or some other pattern to solve it?

答:
In your example, you're applying a transformation to an object so I would use something like an ApplyTransform() method that returns a BlockBase rather than trying to change the current object.

For example, to change an IceBlock to a WaterBlock by applying some heat, I would call something like

```<code>BlockBase currentBlock = new IceBlock();
currentBlock = currentBlock.ApplyTemperature(1);
// currentBlock is now a WaterBlock
</code>```

and the IceBlock.ApplyTemperature() method would look something like this:

```<code>public class IceBlock() : BlockBase
{
    public BlockBase ApplyTemperature(int temp)
    {
        return (temp > 0 ? new WaterBlock((BlockBase)this) : this);
    }
}
</code>```

Body:
In your example, you're applying a transformation to an object so I would use something like an ApplyTransform() method that returns a BlockBase rather than trying to change the current object.

For example, to change an IceBlock to a WaterBlock by applying some heat, I would call something like

BlockBase currentBlock = new IceBlock();
currentBlock = currentBlock.ApplyTemperature(1);
// currentBlock is now a WaterBlock

and the IceBlock.ApplyTemperature() method would look something like this:

public class IceBlock() : BlockBase
{
    public BlockBase ApplyTemperature(int temp)
    {
        return (temp > 0 ? new WaterBlock((BlockBase)this) : this);
    }
}


问:
How do I go about data deduplication at scale?
I need to develop, or at least conceptualize a module that does efficient data deduplication. Say we have millions of data records already. Insertion of another 100 mn records, making sure that there are no duplicate records in the resultant dataset, is what the module needs to do, at the top level. Now this may mean comparing on a field(s) that decides whether records are duplicate or not. But this approach, taken serially, is really naive, when we're talking millions of records.

What do you think can a viable approach be? Hashing? using divide and conquer type algorithms to exploit parallelism? I have these in my head, but it really gets giddy at such scale.

Also, please post any pointers to resources on the Web I can use - I could only find debates and vendors saying things about their db's "supreme data deduplication features".

答:
Try using MapReduce.

edit:  Here's a wiki entry on map reduce.  Here's how I would go about using map reduce on this task:

The Mapping function would map the item to itself (e.g. return a pair ). The Reduce function would, for a pair of duplicate items, delete one of the items.


答:
The solution is to cheat a little bit.  Specifically:

Create A, but leave its reference to B uninitialized (as B doesn't exist yet).

Create B, and have it point to A.

Update A to point to B.  Do not update either A or B after this.

This can either be done explicitly (example in C++):

```<code>struct List {
    int n;
    List *next;

    List(int n, List *next)
        : n(n), next(next);
};

// Return a list containing [0,1,0,1,...].
List *binary(void)
{
    List *a = new List(0, NULL);
    List *b = new List(1, a);
    a->next = b; // Evil, but necessary.
    return a;
}
</code>```

or implicitly (example in Haskell):

```<code>binary :: [Int]
binary = a where
    a = 0 : b
    b = 1 : a
</code>```

The Haskell example uses lazy evaluation to achieve the illusion of mutually dependent immutable values.  The values start out as:

```<code>a = 0 : <thunk>
b = 1 : a
</code>```

a and b are both valid head-normal forms independently.  Each cons can be constructed without needing the final value of the other variable.  When the thunk is evaluated, it will then point to the same data b points to.

Thus, if you want two immutable values to point to each other, you either have to update the first after constructing the second, or use a higher-level mechanism to do the same.

In your particular example, I might express it in Haskell as:

```<code>data Material = Water {temperature :: Double}
              | Ice   {temperature :: Double}

setTemperature :: Double -> Material -> Material
setTemperature newTemp (Water _) | newTemp <= 0.0 = Ice newTemp
                                 | otherwise      = Water newTemp
setTemperature newTemp (Ice _)   | newTemp >= 1.0 = Water newTemp
                                 | otherwise      = Ice newTemp
</code>```

However, I'm side-stepping the issue.  I'd imagine that in an object-oriented approach, where a setTemperature method is attached to the result of each Material constructor, you would have to have the constructors point to each other.  If the constructors are treated as immutable values, you can use the approach outlined above.

Title: Is there a specific design strategy that can be applied to solve most chicken-and-egg problems while using immutable objects?

Body:
Coming from a OOP background (Java), I'm learning Scala on my own. While I can readily see the advantages of using immutable objects individually, I'm having a hard time seeing how one can design a whole application like that. I'll give an example:

Say I have objects that represents "materials" and their properties (I'm designing a game, so I actually really have that problem), like water and ice. I would have a "manager" that owns all such materials instances. One property would be the freezing and melting point, and what the material freezes or melts to.

[EDIT] All material instances are "singleton", kind of like a Java Enum.

I want "water" to say it freezes to "ice" at 0C, and "ice" to say it melts to "water" at 1C. But if water and ice are immutable, they cannot get a reference to each other as constructor parameters, because one of them has to be created first, and that one could not get a reference to the not-yet-existing other as constructor parameter. I could solve this by giving them both a reference to the manager so that they can query it to find the other material instance they need every time they are being asked for their freezing/melting properties, but then I get the same problem between the manager and the materials, that they need a reference to each other, but it can only be provided in the constructor for one of them, so either the manager or the material cannot be immutable.

Is their just no way around this problem, or do I need to use "functional" programming techniques, or some other pattern to solve it?

Body:
The solution is to cheat a little bit.  Specifically:

Create A, but leave its reference to B uninitialized (as B doesn't exist yet).

Create B, and have it point to A.

Update A to point to B.  Do not update either A or B after this.

This can either be done explicitly (example in C++):

struct List {
    int n;
    List *next;

    List(int n, List *next)
        : n(n), next(next);
};

// Return a list containing [0,1,0,1,...].
List *binary(void)
{
    List *a = new List(0, NULL);
    List *b = new List(1, a);
    a->next = b; // Evil, but necessary.
    return a;
}

or implicitly (example in Haskell):

binary :: [Int]
binary = a where
    a = 0 : b
    b = 1 : a

The Haskell example uses lazy evaluation to achieve the illusion of mutually dependent immutable values.  The values start out as:

a = 0 : <thunk>
b = 1 : a

a and b are both valid head-normal forms independently.  Each cons can be constructed without needing the final value of the other variable.  When the thunk is evaluated, it will then point to the same data b points to.

Thus, if you want two immutable values to point to each other, you either have to update the first after constructing the second, or use a higher-level mechanism to do the same.

In your particular example, I might express it in Haskell as:

data Material = Water {temperature :: Double}
              | Ice   {temperature :: Double}

setTemperature :: Double -> Material -> Material
setTemperature newTemp (Water _) | newTemp <= 0.0 = Ice newTemp
                                 | otherwise      = Water newTemp
setTemperature newTemp (Ice _)   | newTemp >= 1.0 = Water newTemp
                                 | otherwise      = Ice newTemp

However, I'm side-stepping the issue.  I'd imagine that in an object-oriented approach, where a setTemperature method is attached to the result of each Material constructor, you would have to have the constructors point to each other.  If the constructors are treated as immutable values, you can use the approach outlined above.


答: An Architecture Description, or Software Design Description does violate DRY. However, in a large organization, where projects last years, developers come and go, and the system is too large for any one person to keep all the details in their head, it is a critical document. The amount of "repetition" needed to keep it in synch is totally worth it for the effort it saves during the next update or maintenance.

Title: Is an architecture description document a violation of the DRY Principle?

Body:
The DRY Principle (Don't Repeat Yourself) states that "every piece of knowledge must have a single, unambiguous, authoritative representation within a system."  Most of the time this refers to code, but it is often extended to documentation also.

It is said that every software system has an architecture whether you chose it or not.  In other words, the software you build has a structure and that "as built" structure is the architecture of the software.  Since a built software system comes with an architecture, is creating an architecture description of that system a violation of the DRY Principle?  After all, if you need to know the architecture then you could always just look at the code...


答: I like the way Apple defines it: Exceptions are only for programmer errors and fatal runtime errors. Else use error codes. It helps me to decide when to use it, thinking to myself "Was this a programmer error?"</p>


答:
That depends on the context:

If there were a default element (an element that somehow stands out), I would prefer your second suggestion of deleting all but that one element.

If all elements are equal and it makes no sense to define a default element, I would not select an arbitrary one not to delete, because that seems like it could lead to confusing and arbitrary behavior. And an unclean design, because if the predicate makes sense, then why doesn't the multiplicity  of the association have (0..n)? I would thus look for a different solution, e.g.

restrict the predicate to those that don't fit to all elements, if that makes sense in your case

not remove any element and give the according feedback to the user/client, so that he can change the predicate or pick one element not to delete

change the association to (0..n).

Title: Removing elements of an 'at least one' association

Body: let's assume - regardless from technology and programming languages - you have a type and the type has an association to another type. This association has the complexity of 'at least one' (1..n). How would you specify the behavior, when removing elements from this association based on a predicate? Say, the predicate fits to all elements, thus the removal would violate the 1..n constraint, would you remove all elements but one or would you rather not remove any element in this case (and have a transactional-like behavior)?</p>


答:
To deduplicate values that are exactly equal, (rather than almost equal), you can simply use a dictionary keyed by a strong-enough cryptographic hash.  Example, using PostgreSQL types:

```<code>CREATE TABLE dictionary (
    sha256 BYTEA PRIMARY KEY,
    value  BYTEA
);
</code>```

The advantage of doing this is that it makes the lookup operation much faster.  Rather than comparing entire strings (which could potentially be very large), you're merely comparing 256-bit (32-byte) values.

This makes the assumption that you will never encounter two different strings with the same SHA-256 hash.  Although such pairs of strings do exist in theory due to the pidgenhole principle—a SHA-256 hash is only 256 bits, whereas a byte string can be (and typically will be) much longer—nobody has found such a pair.

If your values aren't byte strings, you will need to find a way to serialize them.

Title: How do I go about data deduplication at scale?

Body:
I need to develop, or at least conceptualize a module that does efficient data deduplication. Say we have millions of data records already. Insertion of another 100 mn records, making sure that there are no duplicate records in the resultant dataset, is what the module needs to do, at the top level. Now this may mean comparing on a field(s) that decides whether records are duplicate or not. But this approach, taken serially, is really naive, when we're talking millions of records.

What do you think can a viable approach be? Hashing? using divide and conquer type algorithms to exploit parallelism? I have these in my head, but it really gets giddy at such scale.

Also, please post any pointers to resources on the Web I can use - I could only find debates and vendors saying things about their db's "supreme data deduplication features".

Body:
To deduplicate values that are exactly equal, (rather than almost equal), you can simply use a dictionary keyed by a strong-enough cryptographic hash.  Example, using PostgreSQL types:

CREATE TABLE dictionary (
    sha256 BYTEA PRIMARY KEY,
    value  BYTEA
);

The advantage of doing this is that it makes the lookup operation much faster.  Rather than comparing entire strings (which could potentially be very large), you're merely comparing 256-bit (32-byte) values.

This makes the assumption that you will never encounter two different strings with the same SHA-256 hash.  Although such pairs of strings do exist in theory due to the pidgenhole principle—a SHA-256 hash is only 256 bits, whereas a byte string can be (and typically will be) much longer—nobody has found such a pair.

If your values aren't byte strings, you will need to find a way to serialize them.


答:
I think hashing is the way to go. Quick lookup & quick insertions. I'd already try it out directly. 100m records don't seem that much to me ...but of course it'll take many hours.

If needed, one way of dividing the workload is to split the data in bundles of hashes. For instance, PC number i reads all records having a hash_value % N == i and then inserts/rejects all the additional records having also hash_value % N == i. Once you are done, merge the N datasets and you have your result.

Edit:

One way to make it slightly more efficient is to use 2 hashes. A quick and easy hash, on a single field for instance, used for a quick filtering hash % N == i. And a normal hash for the actual insertion/lookup in the database itself.


问:
What is the difference between artificial intelligence (AI) and swarm intelligence?
I understand that when we try to implement swarm intelligence, it basically has multiple independent units communicating and with each other. What I am unsure of is if swarm intelligence an extension of artificial intelligence or if it is a discipline in and of itself.</p>

答: swam intelligence is based less on the learning and who currently has the needed information. For example an Full AI may learn and know things on its own. You give it some infomation and it stores it the best way it can. In SI when a node does not know something it asks the other nodes if they know. If the other nodes dont know then that node is forced to figure out what to do. If another node then comes around asked the same question then the node that learned it before just returns the answer. In some cases the swam has to work togetahter to learn "bigger" things but that is really based on how the swam is setup. </p>


答:
Well, just a matter of etiquette, before "starting an argument with them", as you state it, I would kindly ask "Why they use exception handling in all these different places?"

I mean, there are several possibilities:

they are incompetent

there is a perfectly valid reason for what they did, which may not appear at first sight.

sometimes it is a question of taste and may simplify some complex program flow.

It's a relic of the past that nobody changed yet and they'd be happy if someone does it

...I think all of these are equally likely. So just ask them nicely.


问:
Being stupid to get better productivity?
I've spent a lot of time reading different books about "good design", "design patterns", etc. I'm a big fan of the SOLID approach and every time I need to write a simple piece of code, I think about the future. So, if implementing a new feature or a bug fix requires just adding three lines of code like this:

if(xxx) {
    doSomething();
}
```

It doesn't mean I'll do it this way. If I feel like this piece of code is likely to become larger in the nearest future, I'll think of adding abstractions, moving this functionality somewhere else and so on. The goal I'm pursuing is keeping average complexity the same as it was before my changes.

I believe, that from the code standpoint, it's quite a good idea - my code is never long enough, and it's quite easy to understand the meanings for different entities, like classes, methods, and relations between classes and objects.

The problem is, it takes too much time, and I often feel like it would be better if I just implemented that feature "as is". It's just about "three lines of code" vs. "new interface + two classes to implement that interface".

From a product standpoint (when we're talking about the result), the things I do are quite senseless. I know that if we're going to work on the next version, having good code is really great. But on the other side, the time you've spent to make your code "good" may have been spent for implementing a couple of useful features.

I often feel very unsatisfied with my results - good code that only can do A is worse than bad code that can do A, B, C, and D.

Is this approach likely to result in a positive net gain for a software project, or is it a waste of time?

答:
Having seen such prematurely generalized designs that did not fit at all to the actual requirements that came later, I devised a rule for me:

For hypothetical requirements only write hypothetical code.

That is: you are well advised to think about changes that might occur later. But only use these insights to choose a design for the code that can easily be changed and refactored if those requirements actually come up. You may even write some code in your head (hypothetical code) that you would want to write in that case, but do not write any actual code!


问:
What percentage of bugs should be stamped out before a project can be accepted as a stable release?
We have been working with a shopping cart for DotNetNuke, and have had endless problems with the developer's releases of their product. Every release fixes one thing but new bugs pop up elsewhere.

I know that bugs are inevitable and that we cannot squash all of them at the time, but can someone please tell me what percentage of bugs should be stamped out before a product can be accepted as a stable release?

答:
I always look at my bugs by how the program is going to be used and does it affect the user. If its a bad end system for developers that know what they are doing and they can avoid the bug with a little extra typing then you can relase it as an RC but not really a stable if its going to be used for users you have to think of every user like your grandparents they are always going to not know what to do.

Keep your known bugs as close to 0% as posiable for the amount of time. If you HAVE to relase something with bugs make sure you post the known bugs so people can be aware. And try to make sure your bugs are less critical. I was making a multilayered comment system. I had a bug that you could comment on any post but the first one. well that was nice but needed to be fixed because someone will want to comment on the first one.

OwnerDisplayName: SixfootJames


答:
The Objective-C compiler automatically inserts casts into the binary code where the arguments and return types are of different types (e.g. different size integers). If the compiler can't unambiguously figure out the signature of the method you're using at compile time, it's possible it can get this wrong leading to very weird bugs.

(This is why the compiler also has special warning messages for "no method found" and "multiple methods found", since in those cases it's even more likely to get it wrong)

Title: Warning-free Objective C code

Body: I am currently creating my first iPhone app in Objective C and getting a lot of warnings because I've in many places taken advantage of the fact that Objective C is a dynamically typed language. I get a lot of 'class' may not respond to '-message:' warnings. Should I strive to remove all these warnings? If yes, then what's the benefit of having a dynamic language at your disposal?</p>


问:
Is anyone doing "real" TDD with Visual-C++, and if yes, how do they do it?
Test Driven Development implies writing the test before the code and following a certain cycle:

Write Test

Check Test (run)

Write Production Code

Check Test (run)

Clean up Production Code

Check test (run)

As far as I'm concerned, this is only possible if your development solution allows you to very quickly switch between the production and test code, and to execute the test for a certain production code part extremely quickly.

Now, while there exist lots of Unit Testing Frameworks for C++ (I'm using Bost.Test atm.) it does seem that there doesn't really exist any decent (for native C++) Visual Studio (Plugin) solution that makes the TDD cycle bearable regardless of framework used.

"Bearable" means that it's a one-click action to run a test for a certain cpp file without having to manually set up a separate testing project etc. "Bearable" also means that a simple test starts (linking!) and runs very quickly.

So, what tools (plugins) and techniques are out there that make the TDD cycle possible for native C++ development with Visual Studio?

Note: I'm fine with free or "commercial" tools.

Please: No framework recommendations. (Unless the framework has a dedicated Visual Studio plugin and you want to recommend the plugin.)

Edit Note: The answers so far have provided links on how to integrate a Unit Testing framework into Visual Studio. The resources more or less describe how to get the UT framework to compile and get your first Tests running. This is not what this question is about. I'm of the opinion that to really work productively, having the Unit Tests in a manually maintained(!), separate vcproj from your production classes will add so much overhead that TDD "isn't possible". As far as I am aware, you do not add extra "projects" to a Java or C# thing to enable Unit Tests and TDD, and for a good reason. This should be possible with C++ given the right tools, but it seems (this question is about) that there are very little tools for TDD/C++/VS.

Googling around, I've found one tool, VisualAssert, that seems to aim in the right direction. However, afaiks, it doesn't seem to be in widespread use (compared to CppUnit, Boost.Test etc.).

Edit: I would like to add a comment to the context for this question. I think it does a good summary of outlining (part of) the problem: (comment by Billy ONeal)

Visual Studio does not use "build scripts" that are reasonably
  editable by the user. One project produces one binary. Moreover, Java
  has the property that Java never builds a complete binary -- the
  binary you build is just a ZIP of the class files. Therefore it's
  possible to compile separately then JAR together manually (using e.g.
  7z). C++ and C# both actually link their binaries, so generally
  speaking you can't write a script like that. The closest you can get
  is to compile everything separately and then do two linkings (one for
  production, one for testing).

答:
Can't comment on C++ tools as I've not touched in about 20 years (.NET dev these days) and I guess most of the tools these days are for managed code but as for techniques...

As others have mentioned, test code is always in a completely different project/assembly than production code and yes you usually have to maintain that project yourself, although certainly in the VS IDE this isn't a big problem as you often have several projects as part of your solution anyway.

Production code is and has to be written a little different for TDD. As you write the tests first you end up having to design your code to be testable. This is whole other subject in itself but can take time and seem very frustrating at first especially if your IDE/tools don't give you quick feedback, shelling out to run command-line tools to run tests is just to disruptive.

There are lots of specific techniques for making code testable, but most of them break down in to making small objects that don't do much so you can test them in isolation and being able to inject a test version of some behaviour in to more complex objects. IOC frameworks can help a lot here.

A book you may find useful is; Michael Feathers, Working Effectively with Legacy Code. This uses multiple languages in its examples and may help you identify specific approaches to safely adapt code/techniques that were not originally designed to be testable.

Small caveat: I drunk from the Agile Kool-Aid years ago :D


答:
You may want to look into a rolling hash function.  With one, you can compute the hash of a given window of bytes, then "roll" it one byte forward to find the hash of the next window of bytes:

```<code>Hello world
[    ]
 [    ]
  [    ]
   [    ]
    [    ]
     [    ]
</code>```

If your task is to create an object store that works with binary blobs, you could do something like this:

Maintain a hash table of fixed-size chunks (in this example, 64-byte chunks and 32-bit hashes).

When a new blob is inserted, hash every 64 bytes of it, and store each chunk in the hash table.  "Compress" the blob by encoding it as an array of hashes and strings.  Bear in mind the possibility of hash collisions.

```<code>------------------------------
[1fedccba][deadbeef][13579ace]
</code>```

When a subsequent blob is inserted, roll through it to find chunks we already have:

```<code>---------------------------
[a7ed8842]
 [cb438564]
  [e5fe0527]
   [c2ff4713]
    [1fedccba] *** Chunk matches one we already have.
              [793bd55d]
               [45a39f7e]
                [dace4e10]
                 [ee6fcc7b]
</code>```

This technique can be used to deduplicate chunks of data even in the presence of insertions and deletions, or variations in alignment due to serialization.

Body:
You may want to look into a rolling hash function.  With one, you can compute the hash of a given window of bytes, then "roll" it one byte forward to find the hash of the next window of bytes:

Hello world
[    ]
 [    ]
  [    ]
   [    ]
    [    ]
     [    ]

If your task is to create an object store that works with binary blobs, you could do something like this:

Maintain a hash table of fixed-size chunks (in this example, 64-byte chunks and 32-bit hashes).

When a new blob is inserted, hash every 64 bytes of it, and store each chunk in the hash table.  "Compress" the blob by encoding it as an array of hashes and strings.  Bear in mind the possibility of hash collisions.

------------------------------
[1fedccba][deadbeef][13579ace]

When a subsequent blob is inserted, roll through it to find chunks we already have:

---------------------------
[a7ed8842]
 [cb438564]
  [e5fe0527]
   [c2ff4713]
    [1fedccba] *** Chunk matches one we already have.
              [793bd55d]
               [45a39f7e]
                [dace4e10]
                 [ee6fcc7b]

This technique can be used to deduplicate chunks of data even in the presence of insertions and deletions, or variations in alignment due to serialization.


问:
What should I name this helper class?
Usually when writing unit tests I create a helper class with extension methods. I use these methods exclusively for generating generic data for things that I am too lazy to type out. I usually name these classes something relevant to the class under test - for example, I'll follow a pattern like TestHelper.cs.

I've read that helper classes don't promote good design; however I know SOLID principles pretty well and I don't see how using "helpers" in the way described is violating any principles.

I think the issue I'm having is with the name of my "TestHelper" ... Should I simply come up with a new naming scheme or am I really violating a SOLID Principle by utilizing these helpers?

答:
I don't see how this violates SOLID or relates to SOLID at all.

In terms of class naming, if the purpose it to generate test data, you can use a naming convention like <test name>DataGenerator and a GetTestData extension method to make it as clear as possible.

Title: What should I name this helper class?


答:
Here some other suggestions, you can use:

Mocks

[AssemblySetUp] *

[FixtureSetUp] *

*(from NUnit, or similar in other framework)

Title: What should I name this helper class?

Body:
Usually when writing unit tests I create a helper class with extension methods. I use these methods exclusively for generating generic data for things that I am too lazy to type out. I usually name these classes something relevant to the class under test - for example, I'll follow a pattern like TestHelper.cs.

I've read that helper classes don't promote good design; however I know SOLID principles pretty well and I don't see how using "helpers" in the way described is violating any principles.

I think the issue I'm having is with the name of my "TestHelper" ... Should I simply come up with a new naming scheme or am I really violating a SOLID Principle by utilizing these helpers?


答:
Don't take DRY as a hard and fast rule. It's a good thing, but you can only approximate it in practice.

Also I think it's not well written. "Don't repeat yourself" doesn't seem to cover the equally important case that to make a semantic or functional change you would have to edit source text in multiple places, saying different but coordinated things.

Rather than take it as a commandment not to be violated, it is better to understand why it is a good idea and make sensible choices about it. The reason it is bad to have to make coordinated edits in multiple places is that you, the editor, make mistakes. You are not 100% reliable to make the changes without error. If you have to make 10 different source text changes, and you only get 9 of them right, you've put in a bug. That is why arranging the source text to minimize the number of coordinated changes is a good thing. It minimizes bugs.

We don't belong to a religion in which DRY is one of the commandments. It is just a handy, though slightly misleading, way to encapsulate some common sense.


答:
Debug and maintenance work is very difficult when control flow is performed using exceptions.

Inherently, exceptions are designed to be a mechanism for altering the normal control flow of your program - of performing unusual activities, causing unusual side-effects, as a way to get out of a particularly tight bind that can't be handled with less complicated means. Exceptions are exceptional. This means that, depending on which particular environment you're working in, use of exception for regular control flow can cause:

Inefficiency The additional hoops that the environment has to jump through to safely perform the relatively difficult context changes required for exceptions require instrumentation and resources.

Debug difficulties Sometimes useful (when trying to debug a program) information gets thrown out the window when exceptions occur. You can lose track of program state or history that's relevant for understanding run-time behavior

Maintenance problems Execution flow is hard to follow through exception jumps. Beyond that, an exception may get thrown from inside black-box type code, which may not behave in easy to understand ways when throwing an exception.

Poor design decisions Programs built in this manner encourage a frame of mind which, in most cases, doesn't easily map to solving problems elegantly. The complexity of the final program discourages the programmer from understanding fully its execution, and encourages taking decisions which lead to short-term improvements with high long-term costs.


答:
Hashing?

Essential.

using divide and conquer type algorithms to exploit parallelism?

If necessary.

Consider this.

You have millions of rows already in the DB.  Each row must have  single surrogate PK field that's (ideally) a number.  Each row also has the key fields used for duplicate detection.

Compute a hash of the various comparison key fields.  Load that hash and PK into an in-memory hashmap (or treemap).  This is 2 million a few megabytes of memory.  Hardly anything on a reasonably modern processor.  The slowest part is computing the hash of millions of rows.

Each incoming row gets checked against the hashmap.  If it's in the map, the comparison keys indicate a duplicate.  If it's not in the map, it's okay.

That should cover most bases.  The odds of a "false positive" collision is really small.  And (for possible duplicates) you simply redo the check to confirm that they keys are indeed a duplicate.

If the comparison key fields are proper keys, they can't be updated.  You can denormalize the entire PK-key hash map outside the database and avoid rebuilding it.

If the comparison keys fields are attributes (and can be updated), you have to handle denormalization of the hash values gracefully.  A change to a comparison key changes the hash values.  Compute it at the time of the update and save a memento of this change so that the comparison hash can be tweaked without being rebuilt from scratch.


答:
This is not anti-SOLID at all, but you may want to consider the Object Mother pattern, which solves exactly the same problem in a similar way and has the added bonus of giving you a funky suffix to use in your class names.

Plus, like all patterns, because they do have a name, any newcomer to the team can simply google the term Object Mother and find a wealth of information, explaining what it is you've done.

Title: What should I name this helper class?


答:
Another way of breaking the cycle is to separate the concerns of material and transmutation, in some made up language:</p>

```<code>water = new Block("water");
ice = new Block("ice");

transitions = new Transitions([
    new transitions.temperature.Below(0.0, water, ice),
    new transitions.temperature.Above(0.0, ice, water),
]);
</code>```

Body:
Another way of breaking the cycle is to separate the concerns of material and transmutation, in some made up language:

water = new Block("water");
ice = new Block("ice");

transitions = new Transitions([
    new transitions.temperature.Below(0.0, water, ice),
    new transitions.temperature.Above(0.0, ice, water),
]);


答:
I use try->catch as flow control in certain situations. If your primary logic depends on something that fails, but you don't want to just throw an exception and quit...That's what a try->catch block is for. I write a lot of unmonitored server-side unix scripts, and its far far more important for them not to fail, than it is for them to fail prettily.

So try Plan A, and if Plan A dies, catch and run with Plan B...And if plan B fails, use finally to kick off Plan C, which will either fix one of the failed services in A or B, or page me.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Anyone attempting to produce random numbers by purely arithmetic means is, of course, in a state of sin.

    — John von Neumann


问:
With agile, what do when a user story doesn't get completed in an iteration?
Do you just move the story to a new iteration, or delay the next iteration?

It gets a bit tricky when you use something like Jira when you have to copy or move around stories between iterations as it effects calculations of velocity/points etc.

Is there a best-practice?

答: Move the story to the next iteration. Possibly update it's size, if a fair amount of work has been done on it.</p>

OwnerDisplayName: codecompleting

OwnerDisplayName: Alec Munro


答:
You can move the story to the next iteration and estimate again.
You can always discuss with product owner / team and scrum master what to do.</p>

Title: With agile, what do when a user story doesn't get completed in an iteration?

Body:
Do you just move the story to a new iteration, or delay the next iteration?

It gets a bit tricky when you use something like Jira when you have to copy or move around stories between iterations as it effects calculations of velocity/points etc.

Is there a best-practice?

OwnerDisplayName: Daan Geurts


答:
In addition to other answers, you could

1)  create a story to represent the completed work, and a new one for the remaining work, adjusting estimates.

2)  analyze why there was a mis-estimate.  Stories typically represent commitments, and if a commitment wasn't met, it's kind of bad.  Was there not enough analysis up front (i.e. devs didn't know how much work it would actually be), did people get sick, did other bugs prevent the work from being done, etc?

OwnerDisplayName: hvgotcodes


答:
The iteration size is supposedly fixed.  The best approach (according to me :) ) is to split.
Typically when tasks are not completed within the iteration they are assigned to, I suggest splitting the user stories and move the incomplete tasks to the next iteration.  The estimate of the new user story is calculated from the remaining units necessary to complete the original user story.  This way you can keep the estimates and also maintain historical references.</p>


答:
In my experiences, stories are either done or not done. There is no concept of an unfinished story. At the end of a sprint, you either completed the design, implementation, testing, integration, and system testing for a story and presented it to the customer for sign-off, at which point it was moved out of the backlog or it remained in the backlog for the next sprint. There was no concept of re-estimation or partially completed stories.

At the beginning of the next iteration, a N point story that was started in the previous iteration and left unfinished was still considered to be a N point story. Our velocity for the previous sprint was used to pull down an appropriate number of story points for the next sprint, starting with the N unfinished points and the top stories until the number of story points in the iteration was the velocity of the previous points.

However, that was just our practice. The key is to be consistent. Whatever you choose, do that at every iteration and don't change - that will affect how you compute velocity and estimate work for future sprints.