答:
Visitor Pattern:

Note that the code contains no if-then-else or switch-case structures to select the appropiate compressor. It's not needed since the visitor patterns allow for the appropiate dispatch.

```<code>public interface IBase {
    void accept(ICompressorVisitor e);
    void setName(String s);
    String getName();
}

public class Base1 implements IBase {
    private String name="";
    @Override
    public void accept(ICompressorVisitor e) {
        e.visit(this);
    }

    @Override
    public void setName(String s) {
        this.name = s;
    }

    @Override
    public String getName() {
        return "Base1("+this.name+")";
    }

}

public class Base2 implements IBase  {
    private String name="";
    @Override
    public void accept(ICompressorVisitor e) {
        e.visit(this);
    }

    @Override
    public void setName(String s) {
        this.name = s;
    }

    @Override
    public String getName() {
        return "Base2("+this.name+")";
    }
}

public interface ICompressorVisitor {
    void visit(Base1 base);
    void visit(Base2 base);
}

public class CompressorX implements ICompressorVisitor {

    @Override
    public void visit(Base1 base) {
        System.out.println("Compressing "+base.getName()+" using algorithm X optimized for Base1");

    }

    @Override
    public void visit(Base2 base) {
        System.out.println("Compressing "+base.getName()+" using algorithm X optimized for Base2");
    }

}

public class CompressorY implements ICompressorVisitor {

    @Override
    public void visit(Base1 base) {
        System.out.println("Compressing "+base.getName()+" using algorithm Y optimized for Base1");

    }

    @Override
    public void visit(Base2 base) {
        System.out.println("Compressing "+base.getName()+" using algorithm Y optimized for Base2");

    }

}

public class Test {

    public static void main(String[] args) {
        Base1 b1 = new Base1();
        b1.setName("a");
        Base2 b2 = new Base2();
        b2.setName("b");

        CompressorX x = new CompressorX();
        CompressorY y = new CompressorY();

        b1.accept(x);
        b1.accept(y);

        b2.accept(x);
        b2.accept(y);

    }

}
</code>```

Output of test:

```<code>Compresing Base1(a) using algorithm X optimized for Base1
Compresing Base1(a) using algorithm Y optimized for Base1
Compresing Base2(b) using algorithm X optimized for Base2
Compresing Base2(b) using algorithm Y optimized for Base2
</code>```

Title: Recommened design pattern to handle multiple compression algorithms for a class hierarchy

Body:
For all you OOD experts. What would be the recommended way to model the following scenario?

I have a certain class hierarchy similar to the following one:

```<code>class Base {
   ...
}

class Derived1 : Base {
   ...
}

class Derived2 : Base {
   ...
}
...
</code>```

Next, I would like to implement different compression/decompression engines for this hierarchy.  (I already have code for several strategies that best handle different cases, like file compression, network stream compression, legacy system compression, etc.)

I would like the compression strategy to be pluggable and chosen at runtime, however I'm not sure how to handle the class hierarchy. Currently I have a tighly-coupled design that looks like this:

```<code>interface ICompressor {
   byte[] Compress(Base instance);
}

class Strategy1Compressor : ICompressor {
   byte[] Compress(Base instance) {

      // Common compression guts for Base class
      ...
      //

      if( instance is Derived1 ) {
         // Compression guts for Derived1 class
      }
      if( instance is Derived2 ) {
         // Compression guts for Derived2 class
      }

      // Additional compression logic to handle other class derivations
      ...
   }

}
</code>```

As it is, whenever I add a new derived class inheriting from Base, I would have to modify all compression strategies to take into account this new class.  Is there a design pattern that allows me to decouple this, and allow me to easily introduce more classes to the Base hierarchy and/or additional compression strategies?

Body:
Visitor Pattern:

Note that the code contains no if-then-else or switch-case structures to select the appropiate compressor. It's not needed since the visitor patterns allow for the appropiate dispatch.

public interface IBase {
    void accept(ICompressorVisitor e);
    void setName(String s);
    String getName();
}

public class Base1 implements IBase {
    private String name="";
    @Override
    public void accept(ICompressorVisitor e) {
        e.visit(this);
    }

    @Override
    public void setName(String s) {
        this.name = s;
    }

    @Override
    public String getName() {
        return "Base1("+this.name+")";
    }

}

public class Base2 implements IBase  {
    private String name="";
    @Override
    public void accept(ICompressorVisitor e) {
        e.visit(this);
    }

    @Override
    public void setName(String s) {
        this.name = s;
    }

    @Override
    public String getName() {
        return "Base2("+this.name+")";
    }
}

public interface ICompressorVisitor {
    void visit(Base1 base);
    void visit(Base2 base);
}

public class CompressorX implements ICompressorVisitor {

    @Override
    public void visit(Base1 base) {
        System.out.println("Compressing "+base.getName()+" using algorithm X optimized for Base1");

    }

    @Override
    public void visit(Base2 base) {
        System.out.println("Compressing "+base.getName()+" using algorithm X optimized for Base2");
    }

}

public class CompressorY implements ICompressorVisitor {

    @Override
    public void visit(Base1 base) {
        System.out.println("Compressing "+base.getName()+" using algorithm Y optimized for Base1");

    }

    @Override
    public void visit(Base2 base) {
        System.out.println("Compressing "+base.getName()+" using algorithm Y optimized for Base2");

    }

}

public class Test {

    public static void main(String[] args) {
        Base1 b1 = new Base1();
        b1.setName("a");
        Base2 b2 = new Base2();
        b2.setName("b");

        CompressorX x = new CompressorX();
        CompressorY y = new CompressorY();

        b1.accept(x);
        b1.accept(y);

        b2.accept(x);
        b2.accept(y);

    }

}

Output of test:

Compresing Base1(a) using algorithm X optimized for Base1
Compresing Base1(a) using algorithm Y optimized for Base1
Compresing Base2(b) using algorithm X optimized for Base2
Compresing Base2(b) using algorithm Y optimized for Base2


问:
Recommened design pattern to handle multiple compression algorithms for a class hierarchy
For all you OOD experts. What would be the recommended way to model the following scenario?

I have a certain class hierarchy similar to the following one:

```<code>class Base {
   ...
}

class Derived1 : Base {
   ...
}

class Derived2 : Base {
   ...
}
...
</code>```

Next, I would like to implement different compression/decompression engines for this hierarchy.  (I already have code for several strategies that best handle different cases, like file compression, network stream compression, legacy system compression, etc.)

I would like the compression strategy to be pluggable and chosen at runtime, however I'm not sure how to handle the class hierarchy. Currently I have a tighly-coupled design that looks like this:

```<code>interface ICompressor {
   byte[] Compress(Base instance);
}

class Strategy1Compressor : ICompressor {
   byte[] Compress(Base instance) {

      // Common compression guts for Base class
      ...
      //

      if( instance is Derived1 ) {
         // Compression guts for Derived1 class
      }
      if( instance is Derived2 ) {
         // Compression guts for Derived2 class
      }

      // Additional compression logic to handle other class derivations
      ...
   }

}
</code>```

As it is, whenever I add a new derived class inheriting from Base, I would have to modify all compression strategies to take into account this new class.  Is there a design pattern that allows me to decouple this, and allow me to easily introduce more classes to the Base hierarchy and/or additional compression strategies?

答:
Assuming that each combination of Derived and compression strategy compresses differently, then there is no way you can decouple them.  You can refactor the linkage out somewhat to avoid switch and if/else statements, but you can't remove it entirely - each one will have to be aware of the others.

If you can separate the compression algorithm from knowledge of what it's compressing, you can store a ICompressor somewhere, and then populate it at runtime.  ICompressor would have to operate on a standard type, and each Derived would need to be able to convert to that type (probably via function call like .Compress(this.PrepForCompression()) or .Compress(this.Serialize())).

ContentLicense: CC BY-SA 3.0


问:
Alternatives to Professional Version Control
We're teaming up with some non programmers (writers) who need to contribute to one of our projects.

Now they just don't like the idea of using Git (or anything for that matter) for version controlling their work. I think this is because they just don't find it worthwhile to wrap their heads around the twisted concepts of version control. (when I first introduced them to branching and merging -- they looked like I was offending them.)

Now, we're not in a position to educate them or convince them to use it. We're just trying to find alternatives so that we get all their work versioned (which is what we need) -- and they get easy workflow and concentrate on what they do.

I have come up with some ideas...

tell them to save their work as a separate file every time they make some non-trivial change, and then use a diff on our side to just track changes.

write a program (in Python) that implements the "milestones" in CSSEdit in some way.

About the project:

It is a natural language processing system (written in C + Python). We've hired some writers to prepare inputs for the system in different languages. And as we evolve the software, we'd need those writers to make changes to their inputs (articles). Sometimes the changes are very small (a word or two), and other times big.

The reason we need to version control those changes is because every small/big change in the input has the potential to change the system's output dramatically.

答:
Let them work in a folder, saving files as usual.

Once a day (or week, etc) copy the contents of that folder to backup_dd_mm_yyyy  Most systems source code occupies a trivial amount of space given the space available these days.

The copy can either be done by you, them, a third party, a tool or a script.

This limits loss to one day, gives a history, is transparent to them.

Not perfect for either party but an answer that seeks to strike a middle ground.


问:
How will quantum computing change programming?
How is programming a quantum algorithm different? What would a C like language look like if it was designed for qubits? Would types change?</p>

答:
In order to make the most effective possible use of a quantum computer, one needs to be able to deal with inputs and outputs that are states of a quantum register, for which there is really no classical analogue. Speaking from some years of experience in the field of quantum information, I must warn you that no one really has a good intuition for this beyond the abstract mathematics of C* algebras, and I'm told that even this intuition turns out to be inadequate if you start wondering about relativity theory.

