问:
Why would I learn C++11, having known C and C++?
I am a programmer in C and C++, although I don't stick to either language and write a mixture of the two. Sometimes having code in classes, possibly with operator overloading, or templates and the oh so great STL is obviously a better way. Sometimes use of a simple C function pointer is much much more readable and clear. So I find beauty and practicality in both languages. I don't want to get into the discussion of "If you mix them and compile with a C++ compiler, it's not a mix anymore, it's all C++" I think we all understand what I mean by mixing them. Also, I don't want to talk about C vs C++, this question is all about C++11.

C++11 introduces what I think are significant changes to how C++ works, but it has introduced many special cases, exceptions and irregularities that change how different features behave in different circumstances, placing restrictions on multiple inheritance, identifiers that act as keywords, extensions of string literals, lambda function variable capturing, etc.

I know that at some point in the future, when you say C++ everyone would assume C++11. Much like when you say C nowadays, you most probably mean C99. That makes me consider learning C++11. After all, if I want to continue writing code in C++, I may at some point need to start using those features simply because my colleagues have.

Take C for example. After so many years, there are still many people learning and writing code in C. Why? Because the language is good. What good means is that, it follows many of the rules to create a good programming language. So besides being powerful (which easy or hard, almost all programming languages are), C is regular and has few exceptions, if any. C++11 however, I don't think so. I'm not sure that the changes introduced in C++11 are making the language better.

So the question is: Why would I learn C++11?

答:
You should learn it if you think you will need to know it in the future in order to get a job. If you are confident you will remain marketable in the workforce as a C/C++ [ and whatever else you might know ] then don't learn it. If your boss tells you to use C++11, say "no, I don't do that". If he fires you, go work somewhere else. Learn C++11 when you foresee that soon you will be unable to find satisfactory employment with the skills you currently know.

Wanted to clarify my rationale: I'm not anti-C++11. Just saying you could generalize the OP's question to "Why should I learn X". I never learned ML, scheme, or haskell because I have a job with C and C++. I'm sure those languages are useful to someone, but they're not beneficial for me to learn right now. If someone offered me good money to program in ML, I might try to learn it.

OwnerDisplayName: anon


问:
Can anyone help solve this complex algorithmic problem?
I got this question in an interview and I was not able to solve it.

You have a circular road, with N number of gas stations.

You know the amount of gas that each station has.

You know the amount of gas you need to GO from one station to the next one.

Your car starts with 0.

You can only drive clockwise.

The question is: Create an algorithm, to know from which gas station you must start driving so that you complete a full circle.

As an exercise to me, I would translate the algorithm to C#.

答:
I feel like given quiz is missing some vital parts. However, in my reasoning I would use following assumptions:

Car tank have unlimited fuel capacity

It's possible to travel clockwise only

Car starts with 0 gas

Car should finish in the same gas station

Given this assumptions, the task can be easily brute forced with O(n**2) complexity, by trying all gas stations.

If it's required more robust solution, it's possible to transform this quiz to maximum continuous sub-sequence problem with extra constrains, that it should't go below zero. The complexity of this algorithm is O(n) - linear.

For first step, lets transform our initial problem to problem that is solvable by maximum sub-sequence by summing amount of gas at gas station and cost of going to that station.

Second step is to apply maximum sub-sequence algorithm. The algorithm is based on 2 assumptions:

if gas counter went below 0, that is always better to restart from current gas station

otherwise it's better just to fill-in the tank, since it's more than 0 gas here

Applying this algorithm to the circled list of the stations 2 times (2 overlapping sequences), we will get the station that starts sequence which accumulates most of the fuel.

Third step is to verify that goal is reachable with given amount of fuel and given start station, complexity o(n)

ContentLicense: CC BY-SA 3.0


问:
I want to start using TDD. Any tips for a beginner?
I never used an automated test mechanism in any of my projects and I feel I'm missing a lot. I want to improve myself, so I have to start tackling some issues I've been neglecting like this and trying Git instead of being stuck on SVN.

What's a good way to learn TDD? I'll probably be using Eclipse to program in Java. I've heard of JUnit, but I don't know if there's anything else I should consider.

答:
Get familiar with AAA, read about it, read about the issues that come with test driven development ( design for testability vs high cost tools so that the design doesn't matter). Learn Dependency Injection so that removing external dependencies for testing becomes simpler.

Here's a good overview of notes I took while reading The Art of Unit Testing

http://imaginarydevelopment.blogspot.com/2010/01/unit-testing-reference.html

ContentLicense: CC BY-SA 2.5


问:
Is there a language or design pattern that allows the *removal* of object behavior or properties in a class hierarchy?
A well-known shortcoming of traditional class hierarchies is that they are bad when it comes to modeling the real world. As an example, trying to represent animals' species with classes. There are actually several problems when doing that, but one that I never saw a solution to is when a sub-class "loses" a behavior or property that was defined in a super-class, like a penguin not being able to fly (there are probably better examples, but that's the first one that comes to my mind).

On the one hand, you don't want to define, for every property and behavior, some flag that specifies if it is at all present, and check it every time before accessing that behavior or property. You would just like to say that birds can fly, simply and clearly, in the Bird class. But then it would be nice if one could define "exceptions" afterward, without having to use some horrible hacks everywhere. This often happens when a system has been productive for a while. You suddenly find an "exception" that doesn't fit in the original design at all, and you don't want to change a large portion of your code to accommodate it.

So, are there some language or design patterns that can cleanly handle this problem, without requiring major changes to the "super-class", and all the code that uses it? Even if a solution only handles a specific case, several solutions might together form a complete strategy.

After thinking more, I realize I forgot about the Liskov Substitution Principle. That is why you can't do it. Assuming you define "traits/interfaces" for all major "feature groups", you can freely implement traits in different branches of the hierarchy, like the Flying trait could be implemented by Birds, and some special kind of squirrels and fish.

So my question could amount to "How could I un-implement a trait?" If your super-class is a Java Serializable, you have to be one too, even if there is no way for you to serialize your state, for example if you contained a "Socket".

One way to do it is to always define all your traits in pairs from the start: Flying and NotFlying (which would throw UnsupportedOperationException, if not checked against). The Not-trait would not define any new interface, and could be simply checked for. Sounds like a "cheap" solution, in particular if used from the start.

答:
Many good answers with many comments, but they don't all agree, and I can only choose a single one, so I'll summarize here all the views I agree with.

0) Don't assume "static typing" (I did when I asked, because I do Java almost exclusively). Basically, the problem is very dependent on the type of language one uses.

1) One should separate the type-hierarchy from the code-reuse hierarchy in the design and in one's head, even if they mostly overlap. Generally, use classes for reuse, and interfaces for types.

2) The reason why normally Bird IS-A Fly is because most birds can fly, so it's practical from the code-reuse point-of-view, but saying that Bird IS-A Fly is actually wrong since there is at least one exception (Penguin).

3) In both static and dynamic languages, you could just throw an exception. But this should only be used if it is explicitly declared in the "contract" of the class/interface declaring the functionality, otherwise it is a "breach of contract". It also mean that you now have to be prepared to catch the exception everywhere, so you write more code at the call site, and it's ugly code.

4) In some dynamic languages, it is actually possible to "remove/hide" the functionality of a super-class. If checking for the presence of the functionality is how you check for "IS-A" in that language, then this is an adequate and sensible solution. If on the other hand, the "IS-A" operation is something else that still says your object "should" implement the now missing functionality, then your calling code is going to assume that the functionality is present and call it and crash, so it kinds of amount to throwing an exception.

5) The better alternative is to actually separate the Fly trait from the Bird trait. So a flying bird has to explicitly extend/implement both Bird and Fly/Flying. This is probably the cleanest design, as you don't have to "remove" anything. The one disadvantage is now that almost every bird has to implement both Bird and Fly, so you write more code. The way around this is to have an intermediary class FlyingBird, which implements both Bird and Fly, and represents the common case, but this work-around might be of limited use without multiple inheritance.

6) Another alternative that doesn't require multiple inheritance is to use composition instead of inheritances. Each aspect of an animal is modeled by an independent class, and a concrete Bird is a composition of Bird, and possibly Fly or Swim, ... You get full code-reuse, but have to do one or more additional steps to get at the Flying functionality, when you have a reference of a concrete Bird. Also, the language natural "object IS-A Fly" and "object AS-A(cast) Fly" will not work anymore, so you have to invent you own syntax (some dynamical languages might have a way around this). This might make your code more cumbersome.