The class of problems that are efficiently solvable on a quantum computer is known as BQP, for Bounded Quantum Polynomial. This is the quantum version of BPP, and you can find more information in this paper: http://www.scottaaronson.com/papers/bqpph.pdf

I was told just last night by a quantum algorithms researcher that there is a very important problem that is BQP-complete: solving a linear system of N equations. Classically, this is solvable in O(N) steps with Gaussian elimination. The Harrow-Hassidim-Lloyd algorithm (http://arxiv.org/abs/0811.3171) solves it in polylog(N), provided you are willing to accept an answer that has the solution encoded as a quantum state. If you want to make full use of a quantum computer, it therefore seems necessary for you to have a type corresponding to the state of a quantum register.

Though I am a little outside of my particular expertise right now, I would hazard a guess that you would be able to program a quantum computer as long as you had access to a type corresponding to magic states. That's a difficult concept, though, that requires quite some study of the subject.

Be warned that we are a very long time from having a quantum programming language, because we are at a very primitive stage of quantum computing research. Asking for a quantum C right now would be like going to Alan Turing and asking him to design Python. We haven't even got the quantum version of the vacuum tube yet!


问:
SOLID Principles and code structure
At a recent job interview, I couldn't answer a question about SOLID -- beyond providing the basic meaning of the various principles. It really bugs me. I have done a couple of days worth of digging around and have yet to come up with a satisfactory summary.

The interview question was:

If you were to look at a .Net project that I told you strictly followed SOLID principles, what would you expect to see in terms of the project and code structure?

I floundered around a bit, didn't really answer the question, and then bombed out.

How could I have better handled this question?

答:
Some basic things I would expect to see in the codebase of a shop that espoused SOLID in their daily work:

Many small code files - with one class per file as best practice in .NET, and the Single Responsibility Principle encouraging small modular class structures, I'd expect to see a lot of files each containing one small, focused class.

Lots of Adapter and Composite patterns - I'd expect the use of a lot of Adapter patterns (a class implementing one interface by "passing through" to the functionality of a different interface) to streamline plugging in a dependency developed for one purpose into slightly different places where its functionality is also needed. Updates as simple as replacing a console logger with a file logger will violate LSP/ISP/DIP if the interface is updated to expose a means to specify the filename to use; instead, the file logger class will expose the additional members, and then an Adapter will make the file logger look like a console logger by hiding the new stuff, so only the object snapping all this together has to know the difference.

Similarly, when a class needs to add a dependency of a similar interface as an existing one, to avoid changing the object (OCP), the usual answer is to implement a Composite/Strategy pattern (a class implementing the dependency interface and consuming multiple other implementations of that interface, with varying amounts of logic allowing the class to pass a call through to one, some, or all of the implementations).

Lots of interfaces and ABCs - DIP necessarily requires that abstractions exist, and ISP encourages these to be narrowly-scoped. Therefore, interfaces and abstract base classes are the rule, and you'll need a lot of them to cover the shared dependency functionality of your codebase. While strict SOLID would necessitate injecting everything, it's obvious you have to create somewhere, and so if a GUI form is only ever created as a child of one parent form by performing some action on said parent, I have no qualms newing up the child form from code directly within the parent. I just typically make that code its own method, so if two actions of the same form ever opened the window, I just call the method.

Many projects - The point of all of this is to limit the scope of change. Change includes needing to recompile (a relatively trivial exercise anymore, but still important in many processor- and bandwidth-critical operations, like deploying updates to a mobile environment). If one file in a project has to be rebuilt, all files do. That means if you place interfaces in the same libraries as their implementations, you're missing the point; you'll have to recompile all usages if you change an implementation of the interface because you'll also be recompiling the interface definition itself, requiring usages to point to a new location in the resulting binary. Therefore, keeping interfaces separate from usages and implementations, while additionally segregating them by general area of use, is a typical best practice.

Lots of attention paid to "Gang of Four" terminology - The design patterns identified in the 1994 book Design Patterns emphasize the bite-size, modular code design that SOLID seeks to create. The Dependency Inversion Principle and Open/Closed Principle, for instance, are at the heart of most of the identified patterns in that book. As such, I'd expect a shop that adhered strongly to SOLID principles to also embrace the terminology in the Gang of Four's book, and name classes according to their function along those lines, such as "AbcFactory", "XyzRepository", "DefToXyzAdapter", "A1Command" etc.

A generic Repository - In keeping with ISP, DIP and SRP as commonly understood, Repository is nearly ubiquitous in SOLID design, as it allows consuming code to ask for data classes in an abstracted way without needing specific knowledge of the retrieval/persistence mechanism, and it puts the code that does this in one place as opposed to the DAO pattern (in which if you had, for instance, an Invoice data class, you'd also have an InvoiceDAO that produced hydrated objects of that type, and so on for all data objects/tables in the codebase/schema).

An IoC Container - I hesitate to add this one, as I actually do not use an IoC framework to do the majority of my dependency injection. It quickly becomes a God Object anti-pattern of throwing everything into the container, shaking it up and pouring out the vertically-hydrated dependency you need through an injected factory method. Sounds great, until you realize that structure gets pretty monolithic, and the project with the registration info, if "fluent", now has to know everything about everything in your solution. That is a lot of reasons to change. If it isn't fluent (late-bound registrations using config files), then a key piece of your program relies on "magic strings", a whole different can o' worms.

OwnerDisplayName: S-Unit

Title: SOLID Principles and code structure


问:
What values in an application should be configurable?
What values in an application should be configurable, or otherwise not hard coded?  Does this differ based on application type (batch vs UI) and are there any published standards or guidance on this topic (IEEE, ACM, vendor, etc)?</p>

答:
Obviously, the more the value is expected to have to change, the more likely I'd make it a config setting rather than hard-coding it. I generally have a three-strikes rule; Hard-code it first because that's easy, then change it once on the first user request, and on the next change after that, refactor it into a config value that can be changed in-place without another code update.

Other factors that would lead me toward hard-coding:

The value is an implementation detail. If your end users don't care what its value is, don't expose it.

The value is a "universal constant" for the system; maybe not something mathematical like pi or e, but a value that, if it ever did change, would require substantial code edits anyway.

The program doesn't use shared config settings, and it's easier/safer to push a full update than to have the users update their local configs. I have a couple of ClickOnce apps that are hard to access in the filesystem by design, while a publish and upgrade is relatively easy. Using config settings for machine-independent values is purely for my benefit as a coder in these circumstances.

Factors that lead me toward configuration settings (whether in a local file or a shared DB):

Uptime is critical. Business-critical services that can only be taken down for maintenance at very un-businesslike hours of the night or weekend should be designed with as few reasons to perform such maintenance as possible. So, not only should you make controlling values that could change independent of other code into config values, the service should be designed to refresh these values and change its configuration periodically, so you don't even need a manual restart.

The value varies between installations. The phone number of the workstation on which the software is installed is an obvious example of something that is never OK to hard-code.

The value is part of a system designed to be customizable. For instance, programs with multiple child windows like an MDI should remember the positions of different types of windows when they're closed, and re-open the next one of that type in the same spot. This may not be user-configurable, but don't just hard-code unless your users are trained specifically toward a particular layout.


问:
Writing Large Portions Of Code Then Debugging?
Lately I have been writing a game engine, and I have been writing a lot of "foundation stuff" (standard interfaces, modules, a message system ect.), but I have noticed a pattern, a lot of the stuff is interdependent and I can not debug until everything is done, hence I do not debug for about 3 to 5 hours at a time. I am wondering if this is an acceptable practice for this part of the project, and if not, if anyone can give me some advice?

-----Update-----:

I downloaded some code metrics tools, and my programs cyclomatic complexity is 1.52 which as I understand it is good, and should correlate to high cohesion, if I am wrong please correct me/

答:
Stop. No really, stop. Stop and read about Test Driven Development.

The system you are implementing will have a difficult time being tested, debugged, maintained, updated, etc.

Take TDD to heart and spend the time now to understand how TDD can drive your design to a system that can be tested, debugged, and maintained.

TDD has changed the way that I develop.


问:
Query something and return the reason if nothing has been found
Assume I have a Query - as in CQS that is supposed to return a single value.

Let's assume that the case that no value is found is not exceptional, so no exception will be thrown in this case. Instead, null is returned.

However, if no value has been found, I need to act according to the reason why no value has been found.

Assuming that the Query knows the reason, how would I communicate it to the caller of the Query?

A simple solution would be not return the value directly but a container object that contains the value and the reason:

```<code>public class QueryResult
{
    public TValue Value { get; private set; }
    public TReason ReasonForNoValue { get; private set; }
}
</code>```

But that feels clumsy, because if a value is found, ReasonForNoValue makes no sense and if no value has been found, Value makes no sense.

What other options do I have to communicate the reason? What do you think of one event per reason?

For reference: This is going to be implemented in C#.

答:
First of all, I would most likely use an exception in this case.  Catchy slogans aside, exceptions are the standard way to concisely specify a "success" control flow and an orthogonal "non-success" control flow.  How commonly the non-success path happens has little to do with it, especially when you're adding exception overhead to the much larger database query overhead.

My second choice would be having the calling class implement a result interface, something like this:

```<code>public class Caller implements ResultHandler {

    public void findValue(Query query) {
        query.execute(this);
    }

    public void valueFound(Value value) {
        System.out.println("Found value " + value);
    }

    public void valueNotFound(String reason) {
        System.err.println("Value not found: " + reason);
    }
}
</code>```

Like an exception, this solution has the benefit of being unignorable on null values.  This architecture also makes it easy to do other things while you wait for the query to complete.  Also, you should really be putting valueFound and valueNotFound in their own functions either way.

Your QueryResult object is better than returning null, but has the drawback of requiring boilerplate code everywhere to check the response code.  If someone later on forgets that boilerplate, or intentionally omits it thinking the value will always be found, there's no telling what state that will put the code into.

In other words, it adds burden on the maintainers.  It may seem blatantly obvious that you need to check the response code now, but it won't be so obvious two years from now.  The more errors are caught by the compiler, the better.

Body:
First of all, I would most likely use an exception in this case.  Catchy slogans aside, exceptions are the standard way to concisely specify a "success" control flow and an orthogonal "non-success" control flow.  How commonly the non-success path happens has little to do with it, especially when you're adding exception overhead to the much larger database query overhead.

My second choice would be having the calling class implement a result interface, something like this:

public class Caller implements ResultHandler {

    public void findValue(Query query) {
        query.execute(this);
    }

    public void valueFound(Value value) {
        System.out.println("Found value " + value);
    }

    public void valueNotFound(String reason) {
        System.err.println("Value not found: " + reason);
    }
}

Like an exception, this solution has the benefit of being unignorable on null values.  This architecture also makes it easy to do other things while you wait for the query to complete.  Also, you should really be putting valueFound and valueNotFound in their own functions either way.

Your QueryResult object is better than returning null, but has the drawback of requiring boilerplate code everywhere to check the response code.  If someone later on forgets that boilerplate, or intentionally omits it thinking the value will always be found, there's no telling what state that will put the code into.

In other words, it adds burden on the maintainers.  It may seem blatantly obvious that you need to check the response code now, but it won't be so obvious two years from now.  The more errors are caught by the compiler, the better.


问:
Is the development of CLI apps considered "backward"?
I am a DBA fledgling with a lot of experience in programming.

I have developed several CLI, non interactive apps that solve some daily repetitive tasks or eliminate the human error from more complex albeit not so daily tasks. These tools are now part of our tool box.

I find CLI apps are great because you can include them in an automated workflow.

Also the Unix philosophy of doing a single thing but doing it well, and letting the output of a process be the input of another, is a great way of building a set of tools than would consolidate into an strategic advantage.

My boss recently commented that developing CLI tools is "backward", or constitutes a "regression".

I told him I disagreed, because most CLI tools that exist now are not legacy but live projects with improved versions being released all the time.

Is this kind of development considered "backwards" in the market?

Does it look bad on a rèsumè?

I also considered all solutions whether they are web or desktop, should have command line, non-interactive options. Some people consider this a waste of programming resources.

Is this goal a worthy one in a software project?

I also think that for a web or desktop app, having an alternate CLI interface is a great way of demonstrating that the business logic is completely decoupled from the GUI.

答:
No, it's not backwards at all.

The "direction" has a lot to do with our perspective.  A user happy with the current path toward simple, "one experience all devices" interfaces is going to see the CLI as a throwback or regression for sure.  It's not in line with their overall expectations.

A programmer, administrator or power user may well see it as the logical progression of tools according to their experience.  Many of these start out using GUI tools.  When they want to or need to scale, they rapidly figure out why the CLI exists and that progression resonates with those building more CLI tools.

There is this by Paul Ferris:  http://www.linuxplanet.com/linuxplanet/opinions/1505/1

To me personally, the idea of syntax differentiates the two.  When syntax is somewhat present in a GUI, the result is almost never good and as flexible as well thought out CLI syntax.  When this is coupled with pipes and redirection, the GUI falls flat due to it not being very useful outside the planned use cases.

My personal preference on this is CLI tools that offer a --gui or --verbose option sufficient to allow a GUI wrapper to interact in a robust way including status bars and other basic elements people look to the GUI for.

Of course the cost of this is essentially two programs with one rather useless without the other, but the major benefit is being able to incorporate one or more great CLI tools into a custom GUI without modification to said CLI tools.  Most often this is only done to offer a GUI option on a particular CLI, but the idea of driving multiple tools with one "process" or "use case" oriented GUI can deliver results similar to piping and redirecting and scripting for that use case, making it available to people who would not perform those operations regularly enough to reach mastery while still not inhibiting the CLI users.

I encountered this approach on SGI IRIX and really liked it.  I found myself using either the GUI or command line as needed and the nice thing was knowing exactly what the fancy buttons were actually doing.

Where there are lots of different operating environments, the GUI wrappers can differ considerably without impacting the CLI tool as well.

I see this in Linux today with things like disk / filesystem tools, where the GUI can add a lot of value even to CLI familiar users.

In the case of known filesystems / disks / devices, knocking out the CLI isn't tough, and it can be scripted of course.  Mistakes can be painful however.

Where those may not be known, or perhaps performing the operations isn't done regularly enough to remain solid and error free, running the GUI provides an environment that can be easily verified, operations chained together and then run with confidence, no scripts required.


问:
Putting semicolons after while and if statements in C++
How come in C++ when you put:

```<code>while (expression);
</code>```

the while loop doesn't run no matter if the expression is true or not.

However if you put:

```<code>if (expression);
</code>```

the statement runs no matter if the expression is true or not.

It seems like they should both behave the same way.

答:
The syntax is:

```<code>if (<expr>) <statement>

// or

while (<expr>) <statement>
</code>```

So the statement (in both cases) is only executed if the expression evaluates to true. In the case of while it will enter a loop (re-evaluating express each time).

So the question what <statement> is executes. This comes down to the definition of statement. If there are not braces {} then the next statement is terminated by ; even if that statement is EMPTY. An empty statement is valid;

```<code>if (<expr>)    /* Empty Statement */;

while (<expr>) /* Empty Statement */;
</code>```

In both cases there is nothing being executed (after the expression is evaluated). Though while may enter an infinite loop. Note: '{}' is a statement-Block (a type of statement (that contains a list of other statement).

Note:

It is considered bad form to use empty statements with for(;;) or while() or if(). It is often hard to spot and when people do spot it they are not entirely sure the code is correct (and may have to spend time de-bugging the code to verify correctness).

I find it best to use '{}` after each of these to emphasis the point (and catch multi=statement macros).

```<code>for(<init>;<test>;<inc>) { /*Deliberately blank */ }
</code>```

Body:
The syntax is:

if (<expr>) <statement>

// or

while (<expr>) <statement>

So the statement (in both cases) is only executed if the expression evaluates to true. In the case of while it will enter a loop (re-evaluating express each time).

So the question what <statement> is executes. This comes down to the definition of statement. If there are not braces {} then the next statement is terminated by ; even if that statement is EMPTY. An empty statement is valid;

if (<expr>)    /* Empty Statement */;

while (<expr>) /* Empty Statement */;

In both cases there is nothing being executed (after the expression is evaluated). Though while may enter an infinite loop. Note: '{}' is a statement-Block (a type of statement (that contains a list of other statement).

Note:

It is considered bad form to use empty statements with for(;;) or while() or if(). It is often hard to spot and when people do spot it they are not entirely sure the code is correct (and may have to spend time de-bugging the code to verify correctness).

I find it best to use '{}` after each of these to emphasis the point (and catch multi=statement macros).

for(<init>;<test>;<inc>) { /*Deliberately blank */ }


问:
Avoiding null in a controller
I'm trying to work through how to write this code.

```<code>def get(params):
    """ Fetch a user's details, or 404 """
    user = User.fetch_by_id(params['id'])
    if not user:
        abort(404)
    # Render some template for the user...
</code>```

What's the best way to handle the case where the lookup fails? One principle says you should avoid returning null values from functions. These lead to mistakes and AttributeErrors etc. later on in the file.

Another idea is to have fetch_by_id raise a ValueError or similar if no user exists with that id. However there's a general principle that you shouldn't use exceptions for control flow, either, which doesn't help much.

What could be done better in this case?

答:
I won't be against the first approach (returning null) too much, but will rename the method to clearly indicate it may return null.

Signatures like:

```<code>findCustomer(int customerId)
parse(string number)
pop(stack sequence)
</code>```

are not clear. If a customer doesn't exist, is the method returning null or throwing a CustomerNotFound exception? If the number is "abc" and cannot be reasonably parsed, is the method returning null or throwing InvalidFormat exception? What happens when poping an element from an empty stack?

Instead:

```<code>findCustomerIfAny(int customerId)
tryParse(string number)
lastOrNull(stack sequence)
</code>```

are easier to understand.

Other options you have include:

1. out parameters

If your language supports out parameters, a different approach would be to have the following:

```<code>tryFindCustomer(int customerId, out customer result) returns bool
</code>```

The boolean result indicates whether the customer was found or not.

Personally, I find this approach too verbose and ugly. I won't use it.

2. Tuples

If your language has tuples, then you can write:

```<code>findCustomer(int customerId) returns (bool isFound, customer match)
</code>```

This is perfectly valid, and may make your code extremely explicit.

3. Value or default

There is also another interesting convention in LINQ in .NET. A method which searches for the first element of a sequence, FirstOrDefault, returns the default value if the sequence is empty.

This means that:

```<code>[ 2, 7, 1 ].FirstOrDefault()
</code>```

gives 2, while:

```<code>[].FirstOrDefault()
</code>```

gives 0, since default(int) is 0. Note that:

```<code>default(customer) ↔ null
default(System.Drawing.Point) ↔ System.Drawing.Point.Empty ↔ (0, 0)
</code>```

etc.

Unfortunately, you can't override default operator, which makes this approach rather limited.

I'm not sure this last approach will help in your case, but it's worth mentioning.

4. Status within the returned value

A custom-made approach would be to integrate a status value within the class itself. For example:

```<code>// `findCustomer` always returns a non-null value.
selectedCustomer = findCustomer(customerIdFromInput)

// When the customer cannot be found, `IsEmpty` is set to `true`.
if (selectedCustomer.IsEmpty) {
    throw CustomerNotFoundException;
}
</code>```

Title: Avoiding null in a controller

Body:
I won't be against the first approach (returning null) too much, but will rename the method to clearly indicate it may return null.

Signatures like:

findCustomer(int customerId)
parse(string number)
pop(stack sequence)

are not clear. If a customer doesn't exist, is the method returning null or throwing a CustomerNotFound exception? If the number is "abc" and cannot be reasonably parsed, is the method returning null or throwing InvalidFormat exception? What happens when poping an element from an empty stack?

Instead:

findCustomerIfAny(int customerId)
tryParse(string number)
lastOrNull(stack sequence)

are easier to understand.

Other options you have include:

1. out parameters

If your language supports out parameters, a different approach would be to have the following:

tryFindCustomer(int customerId, out customer result) returns bool

The boolean result indicates whether the customer was found or not.

Personally, I find this approach too verbose and ugly. I won't use it.

2. Tuples

If your language has tuples, then you can write:

findCustomer(int customerId) returns (bool isFound, customer match)

This is perfectly valid, and may make your code extremely explicit.

3. Value or default

There is also another interesting convention in LINQ in .NET. A method which searches for the first element of a sequence, FirstOrDefault, returns the default value if the sequence is empty.

This means that:

[ 2, 7, 1 ].FirstOrDefault()

gives 2, while:

[].FirstOrDefault()

gives 0, since default(int) is 0. Note that:

default(customer) ↔ null
default(System.Drawing.Point) ↔ System.Drawing.Point.Empty ↔ (0, 0)

etc.

Unfortunately, you can't override default operator, which makes this approach rather limited.

I'm not sure this last approach will help in your case, but it's worth mentioning.

4. Status within the returned value

A custom-made approach would be to integrate a status value within the class itself. For example:

// `findCustomer` always returns a non-null value.
selectedCustomer = findCustomer(customerIdFromInput)

// When the customer cannot be found, `IsEmpty` is set to `true`.
if (selectedCustomer.IsEmpty) {
    throw CustomerNotFoundException;
}


问:
How to manually detect deadlocks
I understand the concepts of deadlock well enough, but when I'm given a problem like the one below I'm not sure how to go about solving it. I can draw a resource allocation graph, but I'm not sure how to solve it from there.

Is there a better more formal way of solving this?

```<code>Consider  a  system  with  five  processes,  P1  through P5,  and  five
resources, R1 through R5. Resource ownership is as follows.

•  P1 holds R1 and wants R3
•  P2 holds R2 and wants R1
•  P3 holds R3 and wants R5
•  P4 holds R5 and wants R2
•  P5 holds R4 and wants R2

Is this system deadlocked? Justify your answer. If  the system is deadlocked, list
the involved processes.
</code>```

答: In a formal sense, a deadlock will be indicated by one or more cycles in the resource allocation graph.  The processes that form the cycle or cycles, or that transitively depend on the cycles are deadlocked. </p>

Title: How to manually detect deadlocks


答:
Yes it's a deadlock, diagram the wait chain of processes (1 -> 2 indicates P1 waiting on P2 to release a resource):

1 -> 3 -> 4 -> 2 -> 1

Ran back into 1 in the wait chain and the cycle is complete; that is 1 is waiting on resources that are waiting on resources that are waiting on 1.

If following 1 like this didn't run back into itself then it would be accurate to say 1 is not in a deadlock (for instance if it was 1->3->4->2). However if one were not in a deadlock that does not prove or indicate none of the others are in dead locks. To verify none of the resources are in a deadlock you would need to graph the same chain with any nodes that weren't in the critical path for 1 (if any in the critical path were in a deadlock then 1 would be, so you know all members of it's dependency chain are not in deadlocks). Since 5 isn't in the critical path you would have to next follow 5's path if 1 wasn't in a deadlock (incidentally 5 is also in a deadlock because it links into the same cycle 1 is in, therefore all listed resources are deadlocked in that cycle)

Another point regarding this particular problem is that all resources available (the set of R1-R5) are already acquired. In such a scenario it is impossible for any process to acquire another resource if no processes are willing to first let go of a resource. A cycle is inevitable in such a scenario. This fact that you should release resources before requesting more is I think supposed to be the lesson of the 73.4 philosophers problem (don't quote me on that)

Title: How to manually detect deadlocks

Body:
I understand the concepts of deadlock well enough, but when I'm given a problem like the one below I'm not sure how to go about solving it. I can draw a resource allocation graph, but I'm not sure how to solve it from there.

Is there a better more formal way of solving this?

```<code>Consider  a  system  with  five  processes,  P1  through P5,  and  five
resources, R1 through R5. Resource ownership is as follows.

•  P1 holds R1 and wants R3
•  P2 holds R2 and wants R1
•  P3 holds R3 and wants R5
•  P4 holds R5 and wants R2
•  P5 holds R4 and wants R2

Is this system deadlocked? Justify your answer. If  the system is deadlocked, list
the involved processes.
</code>```


答:
Renaming the methods as MainMa suggested is a possibility, though the resulting method names may not be appealing to everyone. In the line of your question on how to actually avoid returning null, here are two more options:

Option/Maybe

Several languages directly support a type that encodes whether you successfully found an object or not (f.ex. Option in Scala, or Maybe in Haskell). With these you basically wrap your result inside of another type to ensure you deliver a non-null result. More precisely, if you found the user object, you dont returnuserbutSome(user), whereSomeis anOption. If you did not find the user, you instead return aNoneobject, which is better than anull, as you at least have theOption` interface available on it.

For languages, which do not directly support these, there are typically additional libraries you can pull in for that (for example Optional in guava for Java).

Null Object Pattern

A different option is the null object pattern. Essentially, it means that you have to return a User object, no matter what happens. In case you could not find a user object for your id, you have to return a specially crafted null-user object. The advantage of this object is that it implements the complete interface of a User class and callers need not care about whether the user was found or not (they may want to though, which is why it makes sense to add some isNull method or such to the interface).

Say, you want to write code that given a user id somehow e-mails that user about your oh-so-great new promotion. With the null object pattern you could retrieve the user via id, but instead get the null-user object. On that one you can simply call some getEMailAddress method or such, which may return you a fallback address like error@myhost.com, or anything else that suits you. Your complete code does not need to check whether a user with that id even exists.

Title: Avoiding null in a controller

Body:
I'm trying to work through how to write this code.

```<code>def get(params):
    """ Fetch a user's details, or 404 """
    user = User.fetch_by_id(params['id'])
    if not user:
        abort(404)
    # Render some template for the user...
</code>```

What's the best way to handle the case where the lookup fails? One principle says you should avoid returning null values from functions. These lead to mistakes and AttributeErrors etc. later on in the file.

Another idea is to have fetch_by_id raise a ValueError or similar if no user exists with that id. However there's a general principle that you shouldn't use exceptions for control flow, either, which doesn't help much.

What could be done better in this case?


答:
One of the formal tools aimed at detecting issues in concurrent systems (deadlock, resource starvation...) is Petri nets.

You model your problem with a Petri net, then you can perform mathematical analysis on it and prove some properties of your system, such as unreachable states.

Title: How to manually detect deadlocks


问:
Fork dead SVN based project on GitHub
I previously asked this at stack overflow but it was closed, I believe because 'programmers' is a more appropriate venue for this question.

I have done some work on the SVN Importer project (Apache license), which appears to be effectively dead (no published changes in 5 years). I have a login to their svn server but do not have commit rights. At any rate, I'd like to convert this project to Git and push my own changes to GitHub. The GitHub site suggests the svn2git tool for converting svn projects to Git, so I was planning to convert the SVN repository to Git, add my changes, and then push this Git repository to GitHub.

I'm wondering, what are the legal requirements and common conventions of this process? Is it acceptable to clone the entire history of the project and move it to GitHub? Also, even though this is essentially a dead project, once I've translated the repository to Git should I put all of my commits onto a non master branch or is it acceptable to use master in this case?

答: Where you put the repository should not have any bearing on the license, unless of course the license specifically mentions relocation or a place where everything has to be submitted. Since prohibiting forks or naming a specific repository or VCS would be anything from stupid to not in the spirit of open source, my NAL opinion is that you'd be just fine. I certainly wouldn't think twice about it.</p>

Title: Fork dead SVN based project on GitHub


答:
I'm trying to work through how to write this code.

```<code>def get(params):
  """ Fetch a user's details, or 404 """
  user = User.fetch_by_id(params['id'])
  if not user:
    abort(404)
  # Render some template for the user...
</code>```

What's the best way to handle the case where the lookup fails? One principle says you should avoid returning null values from functions.

Eh... IMO there are only two reasonable options for a direct lookup like 'find_by_id'.  Everything else is overly complicated.

```<code>1) return something false-y, like null
2) raise an exception
</code>```

Returning null is slightly simpler when the caller will immediately check the return value. Throwing an exception is simpler when the caller wants to perform multiple actions and handle failures identically.

IMO a generic API should provide both for single record retrieval, e.g. 'find_by_id', which may return null, and 'fetch_by_id' which returns a record or raises an exception.

Title: Avoiding null in a controller

Body:
I'm trying to work through how to write this code.

def get(params):
  """ Fetch a user's details, or 404 """
  user = User.fetch_by_id(params['id'])
  if not user:
    abort(404)
  # Render some template for the user...

What's the best way to handle the case where the lookup fails? One principle says you should avoid returning null values from functions.

Eh... IMO there are only two reasonable options for a direct lookup like 'find_by_id'.  Everything else is overly complicated.

1) return something false-y, like null
2) raise an exception

Returning null is slightly simpler when the caller will immediately check the return value. Throwing an exception is simpler when the caller wants to perform multiple actions and handle failures identically.

IMO a generic API should provide both for single record retrieval, e.g. 'find_by_id', which may return null, and 'fetch_by_id' which returns a record or raises an exception.


问:
Working for free?
I came across this article Work for Free that got me thinking.

The goal of every employer is to gain
  more value from workers than the firm
  pays out in wages; otherwise, there is
  no growth, no advance, and no
  advantage for the employer.
  Conversely, the goal of every employee
  should be to contribute more to the
  firm than he or she receives in wages,
  and thereby provide a solid rationale
  for receiving raises and advancement
  in the firm.

I don't need to tell you that the
  refusenik didn't last long in this
  job.

In contrast, here is a story from last
  week. My phone rang. It was the
  employment division of a major
  university. The man on the phone was
  inquiring about the performance of a
  person who did some site work on
  Mises.org last year. I was able to
  tell him about a remarkable young man
  who swung into action during a crisis,
  and how he worked three 19-hour days,
  three days in a row, how he learned
  new software with diligence, how he
  kept his cool, how he navigated his
  way with grace and expertise amidst
  some 80 different third-party plug-ins
  and databases, how he saw his way
  around the inevitable problems, how he
  assumed responsibility for the
  results, and much more.

What I didn't tell the interviewer was
  that this person did all this without
  asking for any payment. Did that fact
  influence my report on his
  performance? I'm not entirely sure,
  but the interviewer probably sensed in
  my voice my sense of awe toward what
  this person had done for the Mises
  Institute. The interviewer told me
  that he had written down 15 different
  questions to ask me but that I had
  answered them all already in the
  course of my monologue, and that he
  was thrilled to hear all these
  specifics.

The person was offered the job. He had
  done a very wise thing; he had earned
  a devotee for life.

The harder the economic times, the
  more employers need to know what they
  are getting when they hire someone.
  The job applications pour in by the
  buckets, all padded with degrees and
  made to look as impressive as
  possible. It's all just paper. What
  matters today is what a person can do
  for a firm. The resume becomes pro
  forma but not decisive under these
  conditions. But for a former boss or
  manager to rave about you to a
  potential employer? That's worth
  everything.

What do you think? Has anyone here worked for free? If so, has it benefited you in any way? Why should(nt) you work for free (presuming you have the money from other means to keep you going)? Can you share your experience?

Me, I am taking a year out of college and haven't gotten a degree yet so that's probably why most of my job applications are getting ignored. So im thinking about working for free for the experience?

答:
People regularly offer to work for me for free. (Explaining their reasoning just sounds like bragging, so I've removed what I wrote. Let's just take that as a given, ok?). I ALWAYS refuse.

Even if I don't pay a salary, taking someone on costs me in both money and time. Here's what I write to people who email me making this offer:

We never take on volunteers: everyone
  who works for us is paid. Taking on a
  staff member involves expenses for
  hardware, software, office space,
  management time, training, and so on.
  Putting a new staff member on a
  project may slow that project. Before
  we take someone on we need to be
  convinced they will contribute at
  least as much as all those costs. If
  we are convinced of that, paying a
  salary is no problem. If we're not
  convinced, not paying a salary is no
  help.

I have to tell you what to do, check to see if you did it ok, fix it up if you didn't, train you on how to do it our way, pass on feedback (good or bad) from the client, and so on. An employer who won't take you on for a salary but will for free probably hasn't thought this through.

ContentLicense: CC BY-SA 2.5

Title: Working for free?


答:
The legal requirements are rather simple: You can clone the project as long as you keep to the terms of the original project's license and you don't use any trademarked names/logos/etc. without permission.

If it it your intention to revive the project (and release your modifications as a follow-up version), then common courtesy dictates that you make an effort to square this with the last maintainers of the project, even if the name is not trademarked.

Common sense dictates that, if you revive an existing project, that you make sure no confusion can arise as to which version people have in their hands, so don't restart your version numbering if possible.

As to how you organize the repository, that is completely up to you. For the outside world it either looks like a fork of the original project, or a revival where the maintainers chose to switch repositories at the same time (which is not uncommon).

Title: Fork dead SVN based project on GitHub

Body:
I previously asked this at stack overflow but it was closed, I believe because 'programmers' is a more appropriate venue for this question.

I have done some work on the SVN Importer project (Apache license), which appears to be effectively dead (no published changes in 5 years). I have a login to their svn server but do not have commit rights. At any rate, I'd like to convert this project to Git and push my own changes to GitHub. The GitHub site suggests the svn2git tool for converting svn projects to Git, so I was planning to convert the SVN repository to Git, add my changes, and then push this Git repository to GitHub.

I'm wondering, what are the legal requirements and common conventions of this process? Is it acceptable to clone the entire history of the project and move it to GitHub? Also, even though this is essentially a dead project, once I've translated the repository to Git should I put all of my commits onto a non master branch or is it acceptable to use master in this case?


问:
Why should I adopt MVC?
I decided to get my hands wet and got the YII framework for PHP.
I created my first application, then created new controller, model and view. Connected to database, got my record passed from controller to the view and printed the hello world.

I am confused now. If I have to do the same thing for each page, this seems like a nightmare to me. In each controller I have to do a lot of same operations - declare variables, and pass them to views. I also need to create models for each page and this is all confusing to me. In my idea the main goal of development is to avoid duplication, but what I see here is lots and lots of duplicated code.

Please advise and clarify. Maybe you could suggest a good reading about MVC and coding patterns and best practices in MVC. Because so far, it takes much more time to create a small site using MVC than using my own programming schema.

答:
First thing to consider is the development method, read on test driven, behaviour driven etc. That makes a big different.

Second consideration is the choice of the development system. MVC you started with works for a lot of systems but not for all. If you need to make a chatbox for example there are much better technologies available (think NodeJS etc.) which make life more easy.

MVC in general fits CRUD work and can be extended in many ways but that is the basic approach. Within MVC there are lots of choices more to make. For example: Consider a page with lots of widgets. How would you load every widget. Is that a separate call to the server, it is an internal request, it is a database record etc. Think before starting a project.

MVC: Your thought is wrong:

I also need to create models for each page and this is all confusing to me.

Read a bit more about MVC and about some basic development approaches. For example the feeling that you have to do a lot of duplicate work is not true. In can give you an example of how we quickly setup a concept application. This does not work for all applications but for basic CRUD it works well.

Database

First we build the database tables, so we structure the data in a correct way with the required relations.

Run scaffold

We use CakePHP but I expect it is also possible with YII: We set a variable which gives us a basic interface so we can test out and enter some data:

http://book.cakephp.org/2.0/en/controllers/scaffolding.html

So you get a full (standard) interface where you can work with. It is not customisable but gives a good feeling for the project data.

Generate the models, controllers, views

When satisfied we generate the code for the models, controllers, views (yes: we don't write that out all by hand constantly).

http://book.cakephp.org/2.0/en/console-and-shells/code-generation-with-bake.html

That will give the same look of the application as the scaffold but it generated all needed files.

Start development

From here on you start development. Based on your wishes you can start with some layout implementation but it is also possible to first start with some other parts. This is really the step where you start development.

Example tasks:

Remove or add controllers (controllers are not 1-on-1 linked to models!)

Implement some CSS or stylesheet to get the feeling of the application

Bake a Plugin to structure code separately (take out the most complex parts)

Implement model methods to get the right data and call them from the views

Add custom relations between models

Implement authentication (don't start with this most of the time).

etc.

So, the first steps are thinking about structure (don't try to get the whole application at once) but only the core piece like users, login and the activity (tasks for example).

Then make them good working and good looking. Restructure the standard code you got.

In general it works best to have separate controllers, models, views etc. You are right there is some duplication in it but it is not really duplication. The view action might look the same but is not. It sends other data, requests a specific additional model method etc.

Title: Why should I adopt MVC?


答:
Because so far, it takes much more time to create a small site using MVC than using my own programming schema.

This is the crucial point in your post and about patterns in general. Most of the people out there have the impression that every problem is best solved by a pattern or in your case by an arrangement of several patterns (MVC). Unfortunately this is not the truth since one can imagine instances of the same problem in an infinite number of contexts, which partially differ heavily in the sense of complexity.

Patterns are proven to solve specific problems in specific contexts, so as you noticed already, MVC is not a pattern for creating small sites/development projects, but to achieve lose coupling between your model, view and controller that they are relatively easy exchangeable. If you do not plan to change any of these in the future, MVC is probably not the best choice.

So as a conclusion you see that applying patterns is dependent from:

the problem

the context

quality requirements

Do the advantages predominate the disadvantages of it

In the case of MVC you have the following advantages:

View can easily be exchanged

effort estimations for adjustments are easier, because you can locate the change impact better

Your model can in most of the cases be tested independently from controller and view

and disadvantages:

effort for implementation increases

with model changes all views on it have to be kept consistent

big effort upfront to set up the basic framework (interfaces, events) in order to satisfy the specific requirements

Title: Why should I adopt MVC?

Body:
I decided to get my hands wet and got the YII framework for PHP.
I created my first application, then created new controller, model and view. Connected to database, got my record passed from controller to the view and printed the hello world.

I am confused now. If I have to do the same thing for each page, this seems like a nightmare to me. In each controller I have to do a lot of same operations - declare variables, and pass them to views. I also need to create models for each page and this is all confusing to me. In my idea the main goal of development is to avoid duplication, but what I see here is lots and lots of duplicated code.

Please advise and clarify. Maybe you could suggest a good reading about MVC and coding patterns and best practices in MVC. Because so far, it takes much more time to create a small site using MVC than using my own programming schema.


问:
How do you get users to rank their software enhancement needs?
I've inherited a legacy software system, and have been tasked with performing usability and system upgrades. While there's nothing bad with the system, from discussions with the users, there are "small" usabilty issues that need to be addressed.

At this stage I'm the lone developer on this system, and apart from testing I don't use the system at all, so its difficult for me to know what issues may exist or are percieved to exist. I'm going to have some time to speak with them all and discuss what they percieve to be good/bad or indifferent about the system.

Since its essentially just me for the time being my time is limit. So I was considering asking them to imagine that I'd only be able to do one change, have them all write privately what they'd want that one change to be, and then helping them rank those, but I'm hoping for other tips as well.

What techniques exist for getting users to explain their wants, needs, and requirements, while also having them rank them by importance or desirability?

答:
Recently, I had the "pleasure" of producing three separate prototype solutions for a problem our company has related to reports and presenting them to my bosses.  Each had its share of advantages and disadvantages in terms of development time, performance, scalability (time between start of project and being able to begin producing reports), ability for clients to modify these reports, etc.

My bosses are notoriously known for their inability to make decisions of this nature, so I wasn't expecting wondrous things.  So after explaining the advantages and disadvantages of each prototype, I asked which prototype they would have wanted.  They were undecided (surprise!).  My bosses were not going to commit to a decision without a suggestion from us as to which would be better (aka, you decide and if it fails, it'll get pinned on you).

So I decided to take a different approach:  I asked which of these priorities is more important (development time, performance, scalability, etc.).  Again, they were somehow able to evade point of my question by saying that all these priorities were important.

Finally, what finally worked was a strategy I adopted in my attempts to play off their inability to choose priorities.  I made a table which have priorities on the x-axis and prototypes on the y-axis.  For each priority and prototype, I gave it a number value from 1 to 10 based on how "ideal" it is in that respect, 10 obviously being the best (don't make 10 the worst for any particular aspect or you only risk to confuse yourself later).

Once you have this, you pick the strength of one prototype and you pit it against the strength of another prototype.  So in other words, you begin forming questions like:  "Which is more important?  Development time or performance?"  "Which is more important?  Performance or scalability?"

At this point, really stretch these questions to get them an idea of perspective:
"Which is more important?  We finish in 6 months time or that the client has to wait half as long for reports?"
"Which is more important?  The client has to wait half as long for reports or that we can begin to produce reports within the end of the week?"

At this point, my bosses could handle making decisions in bite-sized pieces and could give a good indication of which prototype they preferred based on this information.

The inverse works as well, pitting weakness against weakness:  "Which is worse?  It takes us longer than 6 months time to finish or that the client complains about the time it takes to create a report?"

In your case, we're talking about features, not priorties, but I think the same can apply here.  "Which would you prefer?  Making it available on iPhone or enhancing performance?"  Each question is easy to answer and can give you insight as to which features are more important.  In your case, I would assign 1 point for each feature chosen in this way in order to be able to effectively gauge one feature with respect to another.


问:
Contract Billing - How would you handle 'learning time'?
So you take a contract where you have solid experience with 75% of the technology necessary.  How do you handle your time to learn the other 25%?

Work it into the billing time?  Expose the 25% in the contract as 'research'?  Do the learning on my own time (not billed)?  Not take the contract (too large of an unknown for me and the customer)?

On the extreme end of this, I keep hearing a story about Mark Cuban (Dallas billionaire who started broadcast.com and sold it to Yahoo!) when he was at Indiana University.  Someone asked him if he could build a business app for them and he immediately said "Yes"... he had no idea how.  So he bought a book, stayed up nights, studied and coded... He finished it (I'm sure it was ugly), it worked and he kept going.

I'm not suggesting doing contracts this way (the stress!), but there's a middle ground.  What is it, and how would you (or would you?) bill for the unknown?

答:
If I do something for a client that I wouldn't be doing soon for other reasons, the client pays for it.

I find it works best to value myself in a manner like other professionals do, such as doctors, lawyers, and accountants. Everybody who's not explicitly "pro bono" pays for time and effort - and the only charity programming I do is on open source projects.

Some potential clients balk at paying for things like travel time, learning time, etc. I then explain that I'm not going to take time a different client would pay me for, and give it to them for free. Their reaction is a good litmus test of whether they'll be reasonable in the long run.

Like other contracting headaches, this has become much easier since I gave up on fixed-price contracts and went to strictly hourly.  My invoices include a day-by-day summary of work, and I'm not shy about remarking on research or learning. Also, I inform my clients beforehand of time-consuming research and get explicit approval before proceeding.


问:
How to minimize the usage of static variables and objects
I'm trying to implement this JavaFX code where I want to call remote Java class and pass boolean flag:

```<code>final CheckMenuItem toolbarSubMenuNavigation = new CheckMenuItem("Navigation");
    toolbarSubMenuNavigation.setOnAction(new EventHandler<ActionEvent>()
    {
        @Override
        public void handle(ActionEvent e)
        {

            //DataTabs.renderTab = toolbarSubMenuNavigation.isSelected();
            DataTabs.setRenderTab(toolbarSubMenuNavigation.isSelected());
            // call here the getter setter and send boolean flag
            System.out.println("subsystem1 #1 Enabled!");
        }
    });
</code>```

Java class which I want to call:

```<code>public class DataTabs
{
    private static boolean renderTab; // make members *private*
    private static TabPane tabPane;

    public static boolean isRenderTab()
    {
        return DataTabs.renderTab;
    }

    public static void setRenderTab(boolean renderTab)
    {
        DataTabs.renderTab = renderTab;
        tabPane.setVisible(renderTab);
    }

    // somewhere below
    // set visible the tab pane
    TabPane tabPane = DataTabs.tabPane = new TabPane();
    tabPane.setVisible(renderTab);
}
</code>```

This implementation works but I want to optimize it to use less static variables and objects. Can you tell me which sections of the code how can be optimized?

答:
remove all the instances of the static keyword from DataTabs (as well as any internal use of tje DataTabs.<member> prefix.

create an instance of the DataTabs class in your JavaFX code and make it accessible to those parts of the code that use it, either by passing it to constructors and keeping a reference to it, or by passing it as a method parameter.

Step 2 can be difficult and require you to restructure some code, but it's worth it. The problem with static stuff is that it reduces the cohesion of your code while introducing (and encouraging) hard-to-trace coupling, which overall leads to bad maintainability.

It may be annoying that something that used to be simple (just use that static stuff) now requires you to find an answer for the sometimes difficult question "how do I get that instance to where I need it?" - but that question is really "what parts is my code divided into, and how do they communicate?", and if you can't answer that, making any big change to your code will be difficult and error-prone.


答:
Why you won't use a simple framework like Laravel it's amazing trust me
And it's a modern framework and not complicated like Yii</p>

Title: Why should I adopt MVC?


问:
Strategies for removing register_globals from a file
I have a file (or rather, a list of about 100 files) in my website's repository that is still requiring the use of register_globals and other nastiness (like custom error reporting, etc) because the code is so bad, throws notices, and is 100% procedural with few subroutines.

We want to move to PHP 5.4 (and eventually 5.5) this year, but can't until we can port these files over, clean them up, etc. The average file length is about 1000 lines.

I've already cleaned up a few of the low-hanging fruit, however the job took almost an entire day for 2 300-500 line files. I am in a quagmire here (giggity).

Anyway, has anyone else dealt with this in the past? Are there any strategies besides tracing backwards through the code? Most static analysis tools don't look at code outside of functions - are there any that will look at the procedural code and help find at least some of the problems?

答:
This Operation Called refactoring

Refactoring is a disciplined technique for restructuring an existing body of code,
      altering its internal structure without changing its external behavior. Its heart is a

      series of small behavior preserving transformations. Each transformation (called a

      'refactoring') does little, but a sequence of transformations can produce a significant

      restructuring. Since each refactoring is small, it's less likely to go wrong. The system

      is also kept fully working after each small refactoring, reducing the chances that a

      system can get seriously broken during the restructuring.

Read about strategies for PHP Code Refactoring

And you actually have to do it your self there is no way to make the process faster
Just search about PHP Big Refactoring there is a strategies to keep the code clean
and might help you in your process.


问:
Avoiding the Anaemic Domain - How to decide what single responsibility a class has
Even after reading a bunch I'm still falling into the same trap. I have a class, usually an enity. I need to implement more than one, similar operations on this type. It feels wrong to (seemingly arbitrarily) choose one of these operations to belong inside the entity and push the others out to a separate class; I end up pushing all operations to service classes and am left with an anaemic domain.

As a crude example, imagine the typical Employee class with numeric properties to hold how many paid days the employee is entitled to for both sickness and holiday and a collection of days taken for each.

```<code>public class Employee
{
    public int PaidHolidayAllowance { get; set; }

    public int PaidSicknessAllowance { get; set; }

    public IEnumerable<Holiday> Holidays { get; set; }

    public IEnumerable<SickDays> SickDays { get; set; }
}
</code>```

I want two operations, one to calculate remaining holiday, another for remaining paid sick days. It seems strange to include say, CalculateRemaingHoliday() in the Employee class and bump CalculateRemainingPaidSick() to some PaidSicknessCalculator class. I would end up with a PaidSicknessCalculator and a RemainingHolidayCalculator and the anaemic Employee entity as seen above. The other alternative would be to put both operations in the Employee class and kick Single Responsibility to the curb. That doesn't make for particularly maintainable code.

I suppose the Employee class should have some initialisation/validation logic (not accepting negative alowances etc.) So maybe I just stick to basic initialisation and validation in the entities themselves and be happy with my separate calculator classes. Or maybe I should be asking myself if Anaemic Domain is actually causing me some tangible problems with my code.

答:
The other alternative would be to put both operations in the Employee class and kick Single Responsibility to the curb. That doesn't make for particularly maintainable code.

Why? It seems you have an excessively narrow concept what a "responsibility" means in the single responsibility principle. It certainly does not mean each class is only allowed to have a single method containing logic.

If the Employee class contains all the data those methods need, put both of them into the class. They're really a single responsibility: tracking paid free days. If the Employee class gets more complex, you might want to move that aspect into a class of its own - but one that represents a sub-entity of Employee, not a service class.

As a completely non-technical sidenote: I find the concept of a "PaidSicknessAllowance" to be really insane and broken.


答:
They both run, as has been pointed out in other answers.

Consider the canonical string concatenator while(*s1++ = *s2++); once s1 and s2 have been initialized. expr in this case is *s1++ = *s2++, and the body of the while loop is the empty statement ;. Remember that in C, the value of an assignment is the assigned value, so this could be rewritten as

```<code>while((*s1++ = *s2++) != 0)
{
}
</code>```

and have the same effect (with possible variations in performance depending on optimizations performed by the compiler).

Your confusion likely does stem from the fact that if and while are both followed either by a single statement, or a single statement block. When you put a semicolon statement terminator after the condition part, they become semantically equivalent to:

```<code>while(expr)
{
}
{
    /* do something */
}
</code>```

and

```<code>if(expr)
{
}
{
    /* do something */
}
</code>```

which are both perfectly valid code (you can have an empty block, or a block without an associated flow control statement) but probably don't do what you want.

If expr is constant, which is often the case when no constituent variables are modified inside the (empty) loop, then the while loop will either skip the empty statement block (if expr evaluates to false) or turn into an infinite loop executing the empty statement (if expr evaluates to true).

You can check this by giving expr a non-breaking side effect, such as logging a message or increment some internal static or member state variable:

```<code>while(log_message(), expr);
</code>```

and observe that the log_message() function gets called repeatedly.

Assuming that your code is something like:

```<code>int x = 0;
while (x < 1234);
{
    x++;
}
/* do more... */
</code>```

it should now be obvious why your program doesn't do what you expect, as the above is semantically equivalent to:

```<code>int x = 0;
while (x < 1234)
{
}
{
    x++;
}
/* do more... */
</code>```

Since x never gets modified inside the while loop's statement block (because it is empty), the expression x < 1234 will never evaluate to anything other than true, and hence you have an infinite loop. If the expression was instead x != 0 the empty statement block would instead be skipped over because the while loop's condition evaluates to false, you would reach the x++ and end up with x == 1 at the point of /* do more... */.

If the condition was instead something like ++x < 1234, then x would simply be incremented (++x evaluated), and the empty statement-block executed, until the condition is true, after which the while loop finishes and execution continues with a single pass through what you intended to do a number of times.

Title: Putting semicolons after while and if statements in C++

Body:
How come in C++ when you put:

```<code>while (expression);
</code>```

the while loop doesn't run no matter if the expression is true or not.

However if you put:

```<code>if (expression);
</code>```

the statement runs no matter if the expression is true or not.

It seems like they should both behave the same way.

Body:
They both run, as has been pointed out in other answers.

Consider the canonical string concatenator while(*s1++ = *s2++); once s1 and s2 have been initialized. expr in this case is *s1++ = *s2++, and the body of the while loop is the empty statement ;. Remember that in C, the value of an assignment is the assigned value, so this could be rewritten as

while((*s1++ = *s2++) != 0)
{
}

and have the same effect (with possible variations in performance depending on optimizations performed by the compiler).

Your confusion likely does stem from the fact that if and while are both followed either by a single statement, or a single statement block. When you put a semicolon statement terminator after the condition part, they become semantically equivalent to:

while(expr)
{
}
{
    /* do something */
}

and

if(expr)
{
}
{
    /* do something */
}

which are both perfectly valid code (you can have an empty block, or a block without an associated flow control statement) but probably don't do what you want.

If expr is constant, which is often the case when no constituent variables are modified inside the (empty) loop, then the while loop will either skip the empty statement block (if expr evaluates to false) or turn into an infinite loop executing the empty statement (if expr evaluates to true).

You can check this by giving expr a non-breaking side effect, such as logging a message or increment some internal static or member state variable:

while(log_message(), expr);

and observe that the log_message() function gets called repeatedly.

Assuming that your code is something like:

int x = 0;
while (x < 1234);
{
    x++;
}
/* do more... */

it should now be obvious why your program doesn't do what you expect, as the above is semantically equivalent to:

int x = 0;
while (x < 1234)
{
}
{
    x++;
}
/* do more... */

Since x never gets modified inside the while loop's statement block (because it is empty), the expression x < 1234 will never evaluate to anything other than true, and hence you have an infinite loop. If the expression was instead x != 0 the empty statement block would instead be skipped over because the while loop's condition evaluates to false, you would reach the x++ and end up with x == 1 at the point of /* do more... */.

If the condition was instead something like ++x < 1234, then x would simply be incremented (++x evaluated), and the empty statement-block executed, until the condition is true, after which the while loop finishes and execution continues with a single pass through what you intended to do a number of times.


问:
Mono is frequently used to say "Yes, .NET is cross-platform". How valid is that claim?
In What would you choose for your project between .NET and Java at this point in time? I say that I would consider the "Will you always deploy to Windows?" the single most important technical decision to make up front in a new web project, and if the answer is "no", I would recommend Java instead of .NET.

A very common counter-argument is that "If we ever want to run on Linux/OS X/Whatever, we'll just run Mono"1, which is a very compelling argument on the surface, but I don't agree for several reasons.

OpenJDK and all the vendor supplied JVM's have passed the official Sun TCK ensuring things work correctly.  I am not aware of Mono passing a Microsoft TCK.

Mono trails the .NET releases.  What .NET-level is currently fully supported?

Does all GUI elements (WinForms?) work correctly in Mono?

Businesses may not want to depend on Open Source frameworks as the official plan B.

I am aware that with the new governance of Java by Oracle, the future is unsafe, but e.g. IBM provides JDK's for many platforms, including Linux.  They are just not open sourced.

So, under which circumstances is Mono a valid business strategy for .NET-applications?

1Mark H summarized it as: "If the claim is that "I have a windows application written in .NET, it should run on mono", then not, it's not a valid claim - but Mono has made efforts to make porting such applications simpler."

答:
I have worked with Mono, and I would say it is as good as you can get with an alternate platform that is open-source, and not directly supported by Microsoft.  If you can be comfortable using an alternate open-source platform like Clojure or Scala, you could probably be comfortable with using Mono.

The level of .NET supported by Mono can always be found on the Mono Roadmap page.

Do all GUI elements work?  As far as I know, they do, although I haven't exhaustively tried every element.

Is Mono identical to .NET?  No.  I suspect there will be minor (and maybe major) tweaks required here and there.  You can't, at present, run the Entity Framework with it, for example.


答:
If you have several very similar operations, one approach is to make them a single parameterized operation, and another is to split them into a dedicated class and aggregate several instances.

parameterized pseudo-code example:

```<code>public class Employee
{
    public enum PaidAbsenceType { Vacation, Sickness, MPternity, Training, Travel };

    public void setAllowance(PaidAbsenceType type, int amount);
    public int getAllowance(PaidAbsenceType type);

    public void useAllowance(PaidAbsenceType type, int amount);
    public int getUsed(PaidAbsenceType type);
}
</code>```

aggregated pseudo-code example:

```<code>public class Employee
{
    public class PaidAbsence {
        public int allowance { get; set; }
        public int used { get; set; }
    }

    public PaidAbsence Vacation;
    public PaidAbsence Sickness;
    public PaidAbsence MPternity;
    public PaidAbsence Training;
    public PaidAbsence Travel;
}
</code>```

In both cases, the responsibility of the containing class is to aggregate these members, and if necessary to co-ordinate them.

Hard-coding two versions of the same logic into your class, unless there are actual behavioural differences, smells a bit odd.

Note that in either of the above cases, a single calculator would suffice (either passing the PaidAbsenceType of interest, or directly passing the appropriate PaidAbsence object) - again assuming the actual logic is the same.

Title: Avoiding the Anaemic Domain - How to decide what single responsibility a class has

Body:
Even after reading a bunch I'm still falling into the same trap. I have a class, usually an enity. I need to implement more than one, similar operations on this type. It feels wrong to (seemingly arbitrarily) choose one of these operations to belong inside the entity and push the others out to a separate class; I end up pushing all operations to service classes and am left with an anaemic domain.

As a crude example, imagine the typical Employee class with numeric properties to hold how many paid days the employee is entitled to for both sickness and holiday and a collection of days taken for each.

```<code>public class Employee
{
    public int PaidHolidayAllowance { get; set; }

    public int PaidSicknessAllowance { get; set; }

    public IEnumerable<Holiday> Holidays { get; set; }

    public IEnumerable<SickDays> SickDays { get; set; }
}
</code>```

I want two operations, one to calculate remaining holiday, another for remaining paid sick days. It seems strange to include say, CalculateRemaingHoliday() in the Employee class and bump CalculateRemainingPaidSick() to some PaidSicknessCalculator class. I would end up with a PaidSicknessCalculator and a RemainingHolidayCalculator and the anaemic Employee entity as seen above. The other alternative would be to put both operations in the Employee class and kick Single Responsibility to the curb. That doesn't make for particularly maintainable code.

I suppose the Employee class should have some initialisation/validation logic (not accepting negative alowances etc.) So maybe I just stick to basic initialisation and validation in the entities themselves and be happy with my separate calculator classes. Or maybe I should be asking myself if Anaemic Domain is actually causing me some tangible problems with my code.

Body:
If you have several very similar operations, one approach is to make them a single parameterized operation, and another is to split them into a dedicated class and aggregate several instances.

parameterized pseudo-code example:

public class Employee
{
    public enum PaidAbsenceType { Vacation, Sickness, MPternity, Training, Travel };

    public void setAllowance(PaidAbsenceType type, int amount);
    public int getAllowance(PaidAbsenceType type);

    public void useAllowance(PaidAbsenceType type, int amount);
    public int getUsed(PaidAbsenceType type);
}

aggregated pseudo-code example:

public class Employee
{
    public class PaidAbsence {
        public int allowance { get; set; }
        public int used { get; set; }
    }

    public PaidAbsence Vacation;
    public PaidAbsence Sickness;
    public PaidAbsence MPternity;
    public PaidAbsence Training;
    public PaidAbsence Travel;
}

In both cases, the responsibility of the containing class is to aggregate these members, and if necessary to co-ordinate them.

Hard-coding two versions of the same logic into your class, unless there are actual behavioural differences, smells a bit odd.

Note that in either of the above cases, a single calculator would suffice (either passing the PaidAbsenceType of interest, or directly passing the appropriate PaidAbsence object) - again assuming the actual logic is the same.


答: You must have read about Strategy pattern. By implementing this pattern, you are moving responsibility of calculating remaining days of vacation and sickness into separate object. But this object still remains related to the Employee. This could also allow you implement "Vacation" as single class, but have "SickDays" and "Holidays" properties of this class inside and employee. Thus reducing code and behavior duplication.</p>


问:
Would learning any natural language in particular further your programming career?
It seems apparent that English is the dominant international language for programming based on previous P.SE questions (though a highly upvoted comment correctly points out that asking a question like that on a predominantly English site will skew the results).

However, is there benefit in learning a foreign language for software development? For example, do the Chinese have completely different software tools, languages, technologies, etc? How about Japanese, Russian, and other non-latin based languages? Is there an entire world of software development languages, tools and so on that only exist in these other languages?

Or do people that know these languages use the tools and languages we know and love?

答:
No. You are not missing out on any study material.

As a native dutch speaker I can promise you that my development environment + most of my reference material is written in English. There are a few syllabi that are written in a different language, but I can assure you that there isn't any magic in any of them.

However, I can imagine that documentation on API's/webservices/projects or comments in source code can be in a different language then English. For that I would suggest you cover some of the most spoken languages: Spanish, Arabic and Chinese


答:
Unless you plan your career in place like China with self-sustaining market I'd bet that English is more than enough.  Hobbyist may use other languages but in every paid works I saw anywhere around English was the mandated language. For practical reasons too.

On the other hand knowing more languages can help your career in satellite activities. Many programs are localized, and both translation and testing requires people knowing the target language. It is a valuable "skill".   So if you have affinity for this, just go ahead and learn up.

Title: Would learning any natural language in particular further your programming career?

Body:
It seems apparent that English is the dominant international language for programming based on previous P.SE questions (though a highly upvoted comment correctly points out that asking a question like that on a predominantly English site will skew the results).

However, is there benefit in learning a foreign language for software development? For example, do the Chinese have completely different software tools, languages, technologies, etc? How about Japanese, Russian, and other non-latin based languages? Is there an entire world of software development languages, tools and so on that only exist in these other languages?

Or do people that know these languages use the tools and languages we know and love?


问:
Naming: objectAction or actionObject?
The question, Stored procedure Naming conventions?, and Joel's excellent Making Wrong Code Look Wrong article come closest to addressing my question, but I'm looking for a more general set of criteria to use in deciding how to name modules containing code (classes, objects, methods, functions, widgets, or whatever).

English (my only human language) is structured as action-object (i.e closeFile, openFile, saveFile) and since almost all computer languages are based on English, this is the most common convention.

However, in trying to keep related code close together and still be able to find things, I've found object-action (i.e. fileClose, fileOpen, fileSave) to be very attractive. Quite a number of non-English human languages follow this structure as well.

I doubt that one form is universally superior, but when should each be used in the pursuit of helping to make sure bad code looks bad?

答:
related code close together and still be able to find things

thats what packages are for. The difference between fileSave or saveFile is insignificant.

Title: Naming: objectAction or actionObject?


答:
actionObject sounds like a method you'd use in order do to some action with/in the object.

objectAction sounds like an aggregate of information, about the execution/result of the action performed on a object.

So I would generalize and say:

actionObject is appropriate for methods

objectAction, about information aggregation, like simple classes and structs.

One example of that would be:

ReportSecurityFlaw: seems like a method to inform a security flaw

SecurityFlawReport: seems like an object that represents data extracted from already stored Security Flaws

Title: Naming: objectAction or actionObject?

Body:
The question, Stored procedure Naming conventions?, and Joel's excellent Making Wrong Code Look Wrong article come closest to addressing my question, but I'm looking for a more general set of criteria to use in deciding how to name modules containing code (classes, objects, methods, functions, widgets, or whatever).

English (my only human language) is structured as action-object (i.e closeFile, openFile, saveFile) and since almost all computer languages are based on English, this is the most common convention.

However, in trying to keep related code close together and still be able to find things, I've found object-action (i.e. fileClose, fileOpen, fileSave) to be very attractive. Quite a number of non-English human languages follow this structure as well.

I doubt that one form is universally superior, but when should each be used in the pursuit of helping to make sure bad code looks bad?


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答:
I believe the best way to do it (in C#/.net anyway) is a combination of 2 and 6:

```<code>private int MyInteger { get; set; }
</code>```

There's theoretically no variable at all here, but it looks and acts like a private instance variable.  If we need to add some business logic to that value (it's a completely internal value, so we can do anything we want to it after all) then it's already 'propertyized' for us.  A hot steaming cup of win!

Body:
I believe the best way to do it (in C#/.net anyway) is a combination of 2 and 6:

private int MyInteger { get; set; }

There's theoretically no variable at all here, but it looks and acts like a private instance variable.  If we need to add some business logic to that value (it's a completely internal value, so we can do anything we want to it after all) then it's already 'propertyized' for us.  A hot steaming cup of win!


答:
First, you need to make a distinction between the Common Language Infrastructure (The open standard), and .NET (Microsoft's implementation of that standard). Mono is an implementation of the CLI, and has never claimed to be a "portable .NET". Also, the C# language is an open standard, and is not strictly tied to .NET.

I'm not aware whether Microsoft have any tool to validate that an implementation is compliant, but if they do, I'm pretty sure the mono guys have it, and use it.

Mono is trailing behind the .Net, but barely. Mono can run C# 4.0 code (current .NET version). Also, Microsoft have recently made all DLR code and libraries open source (under the Apache 2.0 license), which has enabled mono to make use of languages like IronPython, IronRuby, and F# has been made open source only last week. In addition, Microsoft are regularly releasing CTPs of upcoming features in .NET, which allows mono developers to keep up to date with current release versions.

There's a number of tools and extensions in .NET, for example, Code Contracts. These aren't always implemented fully in mono. (At present, I think there is a partial contract validator for Requires contracts). These aren't commonly used in .NET apps anyway, but if their popularity increased, so would the rate at which they get implemented in mono.

WinForms are not (entirely) portable. They are a .NET specific and not part of the CLI. The CLI does not specify any particular widget set. There are cross platform widget sets though (GTK# and Silverlight). If you were writing an application from the ground up with portability in mind, you would use one of these rather than Winforms/WPF. In addition, mono provides a thin wrapper for the Winforms API - which enables existing winforms apps to be ported more easily into GTK# (without entire rewrite).

Mono provides a tool, the Mono Migration Analyser (MoMA), which can take an existing .Net application and tell you about it's portability. (eg, identify unportable libraries that are used, P/Invokes etc).

For businesses that don't want to depend on Open Source - mono can be re-licensed. Ownership of code added to mono is handed over to novell, who can license it in alternative ways other than the usual LGPL license (which has very few restrictions anyway).

So as for the claim ".NET is portable", I think this can be a valid assertion if you are writing code from the ground up and are aware of the portability issues with the framework. If the claim is that "I have a windows application written in .NET, it should run on mono", then not, it's not a valid claim - but Mono has made efforts to make porting such applications simpler.

Title: Mono is frequently used to say "Yes, .NET is cross-platform". How valid is that claim?

Body:
In What would you choose for your project between .NET and Java at this point in time? I say that I would consider the "Will you always deploy to Windows?" the single most important technical decision to make up front in a new web project, and if the answer is "no", I would recommend Java instead of .NET.

A very common counter-argument is that "If we ever want to run on Linux/OS X/Whatever, we'll just run Mono"1, which is a very compelling argument on the surface, but I don't agree for several reasons.

OpenJDK and all the vendor supplied JVM's have passed the official Sun TCK ensuring things work correctly.  I am not aware of Mono passing a Microsoft TCK.

Mono trails the .NET releases.  What .NET-level is currently fully supported?

Does all GUI elements (WinForms?) work correctly in Mono?

Businesses may not want to depend on Open Source frameworks as the official plan B.

I am aware that with the new governance of Java by Oracle, the future is unsafe, but e.g. IBM provides JDK's for many platforms, including Linux.  They are just not open sourced.

So, under which circumstances is Mono a valid business strategy for .NET-applications?

1Mark H summarized it as: "If the claim is that "I have a windows application written in .NET, it should run on mono", then not, it's not a valid claim - but Mono has made efforts to make porting such applications simpler."