7) Define your Fly trait such that it offers a clear way out for something that cannot fly. Fly.getNumberOfWings() could return 0. If Fly.fly(direction, currentPotinion) should return the new position after the flight, than Penguin.fly() could just return the currentPosition without changing it. You might end-up with code that technically work, but there are some caveats. Firstly, some code might not have an obvious "do nothing" behavior. Also, if someone calls x.fly(), they would expect it to do something, even if the comment says fly() is allowed to do nothing. Finally, penguin IS-A Flying would still return true, which might get confusing for the programmer.

8) Do as 5), but use composition to get around cases that would require multiple inheritance. This is the option I would prefer for a static language, as 6) seems more cumbersome (and probably require more memory because we have more objects). A dynamic language might make 6) less cumbersome, but I doubt it would get less cumbersome than 5).


问:
Is it bad idea to use flag variable to search MAX element in array?
Over my programming career I formed a habit to introduce a flag variable that indicates that the first  comparison has occured, just like Msft does in its linq Max() extension method implementation

```<code>public static int Max(this IEnumerable<int> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    int num = 0;
    bool flag = false;
    foreach (int num2 in source)
    {
        if (flag)
        {
            if (num2 > num)
            {
                num = num2;
            }
        }
        else
        {
            num = num2;
            flag = true;
        }
    }
    if (!flag)
    {
        throw Error.NoElements();
    }
    return num;
}
</code>```

However I have met some heretics lately, who implement this by just starting with the first element and assigning it to result, and oh no - it turned out that STL and Java authors have preferred the latter method.

Java:

```<code>public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();

    while (i.hasNext()) {
    T next = i.next();
    if (next.compareTo(candidate) > 0)
    candidate = next;
}
return candidate;
}
</code>```

STL:

```<code>template<class _FwdIt> inline
_FwdIt _Max_element(_FwdIt _First, _FwdIt _Last)
{   // find largest element, using operator<
_FwdIt _Found = _First;
if (_First != _Last)
    for (; ++_First != _Last; )
        if (_DEBUG_LT(*_Found, *_First))
            _Found = _First;
return (_Found);
}
</code>```

Are there any preferences between one method or another? Are there any historical reasons for this? Is one method more dangerous than another?

UPDATE: Please note, that the java version is capable of throwing exceptions with the line T candidate = i.next();and it's possible to get the same behavior in C# with the guard clause as it's shown in the second part of @ratchet freak's answer.

答:
Personally I've never developed a pattern to always do one way vs. doing it another way.  For me it always boils to the fact that given everything else constant, more lines of code and more local variables increase the complexity of the code.  Not by much but little by little, we end up with functions that get discussed next to the water cooler.

So I always pick approach which minimizes the use of local variables and use of conditionals whenever possible, given that I can shrink the code without sacrificing any clarity. But clarity would always win over using an extra local variable.

In the example you provided, I would probably code it without using the flag, but in the end it comes down to personal style so I wouldn't say it's wrong one way or the other.


答:
Define a default behavior (mark it as virtual) in the base class and override it as necessay.  That way every bird can "fly".

Even penguins fly, its gliding across the ice at zero altitude!

The behavior of flying can be overridden as necessary.

Another possibility is having a Fly Interface.  Not all birds will implement that interface.

```<code>class eagle : bird, IFly
class penguin : bird
</code>```

Properties cannot be removed, so that's why its important to know what properties are common across all birds.  I think that it more a design issue to make sure common properties are implemented at the base level.

Title: Is there a language or design pattern that allows the *removal* of object behavior or properties in a class hierarchy?

Body:
A well-known shortcoming of traditional class hierarchies is that they are bad when it comes to modeling the real world. As an example, trying to represent animals' species with classes. There are actually several problems when doing that, but one that I never saw a solution to is when a sub-class "loses" a behavior or property that was defined in a super-class, like a penguin not being able to fly (there are probably better examples, but that's the first one that comes to my mind).

On the one hand, you don't want to define, for every property and behavior, some flag that specifies if it is at all present, and check it every time before accessing that behavior or property. You would just like to say that birds can fly, simply and clearly, in the Bird class. But then it would be nice if one could define "exceptions" afterward, without having to use some horrible hacks everywhere. This often happens when a system has been productive for a while. You suddenly find an "exception" that doesn't fit in the original design at all, and you don't want to change a large portion of your code to accommodate it.

So, are there some language or design patterns that can cleanly handle this problem, without requiring major changes to the "super-class", and all the code that uses it? Even if a solution only handles a specific case, several solutions might together form a complete strategy.

After thinking more, I realize I forgot about the Liskov Substitution Principle. That is why you can't do it. Assuming you define "traits/interfaces" for all major "feature groups", you can freely implement traits in different branches of the hierarchy, like the Flying trait could be implemented by Birds, and some special kind of squirrels and fish.

So my question could amount to "How could I un-implement a trait?" If your super-class is a Java Serializable, you have to be one too, even if there is no way for you to serialize your state, for example if you contained a "Socket".

One way to do it is to always define all your traits in pairs from the start: Flying and NotFlying (which would throw UnsupportedOperationException, if not checked against). The Not-trait would not define any new interface, and could be simply checked for. Sounds like a "cheap" solution, in particular if used from the start.

Body:
Define a default behavior (mark it as virtual) in the base class and override it as necessay.  That way every bird can "fly".

Even penguins fly, its gliding across the ice at zero altitude!

The behavior of flying can be overridden as necessary.

Another possibility is having a Fly Interface.  Not all birds will implement that interface.

class eagle : bird, IFly
class penguin : bird

Properties cannot be removed, so that's why its important to know what properties are common across all birds.  I think that it more a design issue to make sure common properties are implemented at the base level.


答:
to be totally radical you can do:

```<code>public static int Max(this IEnumerable<int> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }

    int num = int.MinValue;
    foreach (int num2 in source)
    {
        if (num2 > num)
        {
            num = num2;
        }
    }
    return num;
}
</code>```

by defining the max of a empty set to be int.Minvalue

but it is possible to do the java/stl approach with c#

```<code>public static int Max(this IEnumerable<int> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    if(!source.MoveNext()){
        throw throw Error.NoElements();
    }
    int num = source.Current;
    foreach (int num2 in source)
    {
        if (num2 > num)
        {
            num = num2;
        }
    }
    return num;
}
</code>```

though YMMV whether it's clearer or not

Title: Is it bad idea to use flag variable to search MAX element in array?

Body:
Over my programming career I formed a habit to introduce a flag variable that indicates that the first  comparison has occured, just like Msft does in its linq Max() extension method implementation

```<code>public static int Max(this IEnumerable<int> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    int num = 0;
    bool flag = false;
    foreach (int num2 in source)
    {
        if (flag)
        {
            if (num2 > num)
            {
                num = num2;
            }
        }
        else
        {
            num = num2;
            flag = true;
        }
    }
    if (!flag)
    {
        throw Error.NoElements();
    }
    return num;
}
</code>```

However I have met some heretics lately, who implement this by just starting with the first element and assigning it to result, and oh no - it turned out that STL and Java authors have preferred the latter method.

Java:

```<code>public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();

    while (i.hasNext()) {
    T next = i.next();
    if (next.compareTo(candidate) > 0)
    candidate = next;
}
return candidate;
}
</code>```

STL:

```<code>template<class _FwdIt> inline
_FwdIt _Max_element(_FwdIt _First, _FwdIt _Last)
{   // find largest element, using operator<
_FwdIt _Found = _First;
if (_First != _Last)
    for (; ++_First != _Last; )
        if (_DEBUG_LT(*_Found, *_First))
            _Found = _First;
return (_Found);
}
</code>```

Are there any preferences between one method or another? Are there any historical reasons for this? Is one method more dangerous than another?

UPDATE: Please note, that the java version is capable of throwing exceptions with the line T candidate = i.next();and it's possible to get the same behavior in C# with the guard clause as it's shown in the second part of @ratchet freak's answer.

Body:
to be totally radical you can do:

public static int Max(this IEnumerable<int> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }

    int num = int.MinValue;
    foreach (int num2 in source)
    {
        if (num2 > num)
        {
            num = num2;
        }
    }
    return num;
}

by defining the max of a empty set to be int.Minvalue

but it is possible to do the java/stl approach with c#

public static int Max(this IEnumerable<int> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    if(!source.MoveNext()){
        throw throw Error.NoElements();
    }
    int num = source.Current;
    foreach (int num2 in source)
    {
        if (num2 > num)
        {
            num = num2;
        }
    }
    return num;
}

though YMMV whether it's clearer or not


问:
How is this "interface"-like structure/pattern called?
Let's assume we have an XmlDoc class that contains basic functionality for dealing with an XML data structure and saving/loading data to/from a file. Now we have several subclasses, A, B and C. They all inherit from XmlDoc and add component-specific methods for setting and getting lots of data. They are like "interfaces" but also add an implementation for the signatures.

Finally, we have an ABCDoc class that joins all the "interfaces" via virtual multiple inheritence and adds some ABCDoc-specific stuff, such as using XMLDoc-methods to set an appropriate doc type. We may also have an ADoc class for only saving A data.

How is this pattern called? "Interface" is not really the right word since interfaces usually do not contain an implementation.

Bonus points for C++ code conventions.

答: It's called the "Diamond Problem" or, if it's not a problem for you, you can drop the "Problem" part. The issue is, how do you resolve which inherited method gets called from the derived class? You can override the function calls, but then you are only using that inheritance as an interface. If you are doing that, why not make abstract classes that don't inherit from the "master" class, then compose your new classes using multiple inheritance?</p>


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

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

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

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

static/strong typing and compiler checks to minimize runtime errors

small memory usage, and relative fast runtime

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

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

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

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

答: Matlab has a page on DO 178 compliance. FAA requires DO-178 compliance for avionics software, and private space shots require FAA clearance. Adacore has products for C++, C and Ada; as well as stuff to support DO-178. They have a program for universities, so you might be able to get what you want at a reduced price (or free, maybe).  </p>

Title: Mission critical embedded language


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

答:
I've written a 5-part blog series on doing TDD with C++ and Visual Studio: part 1, part 2, part 3, part 4, part 5.

I'm not sure why you say that you don't make extra projects in C# to do TDD, because that's what I've always done with NUnit and it seems typical of what other people do with NUnit as well.  The reason is simple: always keep test code separate from production code.  For C++ with Visual Studio, this means separate projects just like it does for C# and NUnit.  From what I know of the Java world, this is also common there.

Obviously, everyone has different ideas of what is "bearable" for doing TDD.  I've been practicing the method I outline in my blog post for severeal years and I find it very bearable.  C++ is a compiled language and compiling stuff can be slow when the system under test is highly coupled.  There just isn't any getting away from that without refactoring to a more loosely coupled design.

My "one click action" is "Build Solution".  If that's building too much you can always unload irrelevant projects while you're working and then Build Solution will build only the minimal subset of projects neeeded to be updated as a result of your changes.

Granted, the compile time nature of C++ does make this take a little longer in each cycle of the TDD process than it did with NUnit and C#, but the confidence I get from my well-tested C++ code is worth it.  Otherwise I'm going to be spending lots more time in the debugger.  I would caution to be sparing in your use of gmock as it can add substantially to test compile time.  I've so far mostly gotten away with lightweight "fake" objects and rarely need the full-blown functionality of mocks.  The mocking frameworks for C++ are heavily template based and this can increase compile time significantly, so they should be reserved for where you really need a mock and a fake just won't do.

I have considered creating a Boost.Test unit test project wizard to automate some of the boiler plate nature of creating the test project for production code, but after you've done it a couple times its really not that hard to do manually.

As for solutions with many (150?) projects, there are ways to cope with that as well.  One obvious one is to find groups of related projects and bundle them together and start consuming them/publishing them as a unit.  If you really need to rebuild/touch all 150 projects for small changes you're making during a TDD cycle, then your code is so highly coupled anyway that unit tests aren't likely to make much of a difference.

Looking at the netbeans IDE link, I find the eye candy of having something that parses the test output and shows a little test row in a window with a green or red symbol next to it something that I thought I would miss having come from NUnit, but didn't actually miss.  I found it more useful for the build to simply just fail and then I could double-click in the errors window to place the cursor at the location of the failed assertion.


答:
A couple of things spring to mind;

First of all, get this into the head of everyone working on the project:

Don't assume anything. If you don't know; find out, and verify. Then let someone else verify.

Secondly, the language you choose is largely irrelevant; you can screw up in everything, including Ada. Yes, the protection is there, but so are the means to circumvent it.

If you can work with C++, stick with C++; you want to minimize complexity, and adding an embedded language on top of it doesn't. If you can't, get [good] programmers on the team ASAP and let them do their thing while you do yours. Get/write tight code standards, and stick to them. Avoid anything that might go haywire (as in, e.g. point where it shouldn't, or run out of memory), and try to keep the code as simple as possible. Then test, verify and test some more. Do ruthless code reviews.

Do not optimize unless you have no other option; reliability trumps everything.

Oh, and you probably want/need to read up on DO-178B.

Lastly; if you don't trust it, don't fly it.

Title: Mission critical embedded language

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

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

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

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

static/strong typing and compiler checks to minimize runtime errors

small memory usage, and relative fast runtime

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

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

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

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


问:
How to populate a private container for unit test?
I have a class that defines a private (well, __container to be exact since it is python) container.  I am using the information within said container as part of the logic of what the class does and have the ability to add/delete the elements of said container.

For unit tests, I need to populate this container with some data. That
data depends on the test done and thus putting it all in setUp() would
be impractical and bloated -- plus it could add unwanted side effects.

Since the data is private, I can only add things via the public
interface of the object.  This runs code that need not be run during a
unit test and in some cases is just a copy and paste from another test.

Currently, I am mocking the whole container but somehow it does not feel that elegant a solution.  Due to Python mocking frame work (mock), this requires the container to be public -- so I can use patch.dict().  I would rather keep that data private.

What pattern can one use to still populate the containers without excercising the public method so I have data to test with?

Is there a way to do this with mock's patch.dict() that I missed?

答:
Until recently, I would have just pointed you at plenty of other existing questions that say that you generally shouldn't need access to any private stuff, in order to write unit tests - as the whole point of tests is to test the public (and protected) interface.

For example, in the question how to unit-test private methods in jquery plugins?, there is this answer:

The same applies here as with any other language and testing privates: To test private methods, you should exercise them via the public interface. In other words, by calling your public methods, the private methods get tested in the process because the public methods rely on the privates.

Generally private methods are not tested separately from the public interface - the entire point is that they are implementation details, and tests should generally not know too much about the specifics of the implementation

In your specific case, you say:

Since the data is private, I can only add things via the public interface of the object. This run codes that need not be run during a unit test and in some case is just a copy and paste from another test.

I would be cautious about having any tests that avoided code that normally needs to be run - for fear that your tests would spuriously pass, due to some difference between the test behaviour and the real world.

Having said all that, I recently learned about a really excellent article on writing testsuite called The Way of Testivus. It's a PDF that's only 12 pages long, and a really easy and enjoyable read.

What's relevant here is the section entitled "Sometimes, the test justifies the means" - in the context of violating encapsulation to enable testing. I highly recommend it.

(Another favourite of mine is "An ugly test is better than no test.")

So, in your context, if you still decide you really want a different way to set up data purely for tests, it might be reasonable to add a public setter method, specifically documented as only existing to aid writing of tests.


问:
Is the use of explicit ' == true' comparison always bad?

Possible Duplicate:

  Make a big deal out of == true?

I've been looking at a lot of code samples recently, and I keep noticing the use of...

```<code>if( expression == true )
    // do something...
</code>```

and...

```<code>x = ( expression == true ) ? x : y;
</code>```

I've tended to always use...

```<code>x = ( expression ) ? x : y;
</code>```

and...

```<code>if( expression )
    // do something...
</code>```

Where == true is implicit (and obvious?)

Is this just a habit of mine, and I'm being picky about the explicit use of == true, or is it simply bad practice?

答:
Yes.

I'm going to go ahead and response with a big yes, since there are no other responses yet. But, always open to new data suggesting otherwise.

It's a yes because the expression already evaluates to a boolean. Your explicit testing of that boolean is adding nothing of value to the program. In fact, it increases the surface area for error (typos, future changes, etc).

Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away. -- Antoine de Saint-Exupery


问:
Suggestions for getting an open source electron beam tracking code going
I work in the field of accelerator physics and synchrotron radiation. High energy electrons circulating in large rings of magnets produce x-rays that are used for a variety of different kinds of science.

Running and improving these facilities requires controlling and modelling the electron beam as it circulates in the ring. A code to model this basically requires trackers to follow the electrons through the elements (something called a symplectic integrator), and then the computation of different parameters associated with this motion. The problem with these codes is that every facility has there own (maybe 4-5 different codes, some with multiple versions). In principle the code is not so complex. And as a modelling project, one might think it has some general interest.  Who doesn't want to be able to create a track in space out of magnets and watch the electrons circulate?

There is a Matlab based code to do this called Accelerator Toolbox, but the creator of the code is no longer in the field. I put the code in Sourceforge under the name atcollab. The basic resource is a set of symplectic integrators written in C. These are then compiled into mex code and interfaced via Matlab. It has been useful to put the code on Sourceforge in order to exchange code, but the community of users is quite small and most are too busy to put that much time into collaboration. So in terms of really improving the code, I don't think it has been so successful.

Any piece of this picture could be recreated without that much difficulty, but overall it is a bit complex, and because each lab has their own installation with lots of added-on code and locally developed tools, people find it hard to really work together and share code. Somehow I think we need to involve a wider community in our development, or just use some standard tools. But for that, I suppose it needs to be of some general interest. I think symplectic integrators may have some general interest. And the part about a plug-in architecture to build up the ring ought to fit other patterns. Or the other option is to just accept that this is not a problem of general interest, and work harder within our small community.

Suggestions or anecdotes of analogous experience would be appreciated.

答:
Since you're asking about "suggestions or anecdotes", there is a relevant TED Talk "Open science now!" which also mentions at one moment the sharing of the source code¹.

More generally, there are a few problems with such open source projects:

The scientific community doesn't have yet an open source and code sharing culture compared to the software developers. Since they are unwilling to open their source code to the community for review², they will have less chance to use an open source code daily.

The scientific community is disparate. I mean, when I get a C# source code from CodePlex, I'm pretty sure it will compile fine with my latest Visual Studio, or I'll need to download and install just a couple of add-ins to make it work. At the opposite, a FORTRAN code written by a scientist is written to be highly optimized to run on the workstations in his lab. Chances are, when somebody will try to deploy the same project in another environment with slightly other configuration, it will not compile³, or not run as expected⁴.

For an open source project, larger is the target audience, bigger is the chance to succeed. When publishing a Java application, you are targeting thousands and thousands of developers. C, Java, C#, JavaScript communities are so large that any open source library can be interesting to a few. At the opposite, "accelerator physics and synchrotron radiation", being a very interesting subject, is, well, too difficult to be understood by everyone.

There are well known websites built by or for the communities of developers to share open source code. CodePlex is one example. Since plenty of developers visit those websites, you're pretty sure that if you post your code here, some will see it. At the opposite, there are no famous websites for open source code around "accelerator physics and synchrotron radiation" visited daily by thousands of people. If you want to share your code, you'll have to talk to people in live, and do much more effort in order to be known.

¹ Talking about science wiki projects that failed, Michael Nielsen adds (6:10): "It's not just science wikis either. Inspired by Facebook, many organizations have tried to create social networks for scientists, which will connect scientists to other people with similar interests, so they can share things like data, or code they write [...] If you join one of these sites, you'll discover they are essentially empty".

² Publish your computer code: it is good enough  by Nick Barnes in Nature, October 14th 2010, Vol. 467, 753.

³ Why scientific programming does not compute  by Zeeya Merali in Nature, October 14th 2010, Vol. 467, 777

⁴ I'm not saying that the scientists are writing bad code. It's more that they have different goals. Developers are trained to write compatible, readable and not so optimized code. If I'll start to do small changes to gain a few milliseconds of performance, making the code difficult to understand, my colleagues will ask me if I'm crazy. If a scientist will start to write code for readability and compatibility, and the code will run five days instead of four and a half, there will be problems.


答:
It usually depends on the language (you can find issues around implicit boolean casting of variables in some situations).

If you're using a language like Javascript, you can have unexpected behavior in some cases (watch Douglas Crockford's Google talk - it's in there somewhere, and a good talk to watch anyway).

As there are these strange cases that can be a pain in the arse to track down and fix, I've made a point to always be explicit in my own evaluations (even using === when using a language that supports it).

The trick is to be consistent throughout your code base. When you start tossing special cases in the mix (i.e. "well, if this makes sense to me, then I'll use implicit coercion), someone's bound to get confused somewhere and start misusing it (and/or misunderstanding it). The simplest thing to do is to just stick to one rule throughout - to me, being explicit makes sense.

Title: Is the use of explicit ' == true' comparison always bad?

Body:
Possible Duplicate:

  Make a big deal out of == true?

I've been looking at a lot of code samples recently, and I keep noticing the use of...

```<code>if( expression == true )
    // do something...
</code>```

and...

```<code>x = ( expression == true ) ? x : y;
</code>```

I've tended to always use...

```<code>x = ( expression ) ? x : y;
</code>```

and...

```<code>if( expression )
    // do something...
</code>```

Where == true is implicit (and obvious?)

Is this just a habit of mine, and I'm being picky about the explicit use of == true, or is it simply bad practice?


答:
Yes and no.

First off, to those who say no to the situation with no exceptions, I challenge you to find a situation where a coding convention fits all use cases. This is no different.

Now in a situation where you have a simple expression being evaluated I would not add == true to the code. It is largely self explanatory and I know my coworkers would understand what is happening without much though. In addition you may fall into the debugging joy that is writing var = true rather than var == true.

```<code>while (flag) {
  // iterate
}
</code>```

In a situation where you have a function inside of the comparison, unless the method is of the isSomeCondition() variety, I would add the == true. In my opinion doing so with an ambiguous method makes it more clear what you expect the code to be. After all, it is easy to miss a !.

```<code>while (largeAmbiguousCheckingMethod(input) == true) {

}
</code>```

In this situation you should immediately know what the intent is, assuming a well name method, and you do not run into the problem of accidental assignment.

Body:
Yes and no.

First off, to those who say no to the situation with no exceptions, I challenge you to find a situation where a coding convention fits all use cases. This is no different.

Now in a situation where you have a simple expression being evaluated I would not add == true to the code. It is largely self explanatory and I know my coworkers would understand what is happening without much though. In addition you may fall into the debugging joy that is writing var = true rather than var == true.

while (flag) {
  // iterate
}

In a situation where you have a function inside of the comparison, unless the method is of the isSomeCondition() variety, I would add the == true. In my opinion doing so with an ambiguous method makes it more clear what you expect the code to be. After all, it is easy to miss a !.

while (largeAmbiguousCheckingMethod(input) == true) {

}

In this situation you should immediately know what the intent is, assuming a well name method, and you do not run into the problem of accidental assignment.


答:
Boolean types should not require explicit testing, whereas non-boolean variables should require explicit testing.

The test condition should be thought of as a boolean itself--the result of which is either true or false.  With this premise, explicit testing of a boolean is redundant and implicit testing of non-booleans is a type mis-match.  Furthermore, if the coding style is consistent, an implicit test serves as a good reminder to the reader that the variable is a boolean type.

Code is read far more often than it is written so please be as kind as practical to the next person reading your code.


问:
What methods to you use to promote programmer awareness in an API or custom architecture?
If you are developing your own architecture or heavily use anothers vendors API, how do you promote awareness to the programming staff? For example, say you use Infragistics controls for you C# winforms apps - the controls have boatloads of methods, some quirks, and a best way to use them for your application. How do you promote the knowledge transfer thru your programming staff? Wiki's? Email? Blogs?.</p>

答:
Documentation seems like the most reasonable place to inform your development team regarding implementation and usage of external libraries/API.s

Emails get lost, are not read.
Wikis are for interlinked content.

Blogs are usually for individuals.

Documentation is for communicating evidence of something.

Although I suppose you could have a meeting initially when a project starts to discuss a chosen API/library to make sure 1. everyone is on the same page and 2. no one has a concern with using it that may have been missed.


问:
Getting non-programmers to understand the development process
When starting a project for a company that's not primarily a programming company, one of the expectations is that there's a finished product at the end free of all bugs and does everything needed right away. However, that's rarely the case.

What are some ways to manage expectations and explain to non-programmers how software development differs from other types of product development?

答: IMO, I've found that the transparency offered by agile processes (e.g. Scrum, Crystal, etc.) goes a long ways towards showing how development works to the average stakeholder.</p>


问:
Does HTML5 have a feature that enables a user to add an icon to the Apps screen when "installing", and if not, when are they planning to add it?
I know that the mobile bookmark bubble might sort of work for iOS, but it isn't going in the same section.  And for Android, bookmarking is really not going to cut it for a mobile HTML5 application install since users just don't think to go to their bookmarks and that bookmark process takes two or three steps.

To me this issue of getting the application (bookmark) installed pretty much makes the rest of the HTML 5 features aimed at mobile HTML much less useful.  I can't realistically expect users to prefer the bookmark install and launch process over regular apps, so I can realistically expect them to ignore my mobile HTML5 application and use a native app.

The groups behind mobile HTML 5 features do seem to be pushing for HTML 5 apps adoption with things like Application Cache etc.  To me it seems obvious that the bookmark bubble is not going to cut it.  Someone please tell me they have addressed this or at least are working on it?

答: You don't make HTML5 itself worry about it -- it isn't a concern for the protocol. In 2011, you launch your HTML5 web app by making a small native app that can perhaps push some alerts, provide contact us info and, last but not least, launch your HTML5 app. </p>


问:
Massive vehicular network simulator
I am interested in making a vehicular network simulator (vehicular network as in vehicles can be equipped with radios and when they come in range they can talk with each other). I want to be able to scale to 1000s of nodes if not more. I am quite frankly torn on how to do, or even which language to use or whether I should instead be using some other piece of software/code.

I know that this should depend on a lot of design decisions that I may have, but it would be great if somebody can point me towards the right direction. I was planning to use a multi-threaded architecture, but not sure whether it will add to the complication or make it easier. Also if I go for a multi-threaded architecture, do you think that the Go language will be a good choice?

I have a few years of experience in Java, but haven't done any big project, and essentially no experience in Go.

答:
Back around 1980, I took a seminar class in discrete-event simulation from Nick Lawrence, who used to be THE discrete-event simulation wizard at Texas Instruments.  He had saved them many millions of dollars, at a time when a million dollars was still real money.

Nick hammered us on two things, over and over and over again.

The first was purpose.  What do you want to know?  Why are you doing this simulation?  What do you hope to learn, what question(s) do you want answered?  If your simulation is not set up to answer those questions, or if it is hardwired to answer them a certain way, you are at best fooling yourself, and you may be harming yourself or your customers, very badly.

The second was validation.  How do you show that your simulation is in fact accurately simulating what you want to simulate?  If your sim is not quite correct, you WILL get wrong answers.

The classic example of validation failure is the TTAPS "Nuclear Winter" study.  The sim designers validated their sim against Martian data, forgetting that Earth, unlike Mars, had oceans, and shorelines, and lake-effect snow.  After they'd published, someone re-did the sim with those effects figured in, and discovered that lake-effect snow scavenged the dust out of the atmosphere in about one year.  (Something similar happened in 1800-And-Froze-To-Death, The Year With No Summer.)

What I'm driving at is this:  Until you can say what you want to learn, and how you plan to validate your sim, choice of programming language is NOT what you should be thinking about.

There's a third point that should be raised, that of scalability.  Until you can simulate your system with a handful of nodes, CORRECTLY, and get the answers you need on the small model, there's no point in trying to simulate thousands of nodes.

Title: Massive vehicular network simulator


答:
There is really no substitute for just grabbing a test harness (like NUnit), reading some of the literature and then getting your hands dirty.

As James T. Kirk once said, "We learn by doing."

Title: I want to start using TDD. Any tips for a beginner?

Body:
I never used an automated test mechanism in any of my projects and I feel I'm missing a lot. I want to improve myself, so I have to start tackling some issues I've been neglecting like this and trying Git instead of being stuck on SVN.

What's a good way to learn TDD? I'll probably be using Eclipse to program in Java. I've heard of JUnit, but I don't know if there's anything else I should consider.


问:
Advantages of object-oriented programming
Note: this question is an edited excerpt from a blog posting I wrote a few months ago.  After placing a link to the blog in a comment on Programmers.SE someone requested that I post a question here so that they could answer it.  This posting is my most popular, as people seem to type "I don't get object-oriented programming" into Google a lot.  Feel free to answer here, or in a comment at Wordpress.

What is object-oriented programming?
  No one has given me a satisfactory
  answer.  I feel like you will not get
  a good definition from someone who
  goes around saying “object” and
  “object-oriented” with his nose in the
  air. Nor will you get a good
  definition from someone who has done
  nothing but object-oriented
  programming. No one who understands
  both procedural and object-oriented
  programming has ever given me a
  consistent idea of what an
  object-oriented program actually does.

Can someone please give me their ideas of the advantages of object-oriented programming?

答:
Since you understand structs, and you understand function pointers, and you understand structs with function pointers, from your perspective I would define object oriented programming as simply "programming, with heavy use of structs that have function pointers".  It's still programming in the traditional sense -- it's all data, and code that acts upon the data. The difference is simply how all of that information is defined and how you approach defining it.

Perhaps an over simplification is that traditional programming is "code, with some data structures", and object oriented programming is "data structures, with some code". Both still have data structures, and both still have code. Object oriented programming, then, is nothing more than the act of defining types of data up front, and enforcing contracts for how they communicate via sets of functions.

As you have observed, there is a huge class of applications for which this is not such a great way to implement a solution. You seem to live in a world predominately made up of such applications. In your blog post you mention looking at implementations of the "99 bottles of beer" problem (your "favorite programming showcase"). 99 bottles of beer is certainly part of that category. Trying to understand object oriented programming by looking at implementations of 99 bottles of beer is a bit like trying to understand high rise architecture by looking at a treehouse. Even a very well built tree house can only teach you so much.

TL;DR: OO programming is like traditional programming, except you focus more of your effort in defining the data structures up front, and you have those data structures communicate with each other via function pointers.


问:
What's the benefit of object-oriented programming over procedural programming?
I'm trying to understand the difference between procedural languages like C and object-oriented languages like C++. I've never used C++, but I've been discussing with my friends on how to differentiate the two.

I've been told C++ has object-oriented concepts as well as public and private modes for definition of variables: things C does not have. I've never had to use these for while developing programs in Visual Basic.NET: what are the benefits of these?

I've also been told that if a variable is public, it can be accessed anywhere, but it's not clear how that's different from a global variable in a language like C. It's also not clear how a private variable differs from a local variable.

Another thing I've heard is that, for security reasons, if a function needs to be accessed it should be inherited first. The use-case is that an administrator should only have as much rights as they need and not everything, but it seems a conditional would work as well:

```<code>if ( login == "admin") {
    // invoke the function
}
</code>```

Why is this not ideal?

Given that there seems to be a procedural way to do everything object-oriented, why should I care about object-oriented programming?

答:
The simple one sentence difference is that C++ is C with Classes.(though it is much more now) I don't why you don't want to learn the differences between two by reading a great article on C++ at Wikipedia.....This article will help you a great deal :- C++ (Wikipedia)

Also googling on the issue will help. Asking random persons to explain this might be tricky. IMHO, one understands better by reading than asking someone


答:
Hmm...maybe it's best to back up and try to give some idea of the basic intent of object oriented programming. Much of the intent of object oriented programming is to allow the creation of abstract data types. For a really simple example with which you're undoubtedly familiar, consider a string. A string will typically have a buffer to hold the content of the string, some functions that can operate on the string (search in it, access parts of it, create substrings, etc.) It will also (at least typically) have something to keep track of the (current) length of the string, and (probably) the size of the buffer so if (for example) you increase the string's size from 1 to 1000000, it'll know when it needs more memory to hold the larger content.

Those variables (the buffer, current length and the buffer size) are private to the string itself, but they're not local to a particular function. Each string has contents of some particular length, so we need to track that content/length for that string. Conversely, the same function (e.g., to extract a substring) might operate on many different strings at different times, so that data can't be local to the individual function.

As such, we end up with some data that's private to the string, so it's only (directly) accessible to string functions. The outside world can get the length of the string using a string function, but doesn't need to know anything about the internals of the string to get it. Likewise, it might modify the string -- but again, it does so via the string functions, and only they directly modify those variables local to the string object.

As far as security goes, I'd note that while this is reasonable as an analogy, it's not how things really work. In particular, access in C++ is specifically not intended to meet the same kind of requirements as access in an operating system. An operating system is supposed to enforce the restrictions so (for example) a normal user can't do things reserved for an administrator. By contrast, access control in C++ is only intended to prevent accidents. By design, anybody who wants to can bypass them quite easily. They're on the same order as marking a file read-only so you don't accidentally delete it. If you decide to delete the file, it's trivial to change it from read-only to read-write; all setting it to read-only does is make you at least think about it a second and decide to delete the file so it won't get deleted by accident just from hitting the wrong key at the wrong time.

Title: What's the benefit of object-oriented programming over procedural programming?

Body:
I'm trying to understand the difference between procedural languages like C and object-oriented languages like C++. I've never used C++, but I've been discussing with my friends on how to differentiate the two.

I've been told C++ has object-oriented concepts as well as public and private modes for definition of variables: things C does not have. I've never had to use these for while developing programs in Visual Basic.NET: what are the benefits of these?

I've also been told that if a variable is public, it can be accessed anywhere, but it's not clear how that's different from a global variable in a language like C. It's also not clear how a private variable differs from a local variable.

Another thing I've heard is that, for security reasons, if a function needs to be accessed it should be inherited first. The use-case is that an administrator should only have as much rights as they need and not everything, but it seems a conditional would work as well:

```<code>if ( login == "admin") {
    // invoke the function
}
</code>```

Why is this not ideal?

Given that there seems to be a procedural way to do everything object-oriented, why should I care about object-oriented programming?


答:
OOP versus C isn't really about any of the things you've discussed.  It's primarily about packaging code into areas that won't/can't unintentionally (or sometimes even intentionally) affect each other.

C lets you basically run any function from anywhere.  OOP prevents that by grouping methods into classes and only allowing you to use the methods by referencing the class containing them.  So, one potentially big advantage of OOP is that you're far more likely to have a better code arrangement without lots of experience to tell you that you should.


问:
Dealing with profanity in source code
How do people deal with profanity in source code and VCS comments. Keep or delete?

What about soft-expletives like WTF or Arrgggh?

Is unprofessional, offensive or something to be shrugged off?

答: If you see profanity in open source software and want to get rid of it, prepare for the possibility of push-back. Don't just write a three line bug report, and expect it to get accepted. Write a mini-essay explaining why profanity and discriminatory language is bad, and pre-empt the rebuttals.</p>

Title: Dealing with profanity in source code


问:
How does PHP5 fare with earlier versions of the language
I would like to learn PHP for web development but have been drawn back because of comments like the following*:

PHP is good but generates spaghetti code

PHP is nice but Python is marriage material

PHP lacks stuff that you get in other languages like C# or Java

But for PHP5 I have seen some promising comments. So, my question is: How does PHP5 fare with earlier versions of the language and is it good enough now to learn for web development.

* Comments are just for reference not to incite a flame war. No comparison of PHP with other languages is asked for here. Please comment just on PHP5 and how it compares with earlier versions.

答:
php5 is a much improved version of php4.

Most but not all php4 code works in php5.

What really changed was the much improved Object Model, which fixed a lot of limitations and quirks inherent in the previous OO implementation, but, which is largely incompatible with preceding versions.

Docs here

The other comments have some validity but are not a "no go"

"PHP is good but generates spaghetti code" -- you can generate all sorts of pasta in any language, but, php, does nothing to discourage the inexperienced coder writing a rats nest of unstructured code. Conversly you can write nice code in any language, skilled programmers have no problem writing clean well structured php.

"PHP is nice but Python is marriage material" -- Its a nice language but there are several diverse web frameworks all of which have extremely good points, but, none of which has really taken off, which is all fine, but any Python/framework of your choice combination will always be a niche skill.

"PHP lags stuff that you get in other languages like C# or JAVA" -- php has the most diverse and well implemented library support of any language except perl. There are a few blank spots like statistical analysis, and, vector processing. But generally if you want to do something a quick search of PEAR will locate a library which does it. The language itself is simpler then C# or Java -- but the simplicity of the basic syntax plus "Duck Typing" means you can do anything in php you can do in Java in a more readable and elegant way.


问:
What's wrong with circular references?
I was involved in a programming discussion today where I made some statements that basically assumed axiomatically that circular references (between modules, classes, whatever) are generally bad.  Once I got through with my pitch, my coworker asked, "what's wrong with circular references?"

I've got strong feelings on this, but it's hard for me to verbalize concisely and concretely.  Any explanation that I may come up with tends to rely on other items that I too consider axioms ("can't use in isolation, so can't test", "unknown/undefined behavior as state mutates in the participating objects", etc.), but I'd love to hear a concise reason for why circular references are bad that don't take the kinds of leaps of faith that my own brain does, having spent many hours over the years untangling them to understand, fix, and extend various bits of code.

Edit: I am not asking about homogenous circular references, like those in a doubly-linked list or pointer-to-parent.  This question is really asking about "larger scope" circular references, like libA calling libB which calls back to libA.  Substitute 'module' for 'lib' if you like.  Thanks for all of the answers so far!

答: In database terms, circular references with proper PK/FK relationships make it impossible to insert or delete data. If you can't delete from table a unless the record is gone from table b and you can't delete from table b unless the record is gone from table A, you can't delete. Same with inserts. this is why many databases do not allow you to set up cascading updates or deletes if there is a circular reference because at some point, it becomes not possible. Yes you can set up these kind of relationships with out the PK/Fk being formally declared but then you will (100% of the time in my experience) have data integrity problems. That's just bad design. </p>

Title: What's wrong with circular references?


答:
PHP has been "good enough" for web development for a long time. As with any programming language, the quality of the code hinges on the skills of the developer writing it.

A common criticism of PHP is that its flexibility makes it easy for inexperienced developers to write bad or "spaghetti" code. This is largely because it tries to simultaneously embrace a number of paradigms that occasionally conflict, are poorly implemented, or do not mesh well.

Server-side scripting (PHP) juxtaposed with client-side code (HTML + Javascript) without modularity is common, almost encouraged, to the detriment of clarity & readability.

It's commonly written in an imperative style, but provides mechanisms for object-orientation. This easily results in mixed styles and can often lead to bad design.

Object-oriented design was (in my opinion) poorly supported in PHP4. This is one area that PHP5 has significantly improved upon (e.g. with access modifiers, abstract classes, improved scope resolution.)

PHP's dynamic typing enables run-time errors that could be eliminated with static type-checking. This is inherent to the design of all PHP versions and will not be changing any time soon; the burden of validating object types is left to the programmer.

The changes in PHP5's OOP model do a lot to encourage good design moving forward, but do not add any disincentives to discourage the bad practices mentioned above.

Body:
I would like to learn PHP for web development but have been drawn back because of comments like the following*:

PHP is good but generates spaghetti code

PHP is nice but Python is marriage material

PHP lacks stuff that you get in other languages like C# or Java

But for PHP5 I have seen some promising comments. So, my question is: How does PHP5 fare with earlier versions of the language and is it good enough now to learn for web development.

* Comments are just for reference not to incite a flame war. No comparison of PHP with other languages is asked for here. Please comment just on PHP5 and how it compares with earlier versions.


答: Your question seems more about the purpose of OOP rather than the difference. The concept in your post is Encapsulation; and encapsulation exists to support CHANGE. When other classes are accessing your internals it becomes difficult to modify them without breaking them. In OOP you provide an interface (public members) through which you allow other classes to interact with yours, and you hide your internals so that they can safely be changed.</p>


答:
No matter where I read private variables cannot be accessed whereas
  public variables can be then why not make public as global and private
  as local whats the difference? whats the real use of public and
  private ? please dont say it can be used by everyone, I suppose why
  not we use some conditions and make the calls ?

I hope you don't ever want more than one string in your application. I also hope that your local variables persist between function calls. These things might be the same in terms of accessibility but in terms of lifetime and other usage? They're absolutely not the same.


问:
Why do we study Java at university?
Java is often found in academia. What is the reason behind that? </p>

答:
I feel compelled to add to the answers here as I don't really see any of these answers actually covering my perspective.

I am a hobbyist programmer. I was well ahead of the curve when it came to 'computers' and 'programming'. I completed my undergrad - Bachelors - in 2007 and Masters about two years later - 2009. I have worked with a plethora of languages including Assembly, QuickBASIC, C, C++, Java, PHP, Perl, Python, BASH Scripts, Javascript, COBOL etc.

IMHO, the language that is used to teach programming to students is an indicator of the times that we currently are living in. For example, during 1980s, Assembly was the low-level language while C was considered to be a high level language.

During 1990s, C++, Java, Perl and such languages gained importance primarily because much higher level than C and embodied rapid development principles. So they kinda stopped teaching Assembly to the CS students and taught C as a way of expressing algorithms. Slowly that has changed over the last decade where C is considered too low-level language to capture the essence of algorithms effectively and without too much of 'systems' know-how. This is actually extremely important as the focus of a CS curriculum ought to be more 'theoretical' than practical and every time someone wants to write an algorithm, if he/she gets bogged down with memory allocations and pointer arithmetic then you'll not get anywhere.

Even today if you're in a Masters CS programme, you would have to complete certain 'Systems' requirements (atleast in the US and this should not be very different for US universities) which needs students to be able to program systems level applications and in certain cases as deep as kernel level hacking to actually pass the requirements. So, although C is not the defacto language being taught in schools, it is relevant if you'd like to specialize in say Systems or High Performance Computing or such niches.

I would also like to mention another point is the C requires a lot of discipline to get things right while languages such as Java are a little relaxed about such constraints. This makes it easier to conduct courses without requiring the RA/TAs to launch GDB to debug a student's program :)

Title: Why do we study Java at university?


答:
When discussing languages, these two Stroustrup quotes always pop in mind:

Anybody who comes to you and says he has a perfect language is either naive or a salesman.

and

There are only two kinds of languages: the ones people complain about and the ones nobody uses.

Now to the question at hand. Most of the hate is mostly directed at PHP4. PHP5 was first released in July 2004 (beta a year earlier) and the last version of PHP4 is 4.4.9 released on August 2008. There is no valid reason to use PHP4 anymore, unless of course you maintain some legacy app. PHP4 is no longer supported by the PHP group, and we all hope it fades away soon.

The gap between the two versions is bigger than it usually is between two major releases, as the engine behind the interpreter was rewritten from scratch, and included a new object model. The release of PHP5 roughly coincided with the release of MySQL5, a major overhaul of MySQL. PHP is usually coupled with MySQL and the fifth version of both addressed several issues and brought them up to speed with the competition. MySQL is also subject to FUD comments, but, well, it's the database behind Google's AdWords.

PHP 5.3 was a major release in everything but name. A lot of features that where intended for PHP6 found their way in 5.3 and for every 5.2 developer out there I'd strongly advise to migrate to 5.3+ sooner than later. The current release, 5.4, includes some awesome features (amongst others):

Namespaces,

Late static binding,

Jump labels (limited goto),

Native closures,

Nested exceptions,

Traits

Now for your specific comments:

PHP is good but generates spaghetti code

That's absolutely not true. No language generates any kind of code, it's always up to the developer to screw up, spaghetti code is possible in every language out there. What is true though is that PHP has a very low entry barrier compared to other popular languages, hence it's a lot easier for inexperienced developers to write bad (but working) code. But that's a side effect of every easy to learn language.

Furthermore PHP does not enforce any particular style or paradigm, and it's always up to you to decide what to do. I've always thought of this as a good thing, while others see it as a valid point of criticism. You'll have to decide for yourself.

PHP is nice but Python is marriage material

PHP lacks stuff that you get in other languages like C# or JAVA

Yes it does. And general-purpose language X lack a lot of stuff that you get in PHP. Like being portable across operating systems AND across http servers, and support for every imaginable third party library that would be useful in a web development environment. You have to understand that PHP doesn't lack of anything important, if it did it would have died a long time ago. The comparison between general-purpose language X and other multi-purpose languages to PHP is a fallacy, apples and oranges. Although PHP offers some facilities to support the idea that it's general-purpose, it's not, it's a web language.

You have to keep in mind that PHP's evolutionary path is quite different from general-purpose language X: PHP grew and evolved, it wasn't designed. Every time a feature is added to the language is out of actual necessity, not in accordance to some imaginary ideal of what  a language should be. Languages are first and foremost tools, and PHP is perfect as such.

I don't have anything against general-purpose language X, I'm all for choosing the right tool for the job. I've always mixed and matched, and I'm coding in Java and Python too, sometimes in parallel with PHP. But PHP is the only one I'd ever consider marrying. :)

If you're considering starting with PHP, you should of course start with the latest stable version, as you would in any other language.

Title: How does PHP5 fare with earlier versions of the language


问:
How can I make an app using mobile's camera to detect words?
I am trying to make an app that will capture the video from the mobile's camera and detect in real time all the text that will be captured. I would like to make it in C# (for e.g. Windows Mobile) but I can also try to do it in Java (for e.g. Android).
Can anyone help me how can I start with it? </p>

答:
Start by breaking the problem down into smaller, more manageable parts:

Choose a platform. You mention using both C# for Windows Mobile and Java for Android. It's great to be open-minded, but pick one or the other for now. You'll have a hard time making much progress until you do.

Procure a development environment and test device suitable for developing on your chosen platform. Learn to use it. You don't want to be trying to learn the ins and outs of mobile development while also implementing your first computer vision project.

Build an app that can capture and process images from the camera. Don't worry about looking for words yet -- just get individual frames and do something very simple with them. You could display the average red, green, and blue values for the image, for example, or replace all the green pixels with pixels from a chosen image.

Learn something about computer vision and optical character recognition. I'm not up on how OCR is done these days, but I'd expect that some steps in the process might involve filtering the image to simplify it, doing some edge detection, and trying to match features of the resulting shapes to the set of known shapes that are the characters you're trying to detect.

Write some software that uses the knowledge you gained in step 4 to detect characters in sample images. Ideally, it should work for samples where the characters are distorted and the images include the kind of noise you'd get from a camera on a mobile device. You don't necessarily have to make this software a mobile application -- at this point you're just learning the techniques you'll need for your mobile app.

Incorporate the image processing software from step 5 into the app from step 3.

Note that steps 4 and 5 can (probably should) take place before steps 1-3, depending on your priorities.


答:
All answers so far have focused on the topic of your question as stated, which is "what is the difference between c and c++". In reality, it sounds like you know what difference is, you just don't understand why you would need that difference. So then, other answers attempted to explain OO and encapsulation.

I wanted to chime in with yet another answer, because based on the details of your question, I believe you need to take several steps back.

You don't understand the purpose of C++ or OO, because to you, it seems that your application simply needs to store data. This data is stored in variables.
"Why would I want to make a variable inaccessible? Now I can't access it anymore! By making everything public, or better yet global, I can read data from anywhere and there are no problems." - And you are right, based on the scale of the projects you are currently writing, there are probably not that many problems (or there are, but you just haven't become aware of them yet).

I think the fundamental question you really need to have answered is: "Why would I ever want to hide data? If I do that, I can't work with it!"
And this is why:

Let's say you start a new project, you open your text editor and you start writing functions. Every time you need to store something (to remember it for later), you create a variable. To make things simpler, you make your variables global.
Your first version of your app runs great. Now you start adding more features. You have more functions, certain data you stored from before needs to be read from your new code. Other variables need to be modified. You keep writing more functions.
What you may have noticed (or, if not, you absolutely will notice in the future) is, as your code gets bigger, it takes you longer and longer to add the next feature. And as your code gets bigger, it becomes harder and harder to add features without breaking something that used to work.
Why?
Because you need to remember what all your global variables are storing and you need to remember where all of them are being modified. And you need to remember which function is okay to call in what exact order and if you call them in a different order, you might get errors because your global variables aren't quite valid yet.
Have you ever run into this?

How big are your typical projects (lines of code)?
Now imaging a project 5000 to 50000 times as big as yours. Also, there are multiple people working in it. How can everyone on the team remember (or even be aware of) what all those variables are doing?

What I described above is an example of perfectly coupled code. And since the dawn of time (assuming time started Jan 1, 1970), human kind has been looking for ways to avoid these problems. The way you avoid them is by splitting up your code into systems, subsystems and components and limiting how many functions have access to any piece of data.
If I have 5 integers and a string that represent some kind of state, would it be easier for me to work with this state if only 5 functions set/get the values? or if 100 functions set/get these same values?
Even without OO languages (i.e. C), people have been working hard on isolating data from other data and creating clean separation boundaries between different parts of the code. When the project gets to a certain size, ease of programming becomes not, "can I access variable X from function Y", but "how do I make sure ONLY functions A, B, C and no one else is touching variable X".

This is why OO concepts have been introduced and this is why they are so powerful. They allow you to hide your data from yourself and you want to do it on purpose, because the less code that sees that data, the less chance there is, that when you add the next feature, you will break something. This is the main purpose for the concepts of encapsulation and OO programming. They allow you to break our systems/subsystems down into even more granular boxes, to a point where, no matter how big the overall project is, a given set of variables may only be accessed by 50-200 lines of code and that's it! There's obviously much more to OO programming, but, in essence, this is why C++ gives you options of declaring data/functions as private, protected or public.

The second greatest idea in OO is the concept of abstraction layers. Although procedural languages can also have abstractions, in C, a programmer must make a conscious effort to create such layers, but in C++, when you declare a class, you automatically create an abstraction layer (it's still up to you whether or not this abstraction will add or remove value). You should read/research more about abstraction layers and if you have more questions, I'm sure this forum will be more than happy to answer those as well.


问:
Does syntax really matter in a programming language?
One of my professors says "the syntax is the UI of a programming language", languages like Ruby have great readability and it's growing, but we see a lot of programmers productive with C\C++, so as programmers does it really matter that the syntax should be acceptable?

I would love to know your opinion on that.

Disclaimer: I'm not trying to start an argument. I thought this is a good topic of discussion.

Update: This turns out to be a good topic. I'm glad you are all participating in it.

答: Syntax definitely matters.  It's terrifically valuable if the language syntax is flexible enough to allow you to create a convenient and readable Domain-Specific Language for your application.  If you doubt this, just imagine doing algebra problems in prosaic Latin, as it was done before the 18th century, or imagine doing calculus without the now familiar Leibniz notation.  Sure, a calculus text is unreadable to a novice, but with practice we can use calculus and the Leibniz notation to quickly solve a class of problems that required pages of mathematics with classical methods.  Programming is just another bit of mathematics.  A convenient notation, close to the problem domain, can make an enormous difference in productivity.</p>


问:
Am I programming too slow?
I've only been a year in the industry and I've had some problems making estimates for specific tasks. Before you close this, yes, I've already read this: How to respond when you are asked for an estimate? and that's about the same problem I'm having. But I'm looking for a more specific gauge of experiences, something quantifiable or probably other programmer's average performances which I should aim for and base my estimates.  The answers range from weeks, and I was looking more for an answer on the level of a task assigned for a day or so. (Note that this doesn't include submitting for QA or documentations, just the actual development time from writing tests if I used TDD, to making the page, before having it submitted to testing)

My current rate right now is as follows (on ASP.NET webforms):

Right now, I'm able to develop a simple data entry page with a grid listing (no complex logic, just Creating and Reading) on an already built architecture, given one full day's (8 hours) time.

Adding complex functionality, and Update and Delete pages add another full day to the task.

If I have to start the page from scratch (no solution, no existing website) it takes me another full day.

(Not always) but if I encounter something new or haven't done yet it takes me another full day.

Whenever I make an estimate that's longer than the expected I feel that others think that I'm lagging a lot behind everyone else. I'm just concerned as there have been expectations that when it's just one page it should take me no more than a full day. Yes, there definitely is more room for improvement.  There always is. I have a lot to learn. But I would like to know if my current rate is way too slow, just average, or average for someone no longer than a year in the industry.

答:
Lucky you, if you've managed 1 year as a green programmer. I was moved to another unit after just 9 months (of which 3 months was actually programming), for not being productive enough. And I was learning more and more each day, enjoying the process and delivering things at a steady pace. It was the first time I had been working in corporate programming at all, ah well...

Perhaps it would just be better to do the dirtiest, least reliable code with zero testing that barely stays together with bubblegum when doing the task, so the managers will get enough "producitivity" for their benchmarks.

Title: Am I programming too slow?


问:
Framework for developing front-end with back-end as REST
Currently I'm developing the back-end of a PHP application using Recess Framework. I'm almost done and I now need to do the front-end. I have many alternatives and I prefer a CMS. The alternatives in my knowledge are Drupal or Wordpress. The problem is that I've never used Drupal and Wordpress(or any better). Thus I don't which one to choose to develop the app to interact with the REST interface.Can you help me in choosing the best CMS for interacting with the REST interface</p>

答:
A typical CMS has tightly coupled back end and front end code (unfortunately). Tightly coupled means that it would be a complete waste of time to try and separate the two.

What you can do is:

Choose a CMS

Disallow access to the CMS backend (that's the easy part)

Modify your back end code to work with the CMS's database

The hard part is the database. Every CMS is built to work with a very specific database structure and your back end will have to adopt that structure if you want to glue it with the CMS front end. In this scenario there is no real benefit in choosing Wordpress over Drupal (or vice versa or any other CMS, like Joomla), simply because the challenges of the scenario have nothing to do with the CMS itself. Whichever one you choose, you'll have to either:

Modify your back end code to work with the database, or

Modify the CMS front end to get its data from your RESTful services (which will probably be insane - you'd have to modify all code that interacts with the database)

If your website is a typical website, and all your needs are covered by the CMS backend (and/or some plugins) then the scenario you're proposing doesn't make any sense. You should just stick with the CMS.

If your needs exceed what the CMS can offer you, and you've made sure that there isn't a plugin out there that does what you want, then the sane choice to still be able to use the CMS, would be to convert your code into a plugin for the CMS of your choice. Or you could just code the front end from scratch as you did with the back end.

I won't go into the which CMS question, since none actually makes sense. I'd advice you to evaluate all three major CMS for PHP, Wordpress, Joomla and Drupal and decide for yourself. CMSes are extremely easy to work with, and relatively easy to code for. I strongly believe that every PHP developer should be familiar if not fluent in all three major CMSes (plus a few more), as to always be able to choose the right one for the job at hand.

Kudos for choosing Recess, it's a great framework, better built than a lot of more popular frameworks.


答:
Whenever I make an estimate that's longer than the expected I feel
  that others think that I'm lagging a lot behind everyone else.

This is all to common, if no-one will every give a longer estimate when looking at a problem in detail, then all estimate will tend to be too short.

Title: Am I programming too slow?

Body:
I've only been a year in the industry and I've had some problems making estimates for specific tasks. Before you close this, yes, I've already read this: How to respond when you are asked for an estimate? and that's about the same problem I'm having. But I'm looking for a more specific gauge of experiences, something quantifiable or probably other programmer's average performances which I should aim for and base my estimates.  The answers range from weeks, and I was looking more for an answer on the level of a task assigned for a day or so. (Note that this doesn't include submitting for QA or documentations, just the actual development time from writing tests if I used TDD, to making the page, before having it submitted to testing)

My current rate right now is as follows (on ASP.NET webforms):

Right now, I'm able to develop a simple data entry page with a grid listing (no complex logic, just Creating and Reading) on an already built architecture, given one full day's (8 hours) time.

Adding complex functionality, and Update and Delete pages add another full day to the task.

If I have to start the page from scratch (no solution, no existing website) it takes me another full day.

(Not always) but if I encounter something new or haven't done yet it takes me another full day.

Whenever I make an estimate that's longer than the expected I feel that others think that I'm lagging a lot behind everyone else. I'm just concerned as there have been expectations that when it's just one page it should take me no more than a full day. Yes, there definitely is more room for improvement.  There always is. I have a lot to learn. But I would like to know if my current rate is way too slow, just average, or average for someone no longer than a year in the industry.


问:
Design review for application facing memory issues
I apologise in advance for the length of this post, but I want to paint an accurate picture of the problems my app is facing and then pose some questions below;

I am trying to address some self inflicted design pain that is now leading to my application crashing due to out of memory errors.

An abridged description of the problem domain is as follows;

The application takes in a “dataset” that consists of numerous text files containing related data

An individual text file within the dataset usually contains approx 20 “headers” that contain metadata about the data it contains. It also contains a large tab delimited section containing data that is related to data in one of the other text files contained within the dataset. The number of columns per file is very variable from 2 to 256+ columns.

The original application was written to allow users to load a dataset, map certain columns of each of the files which basically indicating key information on the files to show how they are related as well as identify a few expected column names. Once this is done, a validation process takes place to enforce various rules and ensure that all the relationships between the files are valid. Once that is done, the data is imported into a SQL Server database. The database design is an EAV (Entity-Attribute-Value) model used to cater for the variable columns per file. I know EAV has its detractors, but in this case, I feel it was a reasonable choice given the disparate data and variable number of columns submitted in each dataset.

The memory problem

Given the fact the combined size of all text files was at most about 5 megs, and in an effort to reduce the database transaction time, it was decided to read ALL the data from files into memory and then perform the following;

perform all the validation whilst the data was in memory

relate it using an object model

Start DB transaction and write the key columns row by row, noting the Id of the written row (all tables in the database utilise identity columns), then the Id of the newly written row is applied to all related data

Once all related data had been updated with the key information to which it relates, these records are written using SqlBulkCopy. Due to our EAV model, we essentially have; x columns by y rows to write, where x can by 256+ and rows are often into the tens of thousands.

Once all the data is written without error (can take several minutes for large datasets), Commit the transaction.

The problem now comes from the fact we are now receiving individual files containing over 30 megs of data. In a dataset, we can receive any number of files. We’ve started seen datasets of around 100 megs coming in and I expect it is only going to get bigger from here on in. With files of this size, data can’t even be read into memory without the app falling over, let alone be validated and imported. I anticipate having to modify large chunks of the code to allow validation to occur by parsing files line by line and am not exactly decided on how to handle the import and transactions.

Potential improvements

I’ve wondered about using GUIDs to relate the data rather than relying on identity fields. This would allow data to be related prior to writing to the database.  This would certainly increase the storage required though. Especially in an EAV design. Would you think this is a reasonable thing to try, or do I simply persist with identity fields (natural keys can’t be trusted to be unique across all submitters).

Use of staging tables to get data into the database and only performing the transaction to copy data from staging area to actual destination tables.

Questions

For systems like this that import large quantities of data, how to you go about keeping transactions small. I’ve kept them as small as possible in the current design, but they are still active for several minutes and write hundreds of thousands of records in one transaction. Is there a better solution?

The tab delimited data section is read into a DataTable to be viewed in a grid. I don’t need the full functionality of a DataTable, so I suspect it is overkill. Is there anyway to turn off various features of DataTables to make them more lightweight?

Are there any other obvious things you would do in this situation to minimise the memory footprint of  the application described above?

Thanks for your kind attention.

答:
EAV is nearly always a mistake (perhaps not in your case but ....).

The data in each column must have some meaning (probably contained in the header meta data!).

Perhaps you could translate the meta-data headers into a "proper" table definition with usable columns?

Either way I would load each data set directly into an intermediate table 1 row per record. Even if you need to name the columns (col1,col2,col3 .... col256) or just a one very wide column. Then change your validation process to use the intermediate tables rather than load everything into memory.

If you can cross-reference the the various files they must have some meaning full key/identifier already. You could use these as the primary keys rather than letting the database allocate a key, thus saving you the work of tying everything up again.