问:
Is macros support in a programming language considered harmful?
The first abuse that comes to my mind in C is:

```<code>#define if while
</code>```

But at the same time it is extremely handy and powerful when used correctly.

Something similar happens with Common Lisp macros.

Why doesn't all the programming languages support macros like this and what are the alternatives?

Is it they are considered harmful?

答:
I don't think there is a specific reason why they aren't supported in some languages, same as why some are case sensitive and some aren't. No real reason usually, just a decision that was made.

BUT the reason they aren't included definitely isn't security. The

```<code>#define X Y
</code>```

statement changes all X's to Y's at compile time. If you can change the #define statements, you could just copy/replace the source you were interested in changing and compile again.

Body:
I don't think there is a specific reason why they aren't supported in some languages, same as why some are case sensitive and some aren't. No real reason usually, just a decision that was made.

BUT the reason they aren't included definitely isn't security. The

#define X Y

statement changes all X's to Y's at compile time. If you can change the #define statements, you could just copy/replace the source you were interested in changing and compile again.


问:
What is the preferred way to store application configurations?
Most of the time, I store development application config in root directory of the project, like this:

```<code>app
|-- config.json
</code>```

But that doesn't seem to be the best approach, since this config ends up being stored in version control system - possibly resulting in leaked usernames, passwords and other sensitive stuff.

12 Factor App guide recommends dropping config files altogether and using environment variables for configuration setup:

... stores config in environment variables. Env vars are easy to change between deploys without changing any code; unlike config files, there is little chance of them being checked into the code repo accidentally; and unlike custom config files, or other config mechanisms such as Java System Properties, they are a language- and OS-agnostic standard.

That sounds really nice to me, but where does one store said environment variables, without checking them into source control? And what tools can I use to pass those variables to the app? There can be dozens of config options, and typing them by hand each time you launch the app is not nice - so they have to be stored in some kind of file somewhere. Said file thus will end up in source control, and we return back to where we started.

Is there some universally accepted way of handling configuration options, that doesn't have the risk of storing local configuration in source control?

答:
In examining problems and possible solutions, it helps me to use a method popularized by Jeff Atwood: If God were to create a way to store sensitive configuration information, how would he do it?

Well, he would know who needs configuration information and only give it to those people, and the information would never be able to be accessed by anyone else.

The first part should already be taken care of: your source control system should be authenticating users. And this approach is also given validity according to #10 in Troy Hunt's 10 Commandments of Source Control, "dependencies need to be in source control".

But how to keep it secure if it is leaked? Well, it doesn't need to be stored there in plain text! Use encryption. In .NET, there are steps you can take to encrypt connection string data in your config files. You would have to find the equivalent methods to do so with your particular technology of choice.

ContentLicense: CC BY-SA 3.0


问:
Make classes immutable or compatible with standard containers
Making types immutable is often desireable, especially for multi-threaded applications. There's no need to worry about concurrent access and no need for any synchronization. The standard containers require the contained objects to be assignable, however, so they don't work with immutable types.

How should I strike a balance between wanting immutable types and wanting to stash them in standard containers? What I could:

provide an assignment operator and stop worrying about immutability. Either add synchronization or document that object assignment isn't thread-safe.

live with the fact that the types can't go directly into containers and wrap them in std::unique_ptr/std::shared_ptr when required.

What are the tradeoffs involved and which solution should I prefer for what types of objects? Should I strive to always make my objects container-compatible or should I only do that when I anticipate need for it? Should I strive to always make my objects immutable or only when I see concrete benefit from it?

答:
Typical C++ is more about values that are copied than about making immutable objects that are shared. Separation instead of immutability. Try to keep the different threads' data separate.

If you do want immutable shared data, you can always make a shared_ptr<T>, fill the object there with data, then hand out shared_ptr<const T> references to it. Or use something like Adobe's copy_on_write.

So make your classes mutable and have them behave as proper values.

ContentLicense: CC BY-SA 4.0


问:
c# class generation/architecture for json rest service
I want to consume part of the Steam WebAPI, it's a simple Rest Service but it produces some complex json.
I thought about using the Newtonsoft Json.Net Library generate my c# objects.

Whats the best way to get the needed Classes to easily use the Library?

I thought about using http://json2csharp.com/ to generate the needed Classes, but of course these don't follow any naming conventions. But as i save the data into a database anyway I have to convert it to the EF-Classes anyway.

I could write my own classes and use annotations, would result in nicer code but a little bit more work.

Whats the best practice creating the c# infrastructure for a external json service?

答:
I think you have two options here.

Best practice. Create objects which match the json returned by/sent to the API and serialize/deserialze these objects when you make calls or receive responses. Hide the JSON implementation from the consumer of this 'Client Library'

These objects could be created with a tool, or hand crafted. Either way you are probably going to have some custom code to deal with the edge cases of converting JSON to .net datatypes and classes

Additionally, you'll need to spend alot of time creating and maintaining these objects.

Quick 'n' Dirty. rather than serializing to objects, simply parse the JSON and query the values out of the responses that you need to use with XPath or similar.

This will yield a partial implementation of a Client, but if you only want a sub set of the features may well be much faster to implement


问:
What are the benefits of a device driver when I can access the I/O registers directly?
I was interested in what modern, C-based, Linux device driver development looked like, and so I took a good gander at this excellent article.

I didn't read every single line, but perused the majority of it, and my take away is this: writing device drivers for Linux seems like an incredibly painful process. Now that's my opinion, and I'm sure many Linux/C gurus out there would disagree, but there's one thing that I just can't wrap my head around here.

Every CPU/MCU exposes a C library that defines I/O registers, ports, etc. for accessing (both reads and writes) every single pin on the chip. On AVR controllers, for instance, there is <avr/io.h>. For ARM chips there is CMSIS.

So my question is this:

Why would I go to all the 'trouble' (more work) of following the guidelines in that article and building a proper device driver in Linux, when I could just write a C library that uses one of these processor-provided I/O registry accessors (again, avr/io.h, CMSIS, etc.) to access all the pins on the chip (which seems like less work)?

I'm sure there's a reason: I'm just not seeing it. What is gained by using a proper device driver? What is lost by not using one and just using one of these libs directly?

答:
Asking why microcontrollers like the AVR family let you twiddle the pins directly when an operating system like Linux requires device drivers is an apples-to-suspension-bridges comparison.

Microcontrollers are typically single-threaded free-for-alls with no supervisor (OS) and all code has full access to memory, I/O and anything else the chip offers.  This means that if one part of the application sets GPIO pin 3 high and needs to see that it stays that way, there's nothing that prevents some other part of the code from setting it low again.  The developer is responsible for putting those kinds of interlocks into place.  There's also no notion of devices: the MCU has a set of registers that control I/O that's the same on every copy of the chip and that's all there is.  If you want to run your program on a different chip in the same family with different I/O, you're likely going to have to rewrite parts of it or, at the very least, recompile it with chip-specific headers or libraries.

General-purpose processors like the one in your desktop PC don't have the I/O features built in, opting instead to communicate with external peripherals whose registers are mapped somewhere in memory.  The model is the same, though.  If you plop an x86 CPU into a board where you know the I/O mappings, it's entirely possible to write AVR-style programs that do their own I/O, but you're going to be doing it on bare metal without any of the facilities an operating system provides.

A lot of software was done this way, but at some point in history, it became apparent that the model wasn't going to scale.  People wanted to write programs to run on a given processor without having to fuss with building a separate version for each combination of peripherals.  This spawned operating systems, which let a program say things like "send the character C across serial port 2" using a standard software interface.  The code behind that standard interface was built up for the specific set of hardware on that system and knew that serial port 2 was a Brand X UART mapped at address 1234.  In microcomputing, this kind of thing became most evident with the appearance of the CP/M operating system in the 1970s.  Vendors selling computers would provide a version of the OS with custom drivers for their specific hardware.  Do-it-your-selfers had to patch up generic versions by hand to work with what they had.  The result was that they all ended up with systems that could run off-the-shelf versions of software without having to modify it.

Modern operating systems do pretty much the same thing but with a much higher level of sophistication.  Systems (PC-style and even many embedded ones) are built around I/O architectures that are enumerable and dynamic, meaning that the software can figure out what's present, assign it a memory mapping and use the right functions to communicate with it.  Along with that comes driver infrastructure that lets hardware developers leverage all of that sophistication without having to re-invent it each time and without risk that driver A was going to conflict with something driver B is doing.

If you decide to try going the poke-the-device-directly route on a full-blown operating system like Linux, the first question you'll ask is how a userland process gains access to the memory area where the device's registers are mapped.  The answer ("you can't") is what brings up the other reason: multi-user, multi-tasking operating systems don't trust user programs to be well-behaved.  They're designed to protect the system from harm and the programs running on the system from each other.  Making this happen brings with it a complex model of interlocks and permissions, all of which contribute to whether or not a program can ask a device driver to do something on its behalf.  The device driver code put into the kernel is given a much greater amount of trust because, presumably, those who wrote it did so carefully.

The functions you put into a device driver for most flavors of Unix are just the essentials (load, unload, open, close, read, write, ioctl) and are called at the end of a very long chain of decision making.  If a process wants to write to a serial port, the driver code isn't called until the OS is sure there's a driver present and functioning for that device, the process has permission to use the device and that the port has been opened by that process.

This, at long last, is why you write a device driver:  The amount of code you have to develop for a device driver is minuscule compared to the amount of sophistication the rest of the OS provides to go with it.

Really, it isn't painful.  It's just unfamiliar.  Once you've done a couple, you'll wonder why you were making such a fuss about it.  (And trust me, it's a lot less work now than it was 25 years ago.)


问:
Does it always make sense to "program to an interface" in Java?
I've seen the discussion at this question regarding how a class that implements from an interface would be instantiated. In my case, I'm writing a very small program in Java that uses an instance of TreeMap, and according to everyone's opinion there, it should be instantiated like:

```<code>Map<X> map = new TreeMap<X>();
</code>```

In my program, I'm calling the function map.pollFirstEntry(), which is not declared in the Map interface (and a couple others who are present in the Map interface too). I've managed to do this by casting to a TreeMap<X> everywhere I call this method like:

```<code>someEntry = ((TreeMap<X>) map).pollFirstEntry();
</code>```

I understand the advantages of the initialization guidelines as described above for large programs, however for a very small program where this object would not be passed to other methods, I would think it is unnecessary. Still, I'm writing this sample code as part of a job application, and I don't want my code to look badly nor cluttered. What would be the most elegant solution?

EDIT: I would like to point out that I'm more interested in the broad good coding practices instead of the application of the specific function TreeMap. As some of the answers have already pointed out (and I've marked as answered the first one to do so), the higher abstraction level possible should be used, without losing functionality.

答:
The point behind coding to an interface rather than an implementation is to avoid the leaking of implementation details which would otherwise constrain your program.

Consider the situation where the original version of your code used a HashMap and exposed that.

private HashMap foo = new HashMap();
public HashMap getFoo() { return foo; }  // This is bad, don't do this.
```

<p>This means that any change to <code>getFoo()</code> is a breaking API change and would make people using it unhappy.  If all that you are guaranteeing is that <code>foo</code> is a Map, you should return that instead.</p>

<pre class="lang-java prettyprint-override"><code>private Map foo = new HashMap();
public Map getFoo() { return foo; }
</code>```

This gives you the flexibility to change how things work inside your code.  You realize that foo actually needs to be a Map that returns back things in a particular order.

private NavigableMap foo = new TreeMap();
public Map getFoo() { return foo; }
private void doBar() { ... foo.lastEntry(); ... }
```

<p>And that doesn't break anything for the rest of the code.</p>

<p>You can later strengthen the contract the class gives without breaking anything either.</p>

<pre class="lang-java prettyprint-override"><code>private NavigableMap foo = new TreeMap();
public NavigableMap getFoo() { return foo; }
private void doBar() { ... foo.lastEntry(); ... }
</code>```

This delves into the Liskov substitution principle

Substitutability is a principle in object-oriented programming. It states that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.).

Since NavigableMap is a subtype of Map, this substitution can be done without altering the program.

Exposing the implementation types makes it difficult to change how the program works internally when a change needs to be made. This is a painful process and many times creates ugly workarounds that only serve to inflict more pain on the coder later (I'm looking at you previous coder who kept shuffling data between a LinkedHashMap and a TreeMap for some reason - trust me, whenever I see your name in svn blame I worry).

You would still want to avoid leaking implementation types. For example, you may wish to implement ConcurrentSkipListMap instead because of some performance characteristics or you just like the java.util.concurrent.ConcurrentSkipListMap rather than java.util.TreeMap in the import statements or whatever.

OwnerDisplayName: jimijazz

Body:
The point behind coding to an interface rather than an implementation is to avoid the leaking of implementation details which would otherwise constrain your program.

Consider the situation where the original version of your code used a HashMap and exposed that.

private HashMap foo = new HashMap();
public HashMap getFoo() { return foo; }  // This is bad, don't do this.

This means that any change to getFoo() is a breaking API change and would make people using it unhappy.  If all that you are guaranteeing is that foo is a Map, you should return that instead.

private Map foo = new HashMap();
public Map getFoo() { return foo; }

This gives you the flexibility to change how things work inside your code.  You realize that foo actually needs to be a Map that returns back things in a particular order.

private NavigableMap foo = new TreeMap();
public Map getFoo() { return foo; }
private void doBar() { ... foo.lastEntry(); ... }

And that doesn't break anything for the rest of the code.

You can later strengthen the contract the class gives without breaking anything either.

private NavigableMap foo = new TreeMap();
public NavigableMap getFoo() { return foo; }
private void doBar() { ... foo.lastEntry(); ... }

This delves into the Liskov substitution principle

Substitutability is a principle in object-oriented programming. It states that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.).

Since NavigableMap is a subtype of Map, this substitution can be done without altering the program.

Exposing the implementation types makes it difficult to change how the program works internally when a change needs to be made. This is a painful process and many times creates ugly workarounds that only serve to inflict more pain on the coder later (I'm looking at you previous coder who kept shuffling data between a LinkedHashMap and a TreeMap for some reason - trust me, whenever I see your name in svn blame I worry).

You would still want to avoid leaking implementation types. For example, you may wish to implement ConcurrentSkipListMap instead because of some performance characteristics or you just like the java.util.concurrent.ConcurrentSkipListMap rather than java.util.TreeMap in the import statements or whatever.


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
I did read somewhere that the authors of some book wanted their code formatted like this:

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

But space constraints from their publisher meant that they had to use this:

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

Now I don't know whether that's true (as I can't find it any more), but the latter style is very prevalent in books.

On a personal level I prefer the brackets on a separate line as:

a) they indicate a new scope

b) it's easier to spot when you've got a mismatch (though this is less of an issue in an IDE that highlights errors for you).

Body:
I did read somewhere that the authors of some book wanted their code formatted like this:

if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}

But space constraints from their publisher meant that they had to use this:

if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}

Now I don't know whether that's true (as I can't find it any more), but the latter style is very prevalent in books.

On a personal level I prefer the brackets on a separate line as:

a) they indicate a new scope

b) it's easier to spot when you've got a mismatch (though this is less of an issue in an IDE that highlights errors for you).

ContentLicense: CC BY-SA 2.5


问:
Changing the Garbage Collector on your JVM
My understanding is that the JVM specification only defines the behavior of a garbage collector, but does not provide implementation details. This means it is up to the JVM implementation to build the garbage collector out.

There appears to be 3rd party garbage collectors such as the Azul Pauseless GC. To me, this implies that my JVM implementation, say HotSpot or JRockit, is configured by default to use its own built-in garbage collector. But, perhaps through configuration, I could use a 3rd party garbage collector (such as the one by Azul, or another).

So I ask: How does one "swap out" the built-in garbage collector with another one? If the answer is JVM implementation-specific, let's assume HotSpot.

答:
Garbage collectors and code generators (in particular the JIT engine inside any industrial JVM) are tightly related, in particular because most GCs are generational, and need some write barrier (which is a constraint on the code generator), and also depend upon multithreading issues. And the GC is also (obviously) tied to object allocations which is JVM specific. Read the GC handbook for more explanations.

Generational GCs are handling differently young objects (which usually die quickly) from older ones. They often copy the live young objects in some older memory region, then the entire birth region can be released. But they need to track any old object which has been modified to hold a pointer to the newest region. This is a write barrier and needs special code to be emitted by the JIT engine for field modifications of (young) object.

BTW, the Azul PGC link you gave has a video explaining all that!

So in practice you cannot easily plug another GC inside your JVM without patching significantly the JVM code.


问:
How Do I Create A Module* For A Class That Relies On Another Module?
*I'm using "Module" to mean some extension of a class, either through inheritance or composition.

Say I have one of the following declarations of an Entity:

```<code>using EUnit = int;

class Entity : /*With inheritance*/
        Positional<EUnit> {

public:

    Entity();

};
</code>```

or

```<code>class Entity { /*With composition*/
    Position<EUnit> pos; //Same as "Positional", but renamed

public:

    Entity();

};
</code>```

And the declaration of Position/Positional:

```<code>template <class T>
class Positional {
    T xPos;
    T yPos;

public:
    Positional();
    Positional(T x, T y);

    void moveTo(T x, T y);
    void moveBy(T xOff, T yOff);

    T getX() const;
    T getY() const;

};
</code>```

What if I want to create a class called RandomWalk that can be used to cause the Entity (or any other Positional class) to randomly move to a location?

Going the inheritance route, I thought of having RandomWalk inherit from Positional so it has access to a position to act on. If I then set up Entity like:

```<code>class Entity :
        Positional<EUnit>, virtual RandomWalk<EUnit> { ...
</code>```

RandomWalk now how access to Entity's position, but it involved "diamond inheritance". I'm virtually inheriting RandomWalk, so only one version of a Positional should exist, but multiple inheritance like this still seems to be frowned upon from what I've read.

That leaves me with composition. The only way I could think of giving RandomWalk access to the Entity's position this way was to do something like pass a reference/pointer to the Entity's Positional to the RandomWalk constructor. Using pointers for something like this seems like overkill though.

And now I'm out of ideas, and I'd like suggestions/advice (or just general comments on the problem).

I know I could just directly add a randomWalk function to Entity, but I'm looking at this through the perspective of re-use.

And yes, RandomWalk is kind of a dumb use-case, but I'm sure this problem (or a similar one) occurs in the real world.

答:
Some alternatives:

Have RandomWalk inherit from Positional.  With this definition, a RandomWalk is a Positional entity which can walk randomly or to specific locations.  I don't really like this approach; it leaves no way to handle arbitrary permutations walkers (e.g., RandomWalk, SquareDanceWalk, etc.).

Have RandomWalk contain a "WalkRandomly" function which takes in a Positional parameter.  Entities which need need random movement can call this function.  If necessary, an abstract class ICanRandomWalk could be inherited from (diamond inheritance is fine if no more than one base class contains an implementation), with the ICanRandomWalk being implemented as calling a member of a private instance of RandomWalk.


问:
A little confused with virtual functions
Please see the following code:

```<code>#include<iostream.h>
#include<string.h>
class father
{
    char fname[20];
    public:
        father()
        {
            strcpy(fname,"eshwarappa");
        }
        void show()
        {
            cout<<"Father's name = "<<fname<<endl;
        }
};
class son: public father
{
    char sname[20];
    public:
        son()
        {
            strcpy(sname,"yajurappa");
        }
        void show()
        {
            cout<<"Son's name = "<<sname<<endl;
        }
};
int main()
{
    father *bp;
    father f;
    bp=&f;
    bp->show();
    son s;
    bp=&s;      //Valid assignment
    bp->show();
}
</code>```

OUTPUT:

```<code>Father's name = eshwarappa
Father's name = eshwarappa
</code>```

Why is it that the base class pointer bp makes a call to base class' method show() even when it contains the address of the object of derived class son.

P.S. I know this can be solved by making the function show() as virtual in the base class but I just want to know why it doesn't work this way.

答:
Because making a function virtual incurs a non-zero runtime cost. Part of the philosophy of C++ is "you only pay for what you use"; i.e. you don't pay the cost of a virtual function unless you've explicitly asked for it by writing virtual in your code.

As for why it incurs that runtime cost, the short answer is that a father pointer by itself does not say whether it's actually pointing to a father or a son or some other derived class. The only way to know what type it's actually pointing to at runtime is for every father object to carry around an extra piece of data that identifies what type it is. That means objects with virtual methods take up (slightly) more memory.

In most implementations that extra piece of data is a single pointer to a "vtable". If you gave father a virtual method, then every father object that gets created at runtime will have a pointer to the father vtable, and every son object that gets created at runtime will have a pointer to the son vtable. Assuming show() is the only virtual method, both vtables will contain a single function pointer to their respective implementations of show(). That means dereferencing a few pointers every single time you call show(), which means virtual methods can be (slightly) slower than non-virtual methods.

You might argue that one extra pointer on every object and a little more pointer chasing is not a significant cost. That depends on the class and the application. If you're doing scientific computations with 1000x1000 matrices, you might not want an extra 4 bytes on every single matrix/vector/etc object and an extra couple dereferences on every add/multiply/divide operation. C++ lets you decide exactly when that cost does and doesn't matter.

On the other hand, some other OOP languages (typically ones with garbage collection) have chosen to make everything "virtual by default." It's a trade-off.


问:
Is there a difference between SQL INSERT patterns
SQL inserts are usually documented like so:

```<code>INSERT TableName (Column1, Column2) VALUES ('Value1', 'Value2')
</code>```

However, in TSQL it's also possible to write the (seemingly) same statement like so:

```<code>INSERT TableName (Column1, Column2) SELECT 'Value1', 'Value2'
</code>```

Explain Plan seems to think they're identical.

Are they? Is there any hidden difference or any argument for doing it the INSERT () Values () way?

答:
The difference is not hidden - simply your examples don't illustrate it :-)

Using INSERT TableName (Column1, Column2) VALUES ... syntax limits your options to values lists (as in your examples; note that the value list should be enclosed in parentheses.) or return value of stored procedure e.g.

```<code>INSERT INTO Cities (Location) VALUES ( dbo.CreateNewPoint(x, y) );
</code>```

Using INSERT TableName (Column1, Column2) SELECT ... syntax is much more powerful. In addition to cases above you can insert almost any result of SELECT statement if only it matches target columns types.

In particular you can insert data from other tables, mix values from multiple tables with constant values etc. For example:

```<code>INSERT INTO TargetTable (name, ColumnA, ColumnB, Sum)
SELECT 'Programmers', T1.Value, T2.Value, SUM(T1.Value, T2.Value)
FROM SourceTable1 T1, SourceTable2 T2 WHERE T1.Value > 0 AND T2.Value > 0;
</code>```

Please note that INTO is an optional keyword that can be used between INSERT and the target table.

Reference: https://msdn.microsoft.com/en-us/library/ms174335.aspx

Body:
The difference is not hidden - simply your examples don't illustrate it :-)

Using INSERT TableName (Column1, Column2) VALUES ... syntax limits your options to values lists (as in your examples; note that the value list should be enclosed in parentheses.) or return value of stored procedure e.g.

INSERT INTO Cities (Location) VALUES ( dbo.CreateNewPoint(x, y) );

Using INSERT TableName (Column1, Column2) SELECT ... syntax is much more powerful. In addition to cases above you can insert almost any result of SELECT statement if only it matches target columns types.

In particular you can insert data from other tables, mix values from multiple tables with constant values etc. For example:

INSERT INTO TargetTable (name, ColumnA, ColumnB, Sum)
SELECT 'Programmers', T1.Value, T2.Value, SUM(T1.Value, T2.Value)
FROM SourceTable1 T1, SourceTable2 T2 WHERE T1.Value > 0 AND T2.Value > 0;

Please note that INTO is an optional keyword that can be used between INSERT and the target table.

Reference: https://msdn.microsoft.com/en-us/library/ms174335.aspx


问:
Design consideration on JSON schema for an API
I have an API endpoint that retrieve data from 3 SQL tables on the server-side. At the moment, I do a SELECT with joins, consolidate/reorganize the selected data based on a JSON schema, and then send the JSON to client. The point here is that, almost none of the data values is changed, only their structure is transformed from the SQL schema to the JSON schema.

On the client side, I also maintain 3 SQL tables that are very similar to those on the server. At the moment, I parse the JSON, re-transform the data, and save them into those tables.

I wonder, on the server-side, whether we could simply dump the the data from each of the 3 tables into JSON without any transformation, so that both server and client can save doing any transformation/restructuring, considering the tables on both sides (more or less) match in schema.

The (only?) benefit of this idea is obvious, but I do wonder if there is any serious drawback. For examples:

We lose data abstraction on the server-side.

We sort of rely on the close matching between schemas of tables on both sides, which probably makes it harder in the future to change/add columns to those tables on either side.

This may be OK for an internal API that is consumed by clients I control, but probably is not so great for external clients/developers in the future.

So far I can only come up with the above, and I am not 100% sure how severe each of the problems is.

答:
Your JSON data should contain the information that the user of the API expects. Which should mostly mean that it is documented and gives the information that is documented. The schema should not depend on your database design. And of course if your database design changes, the API cannot change. So basing your API on your current database design means that after a change you have to translate the existing data into data based on the old database design, which is a pain. </p>

<p>What I think is very useful is when there is no redundancy whatsoever. Because every time there is redundant information, the consumer has to worry about what to do if the redundant information isn't consistent. </p>

Body:
Your JSON data should contain the information that the user of the API expects. Which should mostly mean that it is documented and gives the information that is documented. The schema should not depend on your database design. And of course if your database design changes, the API cannot change. So basing your API on your current database design means that after a change you have to translate the existing data into data based on the old database design, which is a pain.

What I think is very useful is when there is no redundancy whatsoever. Because every time there is redundant information, the consumer has to worry about what to do if the redundant information isn't consistent.


问:
Failover for High Frequency Jobs
I have a job that runs at a fairly high frequency (~1x every second).

This job needs to be executed constantly as long as the web app is running. However, I really only want 1 instance of the job running at a time.

Currently, I just fire up a thread that performs the job in the background, sleeping for ~800ms each loop. That causes a problem when I want redundancy, because the thread starts up as part of the app.

I know I can do something simple, like add a table in a database and have a "primary" and "secondary" server lock the record, track who's in charge, etc. But it seems a bit ugly, so I was curious if anyone had experience with a similar situation, and what solution you ended up using?

答:
I see this ultimately as a problem of interprocess communication (IPC). You have one process generating work and then another one consuming the tasks and doing the work.

This falls into a classic producer and consumer layout (tutorial from RabittMQ).

The nice thing about message queues is that they guarantee the contract of "this message is guaranteed to be delivered to one, and only one consumer (if it is consumed at all)."  This simplifies the IPC as you don't need to worry about the semaphores and shared memory segments or other channels of communication.

Beyond this, you can start to get fancy. You can have two consumers running - though only one will grab the message indicating the task from the queue.  You could have the producer pumping out single "consider this" tasks as fast as it can (up to a certain queue fullness) and the consumers processing them once every 800ms - though the exact implementation depends on the problem.

The message queue has an advantage over databases in that its what its designed to do.  You can do similar things via mechanisms in the database, but then you will start worrying about transactions and locks.  Some databases have gone on to take additional abilities of message queueing as part of the core set of features as described in this post, but a message queue has a general advantage over databases being able to handle more concurrent messages, blocking until you get a message, avoiding deadlocks and races.

How one designs a solution using a message queue for this specific problem is still a bit up in the air as there are many aspects of the domain that are left undescribed, but in general the message queue should be one of the first tools that comes to mind when one starts thinking about how to send messages between one or more processes.

Title: Failover for High Frequency Jobs


问:
What's the idea behind naming classes with "Info" suffix, for example: "SomeClass" and "SomeClassInfo"?
I'm working in a project which deals with physical devices, and I've been confused as how to properly name some classes in this project.

Considering the actual devices (sensors and receivers) are one thing, and their representation in software is another, I am thinking about naming some classes with the "Info" suffix name pattern.

For example, while a Sensor would be a class to represent the actual sensor (when it is actually connected to some working device), SensorInfo would be used to represent only the characteristics of such sensor. For example, upon file save, I would serialize a SensorInfo to the file header, instead of serializing a Sensor, which sort of wouldn't even make sense.

But now I am confused, because there is a middleground on objects' lifecycle where I cannot decide if I should use one or another, or how to get one from another, or even whether both variants should actually be collapsed to only one class.

Also, the all too common example Employee class obviously is just a representation of the real person, but nobody would suggest to name the class EmployeeInfo instead, as far as I know.

The language I am working with is .NET, and this naming pattern seems to be common throughout the framework, for exemple with these classes:

Directory and DirectoryInfo classes;

File and FileInfo classes;

ConnectionInfoclass (with no correspondent Connection class);

DeviceInfo class (with no correspondent Device class);

So my question is: is there a common rationale about using this naming pattern? Are there cases where it makes sense to have pairs of names (Thing and ThingInfo) and other cases where there should only exist the ThingInfo class, or the Thing class, without its counterpart?

答:
ThingInfo can serve as a great read only Proxy for the Thing.

see http://www.dofactory.com/net/proxy-design-pattern

Proxy: "Provide a surrogate or placeholder for another object to control access to it."

Typically the ThingInfo will have public properties with no setters.  These classes and the methods on the class are safe to use and will not commit any changes to the backing data, the object, or any other objects.  No state changes or other side effects will occur.  These can be used for reporting and web services or anywhere that you need information about the object but want to limit access to the actual object itself.

Use the ThingInfo whenever possible and limit the use of the actual Thing to the times you actually need to change the Thing object.  It makes reading and debugging considerably faster when you get used to using this pattern.


答:
I can recommend the Hangfire as a solution. Key highlights for your case (extracted from the web site),

Persistent

Background jobs are saved into a persistent storage – SQL Server, Redis, PostgreSQL, MongoDB and others. You can safely restart your application and use Hangfire with ASP.NET without worrying about application pool recycles.

Reliable

Once a background job created and placed into a storage without exceptions, Hangfire takes the responsibility to process it at least once. You are free to throw unhandled exceptions or kill your application – background jobs will be re-tried automatically.

Distributed

Background method calls and their arguments are serialized and may overcome the process boundaries. You can use Hangfire on different machines to get more processing power with no configuration – synchronization is performed automatically.

Title: Failover for High Frequency Jobs

Body:
I have a job that runs at a fairly high frequency (~1x every second).

This job needs to be executed constantly as long as the web app is running. However, I really only want 1 instance of the job running at a time.

Currently, I just fire up a thread that performs the job in the background, sleeping for ~800ms each loop. That causes a problem when I want redundancy, because the thread starts up as part of the app.

I know I can do something simple, like add a table in a database and have a "primary" and "secondary" server lock the record, track who's in charge, etc. But it seems a bit ugly, so I was curious if anyone had experience with a similar situation, and what solution you ended up using?


问:
When developing an MVC framework, how should I be using Knockout.js?
I'm currently using the Laravel PHP MVC Framework to develop a web application; and it's going along quite nicely. I'm very comfortable with the expectations of the framework and how my application should be structured. This is not a problem.

My problem is with the front end, UI/interaction side. I am using Knockout.js & jQuery to encapsulate a lot of front end UI & data interaction; and I'm not sure I'm using the former correctly.

Knockout.js prides itself on binding elements in the DOM to event handlers and functions in a Javascript "ViewModel" layer, allowing you to send requests away to the server via AJAX to fetch new data, add templates of HTML to your current DOM, and alter what is present on your page. I understand this within a single page context. By that, I mean, if I have a discrete page where I need user & data interaction, I will probably end up creating a SomeSinglePageViewModel.js file to handle this.

What I am not to sure about is how, or even whether, Knockout.js view models should be used across/between pages. Right now, I'm creating a ViewModel for nearly every CRUD operation and page in my application. Is this correct design?

For example, I'll have a CreateUserViewModel.js for my /User/Signup page, and a EditUserViewModel.js for my /User/Edit page; and a `HomePageViewModel.js for the application landing page to control that UI. Is it correct to follow a "one viewmodel per page" philosophy? Or am I doing it wrong? Is it meant to be a "one viewmodel per data model" philosophy?

Where do I draw the line between ViewModels? Do I risk encapsulating too much functionality into one object, or do I risk separating everything out too broadly and creating duplicative files? How have you structured your Knockout.js ViewModels?

答: Very purpose of ViewModel is to covert and display the data in your model to match the view. Simply creating a ViewModel per view would be the best way to handle this.</p>


问:
Large file / data transfer in a Microservice Architecture
My company is currently working on adopting a microservice architecture but we are encountering some growing pains (shock!) along the way. One of the key contention points we are facing is how to communicate large quantities of data between our different services.

As a bit of background we have a document store that serves as a repository for any document we might need to handle across the company. Interacting with said store is done via a service which provides a client with a unique ID and a location to stream the document. The document's location can later be accessed via a lookup with the provided ID.

The problem is this - Does it make sense for all our microservices to be accepting this unique ID as part of their API for the purposes of interacting with documents or not? To me this feels inherently wrong - the services are no longer independent and rely upon the document store's service. While I do acknowledge this might simplify API design and perhaps even have some performance gains the resulting coupling more than counterbalances the benefits.

Does anyone know how the rainbow unicorns (Netflix, Amazon, Google, etc.) handle large files / data exchange between their services?

答:
Personally, I'd rather not use a separate document store service and document id, but a URL to access the documents (with proper header authentication). With this approach you won't need other services to rely on the document service rather it could just use the full URL to access the document.And also it makes sense when it comes to scaling as well, you could use multiple document stores as and when the storage grows and provide the URL.

However you might need a service(s) to upload a document and to obtain it's URL.


问:
Business Layer Procedural?
The most common way I've seen of saving an entity into a database is through a class in a business / service layer. For example, when adding a new entity called User:

```<code>User user = new User();
user.Name = "Foo";

UserService userService = new UserService();
userService.Add(user);
</code>```

This works, and objects are being used, but I feel that the style leans toward the procedural side. Usually, the UserService class mostly contains methods for interacting with the database. You could almost make the UserService class static, and then it won't really be considered as an object anymore.

In a purely object-oriented manner, I feel that the code would look like this:

```<code>User user = new User();
user.Name = "Foo";
user.Add();
</code>```

My question is not about specific implementation details but about object-oriented design in general. Does using classes like the example UserService indicate a procedural way of coding? If so, what could be a better object-oriented approach?

An example from the .NET framework that I feel is more object-oriented is SqlConnection. How do we open a connection? Is there a SqlService class from which you can call sqlService.Open(sqlConnection)? No, but it is done from the SqlConnection object itself: sqlConnection.Open().

Now the Open method may use other classes in turn, but what's interesting to me is that it is exposed on the SqlConnection class itself, much like how the Add method is exposed in the User class in the second snippet above.

答:
One of the principles of object-oriented design is that each object (class) should do only one thing. The User class should know everything about being a user, but that doesn't include knowing where users are stored - that responsibility is for another class (your UserService class).

The UserService class should know all about storing users, but it doesn't need to know anything about the internals of what a User is - only that it needs to store it. When you look at it from this perspective, it makes sense to pass the user object to the userService, because in the other scenario a User would have to know how to store itself.

Title: Business Layer Procedural?


问:
Relationship of common MCUs/CPUs to FPGA and ASIC
I'm trying to understand the relationship between "common" MCUs/CPUs such as Intel, AMD, PowerPC, AVR, ARM, etc. and FPGAs and ASICs.

Here is my understanding:

These commons MCUs/CPUs (again, Intel, AVR, ARM, etc.) are "general purpose" and as such are not programmable and are meant to run a variety of different apps.

FPGAs are also MCUs/CPUs, however their circuitry is entirely programmable.

ASICs are also MCUs/CPUs, however they are app-specific and not programmable/reusable

The more fine-tuned an MCU/CPUs is to the application it is running, the faster that app's performance will be

Ergo: ASICs are fastest but are app-specific, not general purpose. Common MCUs/CPUs are slowest (relatively; not calling them "slow" by any means!) but are general purpose and can run any binary-compatible app. And FPGAs are in the middle because they are both app-specific and programmable.

Is anything about my understanding above is incorrect? If so, please correct me!

答:
You're mixing things up a bit. You've kind of got the gist of it but not completely.

Let's compare General Purpose Microprocessors, Microcontrollers, FPGAs, and ASICs. You've lumped microcontrollers and microprocessors together, when you really shouldn't.

General Purpose Microprocessors: These are the desktop and laptop processors, Intel Pentium chips, AMD Athlons, etc. These are expensive, very high power (watts), high-performance processors. They require an enormous amount of supporting circuitry in order to operate.

Microcontrollers: These classically are devices such as 8-bit Atmel AVRs, Microchip PICs, and many others. They are usually cheap, low-speed, low-performance, low powered devices, and often require very little supporting circuitry to operate. 40W is low for a CPU, 40mW is high for a microcontroller. They have very little memory, often having only 4-8K of SRAM, and 64KB of flash memory.

The processors in many applications, such as cell phones, blur the lines between the general purpose microprocessors, having higher performance and greater memory, but still low power. There are many ARM products that are making headway in the microcontroller realm that have performance capabilities vastly greater than the microcontrollers described above, with admittedly much greater power consumption, but similar in terms of little supporting circuitry, and cost. The processors in a digital camera for example, might be a chip that doesn't fit into either bucket very easily (and will probably have a beefy DSP to go with it).

FPGAs are economically in the middle of microcontrollers and ASICs. They give a trade-off high-speed and low power, but at reduced flexibility and increased complexity. Writing VHDL or Verilog for them is much more complicated than writing C for a microcontroller. These days, unless your application has a lot of analog components to it, ASICs aren't often more cost effective than FPGAs. An FPGA also is neither a microprocessor nor microcontroller, however, you could program one to function as a microcontroller, provided it has the right peripherals.

Application-Specific Integrated Circuit (ASICs). These are custom chips designed for a specific task. In my experience, the ASIC label goes on chips that are designed for a single-customer/single product, not just simply how specialized they are. I personally wouldn't call anything out of the digi-key catalog an ASIC, just an IC. Even something like the TI ADS1298R, a chip specifically designed for ECG devices. ASICs are used for specialty products that have constraints of speed, power, or size, where no existing general purpose part can suffice. An ASIC is not necessarily designed for maximum speed, it could also be for low power consumption. An ASIC can do it all, and give you whatever combination of speed, power, and size you need, but getting there will cost you more than any other option.

Again, like FPGAs, ASICs are neither microcontrollers nor microprocessors, but you could implement one in an ASIC. However, doing that would be so outrageously expensive and complex, that you need to rethink what you are doing. Instead, you would implement a device that computes some small piece of the puzzle, the element that is in the tightest loop of your application, then use general-purpose parts for everything else.

And of course, as alluded to, there are a lot of devices that don't neatly fit into these buckets.

Lastly, general purpose microprocessors aren't necessarily the slowest of the bunch, in fact the desktop processors are insanely fast, exceeding almost everything FPGAs are capable of. However, they also require tons of power compared to an FPGA. So whether you want to use a regular processor or an FPGA will depend whether your application is plugged into the wall or running of a tiny battery.


问:
What factors should influence how I determine when to abandon a small project with a friend?
I've found myself in a tough spot as of late. Been working on a game with a programming buddy for nearly 8 months now. We both started off as newcomers to programming around August of last year, he is a 2nd year CS student, I'm an IT support tech by trade and am a self-taught programmer with multitudes of books and online subscriptions.

The issue that I've been constantly seeing is that as we write out a chunk of code, it will often be a bit hacked together, have many failings, and if it's a brand new concept to one of us, full of naive solutions. This is fine, we are learning, I expect both of our code to be a bit hacked together on the firs or second pass. The problem presents itself when it comes to actually fixing and refactoring those hacked together behaviors.

My partner will hold onto his freshly cobbled together behavior, blatantly refusing to see any error the moment it starts to work. Claiming near perfection from a piece of structure I can't even try to use even if it had comments and appropriately named methods & fields. No matter how hard I try I just cannot get him to see the glaringly obvious flaws that will prevent any further changes or expansion of the behavior without completely breaking it and everything it's so tightly coupled to they might as well be in the same class. Hacked solutions perpetually stay hacked, poorly thought out designs stay the way they where when first conceived and tested.

I spend as much time babysitting new code as I do writing it myself, I'm a loss of what to do. My partner lost it tonight, and made it clear that no matter what, no matter the benchmark, no matter the common practice, no matter the irrefutable proof, his code will stay the way he first made it. Even if entire books have been written on why you want to avoid doing something, he will refuse to acknowledge their validity claiming it's just someones opinion.

I have a vested interest in our project, however I am not sure if I can continue to work with my partner. I seem to have three options open to me.

Stop caring about the codebase functioning past the point of compiling, and just deal with trying to maintain and parse behavior that's barely limping along. Hoping that once things start to seriously break he will see that and try to do more than just put a bandaid over the fundamentally flawed design.

Keep up the endless arguments over issues that have been figured out a decade ago by other much more capable individuals.

Stop programming on this project, abandoning nearly 10,000 lines of my code and countless hours slaving over design and try and find a new project on my own.

What approach can I take to determine if it is worth continuing on with this project with this person? Or what factors should influence my decision? We have written a lot of code and I do not want to give this up unless necessary.

答:
Possibly the easiest way is to bring someone else into the project - either you're wrong and his codebase is just too clever for you, or you're right and its too clever for everyone. You'll soon find out, and will get backup if it does turn out to be rubbish, convoluted, junior-programmer level code.

On the other hand, a working product is worth any number of years of finely tuned, elegant, clear code. Make the game, ship it, walk away then - leave him to maintain it and do not work on v2.


问:
What Type of Report or Documentation to Expect from my Programmers
First, I am not a programmer nor do I have any programming experience. I am an entrepreneur that had a website idea and hired programmers to custom build it. It has been going on for the last one year now. It uses Wordpress with some plugins such as Buddypress, Bbpress, etc, but a lot of custom codings as well.

I give the programmers tasks and they do them and the tasks work as I want, but they don't present any report or documentation as to what they did and how it was all coded, etc.

But my problem is - what if they suddenly disappear and I have to get other programmers to continue working on the site? Can the new programmers do a good job of taking over when there's no report or documentation, etc?

Of course there's report from me to the programmers telling them what to do and what functions I expect the tasks to perform. But when done, they don't present me with any report or documentation. They just say the task is done and I check and it's done.

If such report or documentation is required, what type should I request from these current programmers?

Or am I being unnecessarily paranoid?

答:
You want a high-level design document that describes the big blocks and their interaction and then functional design that describe how these blocks were implemented. Read up on UML for the main design concepts (but do not make them deliver UML docs, please - they go into too much detail, you only want the overviews)

Often the documentation can be sufficient with a simple text document describing the overall architecture, tools used (and versions!) - just enough to let a new dev understand the concepts and assumptions used which will let him them get into the code to find out the exact details of implementation.

You can demand full-on documentation, I've worked places (police, government) who really need to know exactly how something works, and such doc is a beautiful thing to have - but it rapidly gets more expensive to produce, and I think would be overkill for your needs, so be careful not to go too far in documentation. There's a sweet spot between none, enough to understand the product, and too much.


答:
I believe the problem is not about what documentation you should ask for. It is about how you can check that it is valid and will actually help new developer to pick up where previous left. It is easy for you to check if actual feature works, but not easy to check the documentation, no matter what kind of documentation you will request.

This is how I would do it: first, I would add requirement of exactly what you want. I would say that "Each feature should be documented enough for new developer to get general understanding of it, why it exists and why was it implemented the way it was." I would leave it to developers to decide how best to document their work. They can create comprehensive external documentation or they can make the code itself self-documenting with minimal external documentation. After this, I would hire a different, external developer to do a code review of their work. This developer would "emulate" a new developer and would try to understand the what the application is supposed to do and if it is doing it properly. Then he produces a report based on how easy it was for him. This could be done periodically every few weeks/months.

Title: What Type of Report or Documentation to Expect from my Programmers

Body:
First, I am not a programmer nor do I have any programming experience. I am an entrepreneur that had a website idea and hired programmers to custom build it. It has been going on for the last one year now. It uses Wordpress with some plugins such as Buddypress, Bbpress, etc, but a lot of custom codings as well.

I give the programmers tasks and they do them and the tasks work as I want, but they don't present any report or documentation as to what they did and how it was all coded, etc.

But my problem is - what if they suddenly disappear and I have to get other programmers to continue working on the site? Can the new programmers do a good job of taking over when there's no report or documentation, etc?

Of course there's report from me to the programmers telling them what to do and what functions I expect the tasks to perform. But when done, they don't present me with any report or documentation. They just say the task is done and I check and it's done.

If such report or documentation is required, what type should I request from these current programmers?

Or am I being unnecessarily paranoid?


答:
What you are describing is called an Active Record pattern.

As Jack points out, there are multiple problems with this pattern, especially in relation to separation of concerns, domain modeling, and testing. If you are using active record, you are assuming the classes are exactly the same as tables and rows in your relational database. This limits your modeling options. The object also becomes tightly couples to persistence library, making it hard to test it in isolation.

But the Repository pattern has it's problems too. It requires the repository to be able to read and write internal state of the entity it's responsible for, breaking encapsulation. It also doesn't really fit when using ORM, where the changes that are made to the object should be transparently persisted, removing need for any Save/Update methods.

Title: Business Layer Procedural?

Body:
The most common way I've seen of saving an entity into a database is through a class in a business / service layer. For example, when adding a new entity called User:

```<code>User user = new User();
user.Name = "Foo";

UserService userService = new UserService();
userService.Add(user);
</code>```

This works, and objects are being used, but I feel that the style leans toward the procedural side. Usually, the UserService class mostly contains methods for interacting with the database. You could almost make the UserService class static, and then it won't really be considered as an object anymore.

In a purely object-oriented manner, I feel that the code would look like this:

```<code>User user = new User();
user.Name = "Foo";
user.Add();
</code>```

My question is not about specific implementation details but about object-oriented design in general. Does using classes like the example UserService indicate a procedural way of coding? If so, what could be a better object-oriented approach?

An example from the .NET framework that I feel is more object-oriented is SqlConnection. How do we open a connection? Is there a SqlService class from which you can call sqlService.Open(sqlConnection)? No, but it is done from the SqlConnection object itself: sqlConnection.Open().

Now the Open method may use other classes in turn, but what's interesting to me is that it is exposed on the SqlConnection class itself, much like how the Add method is exposed in the User class in the second snippet above.


问:
Use TFS to track bugs from Production Support
I have just moved to a new company and they are using TFS 2010 (2012 in a couple of months) as their version control system and recently started to use it as a work tracking system for the developers.

However, there doesn't seem to be a bug tracking system for use by people outside development & test.  Production support are getting reports of issues, fixing them on the fly and reporting back to their users at the moment.  This needs to be changed but I don't really want to have a sperate system for tracking bugs and tracking dev work.

Is there a way that I can create a very light weight way of entering bugs into TFS similar to the way that FogBugz does?  Logging into TFS to fill out a bug report seems to be a lot heavier and you have to associate it with a particular application.  Support may be able to do this but I want to be able to triage the item and potentially change the association to something other than an application.

I have used FogBugz in the past and when adding a bug, you can add a much/little as you want to the item so it is at least recorded and later you can bounce it back to get more information when you come to triage the ticket.

答:
It largely depends on what fields you would want, as 17 of 26 indicated: TFS is highly customisable. The reason I would want to do this as opposed to use something like JIRA is that you get a single view of what your developers are working on, as opposed to having to aggregate two systems.

TFS also has resource capacity planning, and if you're not showing production defects in your planning (and they take up a significant fraction of your time), then you're not really planning your capacity. I would in fact say that this is an ideal solution for teams where the developers make use of TFS and support Production (e.g. DevOps).

It doesn't mean you can't use other tools for the main Production Support/ITIL work, you'd just need to make sure they integrate, either manually or preferably automatically. Most such tools allow you to put in custom hooks, and TFS certainly does.

Anyway, to the main question. I use the CMMI TFS templates (which actually work fine with Agile BTW), and I just added a single field to one of the drop downs.

Here are the steps:

Install TFS Power Tools

Open the Work Item Template from the server

Edit the Discipline field

The discipline field is the "kind" of work related to the defect. The standard values are:

Analysis

User Experience

User Education

Development

Test

What we're just going to do is add "Production" to that list. First, edit the Discipline field:

Then, click the Rules tab and edit the ALLOWEDVALUES rule:

Then, Click "New", and add in "Production" as one of the values.

Click "OK" repeatedly until you're back at the field list.

Save the Work Item Template

OK, now you're done. You can create new Bugs and indicate their type as Production. I'd also create a few Work Item Queries looking at Production defects, and add them to your pinned items. Finally, look at the existing Bug queries, and maybe change their ordering so that "Production" bugs come up first (if that's possible).


答:
This may be a cultural thing. In some cultures, admitting that you made a mistake is unheard of, and asking someone to admit to making a mistake is about the rudest thing you can do. If it is that situation, run away.

In my experience with very smart people, if you tell them that something they are doing is less than perfect, they will either (1) give you a correct and easy to understand reason why what they are doing is actually right, (2) tell you that they know it is wrong, but they have no time to fix it because of priorities, or (3) thank you for pointing it out and fix it.

Refusing to learn is about the worst attribute a software developer could have. Leave him to it. Life is too short and precious to waste your time on him.

Title: What factors should influence how I determine when to abandon a small project with a friend?

Body:
I've found myself in a tough spot as of late. Been working on a game with a programming buddy for nearly 8 months now. We both started off as newcomers to programming around August of last year, he is a 2nd year CS student, I'm an IT support tech by trade and am a self-taught programmer with multitudes of books and online subscriptions.

The issue that I've been constantly seeing is that as we write out a chunk of code, it will often be a bit hacked together, have many failings, and if it's a brand new concept to one of us, full of naive solutions. This is fine, we are learning, I expect both of our code to be a bit hacked together on the firs or second pass. The problem presents itself when it comes to actually fixing and refactoring those hacked together behaviors.

My partner will hold onto his freshly cobbled together behavior, blatantly refusing to see any error the moment it starts to work. Claiming near perfection from a piece of structure I can't even try to use even if it had comments and appropriately named methods & fields. No matter how hard I try I just cannot get him to see the glaringly obvious flaws that will prevent any further changes or expansion of the behavior without completely breaking it and everything it's so tightly coupled to they might as well be in the same class. Hacked solutions perpetually stay hacked, poorly thought out designs stay the way they where when first conceived and tested.

I spend as much time babysitting new code as I do writing it myself, I'm a loss of what to do. My partner lost it tonight, and made it clear that no matter what, no matter the benchmark, no matter the common practice, no matter the irrefutable proof, his code will stay the way he first made it. Even if entire books have been written on why you want to avoid doing something, he will refuse to acknowledge their validity claiming it's just someones opinion.

I have a vested interest in our project, however I am not sure if I can continue to work with my partner. I seem to have three options open to me.

Stop caring about the codebase functioning past the point of compiling, and just deal with trying to maintain and parse behavior that's barely limping along. Hoping that once things start to seriously break he will see that and try to do more than just put a bandaid over the fundamentally flawed design.

Keep up the endless arguments over issues that have been figured out a decade ago by other much more capable individuals.

Stop programming on this project, abandoning nearly 10,000 lines of my code and countless hours slaving over design and try and find a new project on my own.

What approach can I take to determine if it is worth continuing on with this project with this person? Or what factors should influence my decision? We have written a lot of code and I do not want to give this up unless necessary.


问:
Is macros support in a programming language considered harmful?
The first abuse that comes to my mind in C is:

```<code>#define if while
</code>```

But at the same time it is extremely handy and powerful when used correctly.

Something similar happens with Common Lisp macros.

Why doesn't all the programming languages support macros like this and what are the alternatives?

Is it they are considered harmful?

答:
I am of the opinion that if a language has macros, they should be a well planned out and integral part of the language and not of the compiler.

Example, Lisp's macro system is a very powerful integrated language feature and is subject to all the rules and regulations of Lisp itself.

Counter-example, C/C++ macro system is separate from the language and built into the compiler.  The result is that you are not limited to the constraints of your language and can create invalid code and redefine language specific keywords.

At the end of the day, there are several languages that have no macro feature--but those fatures are not missed as much.  It all depends on how expressive a language is, and whether it has alternative approaches to meta-programming.  Meta-programming is just a way of ensuring that when you do X, X is done the same way all throughout the application.


问:
Big O notation of randomness
I was thinking about inefficient algorithms based on randomness and wondered how to categorise them.

For instance. Say you wanted to generate all the numbers from 1 to N in a random order but only once each.

My inefficient algorithm does this...

```<code>Generate a random number between 1 and N (inclusive).
Check it has not already been used.
If it has then generate a new random number until you get one that hasn't been used.
Display the random number.
Store random number in checking array.
</code>```

This should get all the numbers in a random order but for large values of N will have to run multiple times when getting the last few numbers.

For instance. On average the last random value will take N times to generate.

Best case for this is O(N) because there is a possibility that each random number generated is distinct.

Average case is a bit harder...

Without properly going into the calculation I think it's O(NlogN) or possible O(N^2).

But what would the worst case be? Well, worst case is that it never finds all the numbers. It would loop infinitely and never actually complete. For large N that's understandable but how do you give the big O notation for it?

答: The worst-case is O(∞). The best-case is Ω(n2), because you have to generate n numbers, and for each number generated you have to search a list of length n whether or not the number is already in there.

Title: Big O notation of randomness


问:
DDD using an ORM and a Active Directory Server for Persistence
With Domain Driven Design one would model out the domain. One would then use an ORM of some sort to take care of the persistence. Say you have a Product entity which has a Name, SKU and an Owner. This will be modelled and when a new Product gets created you need to pass in all 3 fields as parameters into the constructor.

The above will be persisted by Fluent NHibernate using a Postgresql Database.

The Owner of the product is of type Account. The Account is an entity which holds ID, FirstName, LastName, Email, Phone, Username, Password  and Address.

The Account needs to be persisted in two databases. It needs to persisted into the Application Database (Postgresql Server) so that there can be a link between Product and Account. However, it also needs to be saved on the 389 Active Directory server. This AD server holds all user records and their information.

I don’t want to duplicate all the data which is stored on the Active Directory server and save it to the Application Server. On the Application Server I want to save FirstName, LastName, Email and the ID.

If a user chooses to change their Account details, this will then update the Active Directory Server and the fields stored in the Application Server.

E.G. A user logs on and wants to change their password. The password field is only stored in the Directory server. We use the Novell LDAP directory services library to access the information from the Directory Server.

In in our Infrastructure Layer we have a project where we implemented access to the AD server. So in the example above of changing password, we will only be talking to the AD server as there is no password saved in the Application Server.

Now the question is, in my domain to I create a model containing:

ID, FirstName, LastName, Email, Phone, Username, Password, Address

Or

ID, FirstName, LastName, Email

There will be a screen in the UI where one can change all Account details.

答:
I have done some more research in domain driven development.

Bounded Contexts seemed to help me solve this problem.

I started modeling out the system and not caring about the persistence, as you should do with DDD.

In the infrastructure level, I have separated out where data should be saved.

The data that is related to the User and Organisation for example, will be saved to LDAP where as all the other data will be saved to the application database.

We basically wrote a Service which the application services can use.


问:
Is contructing complex mocks for unit testing a sign of bad architecture?
The title is fairly self explanatory.

To elaborate: I'm currently updating a suite of unit tests for an application which makes heavy use of Entity Framework. We connect to this via a classic repository interface so it can be mocked out.

We're not doing test first (that's a whole different argument, which I don't want this question to degenerate into). Rather a "code a bit, test a bit" sort of approach. So we're not backfilling a whole application with tests, either.

I appreciate that a whole suite of tests for such an application is likely to require a very complex repository mock. However, I just created a new test class and the very first test required a mock repository with about 5 mocked out repository get/save functions.

It was a fairly simple function that was being tested. The range of mock classes were needed because of operations carried out in the class constructor and suchlike.

Having done so it struck me that that hardly looked like a unit. And that it might be a sign my code was too interdependent. So: is creating a single test that demands a complex mock often a sign of poor architecture?

答:
I'm going to have to make a couple of guesses here

You mention EF so I'm guess the mocks in question are related to the datalayer?

Since you are using EF, I guess your Repository presents an IQueryable and your Models construct queries within themselves?

This would lead to you then having to craft you mock with data which is consistent with the various queries your Models run, which I imagine could end up being pretty complicated.

I think the mistake here is the queryable repository. My view is that repositories should expose methods such as

IEnumerable GetModelsByConditionXAndConditionY(var valueOfAParmeter)

rather than

IEnumerable GetModelsByQuery(Func SomeQueryFunction)

or

IQueryable GetModelsButDontReturnThemYetINeedToThink()

This enables you to construct an in memory version of your database with consistent test data, because the ways in which that data are returned are known by the Repository.

Any Consuming class can take the repository and be expected to work correctly without model specific setup of the data.

I also tend to make this mock repository as its own class rather than using a mock framework to configure it per unit test

This makes your unit tests pretty simple as they all use the same mock data and allows you to inject the same mock repositories into your real app for UI testing etc


答:
I think you are treading on dangerous ground here.

On one hand you have an LDAP authentication system which also has user name, and extra info in it.

On the other you have a domain concept of a product owner.

Its tempting to see the LDAP service as just a repository for product owners, but I dont think it really is. you will have all sorts of users in AD, only some of which will be product owners in your app and in the future you may have product owners in your app which are not in AD. (ie. someone leaves the company and is removed from AD?)

I would duplicate the data and have an extra AuthenticatedBy set of models to link product owners to your LDAP/AD system.

Title: DDD using an ORM and a Active Directory Server for Persistence

Body:
With Domain Driven Design one would model out the domain. One would then use an ORM of some sort to take care of the persistence. Say you have a Product entity which has a Name, SKU and an Owner. This will be modelled and when a new Product gets created you need to pass in all 3 fields as parameters into the constructor.

The above will be persisted by Fluent NHibernate using a Postgresql Database.

The Owner of the product is of type Account. The Account is an entity which holds ID, FirstName, LastName, Email, Phone, Username, Password  and Address.

The Account needs to be persisted in two databases. It needs to persisted into the Application Database (Postgresql Server) so that there can be a link between Product and Account. However, it also needs to be saved on the 389 Active Directory server. This AD server holds all user records and their information.

I don’t want to duplicate all the data which is stored on the Active Directory server and save it to the Application Server. On the Application Server I want to save FirstName, LastName, Email and the ID.

If a user chooses to change their Account details, this will then update the Active Directory Server and the fields stored in the Application Server.

E.G. A user logs on and wants to change their password. The password field is only stored in the Directory server. We use the Novell LDAP directory services library to access the information from the Directory Server.

In in our Infrastructure Layer we have a project where we implemented access to the AD server. So in the example above of changing password, we will only be talking to the AD server as there is no password saved in the Application Server.

Now the question is, in my domain to I create a model containing:

ID, FirstName, LastName, Email, Phone, Username, Password, Address

Or

ID, FirstName, LastName, Email

There will be a screen in the UI where one can change all Account details.


问:
How do I convince my users not to use a sketch UI?
I recently worked on a prototype of a new system using Sketchflow, and now some key stakeholders are pushing for a sketched look & feel in the final product. To make matters worse, the people viewing the prototype were asked to provide feedback on the sketched look & feel by way of a fairly leading survey question, to which 80% of the responses were positive.

It's for an enterprise application that will mostly be for internal clients, but is also intended to be used by some external clients.

The main reasons I have for it thinking it's a bad idea are:

It doesn't look polished or professional

The significant effort involved in skinning an actual application in the sketched style

The sketched style doesn't make efficient use of screen real-estate

I've been trying to figure out what the appeal could possibly be, and the only thing I can come up with is that people are attracted to the simplicity of it -- especially when compared with the existing system(s) it will be replacing.

Can anyone point me in the direction of evidence of why using a sketch look & feel is a bad idea? Ideally something based on UI research. I'm worried that my voice isn't going to be listened to unless I can point to something concrete.

[Edit]

I should probably add that the difficulty of skinning the application is compounded by the fact that it is intended to be delivered as one or more Silverlight webparts in a Sharepoint site. Getting a consistent sketched look & feel across both technologies could be very difficult.

[Edit]

Just in case anyone's not sure about what a Sketchflow prototype looks like (and therefore what the people in question are asking for) they're essentially asking for a production application to have a pencil-sketch wireframe look & feel.

答:
I can think of a reason why it's bad from a programmer's perspective: the sketch look is used to make sure users don't confuse prototypes with the real thing. If the real thing is sketched you can't really use that for prototyping any more.

From a user's perspective I can't think of a reason. If they like that aesthetic and it is easy to use, then you'll have a hard time convincing them otherwise without something better.


答:
I do not see any problem.

You have two distinct objects: User and UserService. Both of these have two distinct roles / responsibilities.

1) The User object represents the User in your domain. It responds to questions / messages like age? or firstName?. It is its duty to answer these types of questions.

2) The UserService is distinct from the User. It answers not to the above questions, but to a different set like: userCount?, countOfUKUsers?. The responsibility is quite different. The User doesn't care of any numbers, nor does it have to know anything about persisting. UserService consumes so to say a User or produces new instances, when returning data from the database.

```<code>UserService userService = new UserService();
userService.Add(user);
</code>```

This is perfectly object oriented - though usually you would inject the Service (which makes it look to you procedural):
The UserService is sent a message Add and the message has a payload, which is a User.

But your 2nd example code above has no clear semantics

```<code>user.Add();
</code>```

You are sending the Add() message to the User. But what does this mean? It is like asking yourself to listen. It is grammatically correct, but doesn't make any sense. Besides: you would mix in knowledge about persisting with actual knowledge of the User itself, which violates the single responsibility pattern.

Does using classes like the example UserService indicate a procedural way of coding?

NO. It is perfectly OOP: Passing messages to independent objects.

Title: Business Layer Procedural?

Body:
I do not see any problem.

You have two distinct objects: User and UserService. Both of these have two distinct roles / responsibilities.

1) The User object represents the User in your domain. It responds to questions / messages like age? or firstName?. It is its duty to answer these types of questions.

2) The UserService is distinct from the User. It answers not to the above questions, but to a different set like: userCount?, countOfUKUsers?. The responsibility is quite different. The User doesn't care of any numbers, nor does it have to know anything about persisting. UserService consumes so to say a User or produces new instances, when returning data from the database.

UserService userService = new UserService();
userService.Add(user);

This is perfectly object oriented - though usually you would inject the Service (which makes it look to you procedural):
The UserService is sent a message Add and the message has a payload, which is a User.

But your 2nd example code above has no clear semantics

user.Add();

You are sending the Add() message to the User. But what does this mean? It is like asking yourself to listen. It is grammatically correct, but doesn't make any sense. Besides: you would mix in knowledge about persisting with actual knowledge of the User itself, which violates the single responsibility pattern.

Does using classes like the example UserService indicate a procedural way of coding?

NO. It is perfectly OOP: Passing messages to independent objects.


答:
A question very close to my heart! (see my OOP vs ADM question)

Yes I believe that it IS procedural, but only if your UserService Modifies User.

for example, consider an Order which has many Items

Order.AddItem(Item item)

would be OOP surely?

but

Order.SetItemPrice(Item item, decimal price)

where Item has Item.Price, breaks the encapsulation principle. you would expect

Item.SetPrice(decimal price)

Now, there is potentially an additional factor that because you are writing to a database you'll be needing to see all the private data fields on User. but, really in these days of ORMs and serialisers using reflection over objects anyway. Unless your pattern forces you to make all the otherwise private fields public I don't think you can consider it 'not OOP'

Also you might have

User.SerialiseToXML() or something which would not break encapsulation

Now your second question "What would be a better OOP way" begs the question. Is an OOP way always better?

Title: Business Layer Procedural?


问:
Is an NPath complexity of over sixteen octillion realistic? Or have I broken the tool?
I have just measured a large chunk of PHP code (1153 lines) using PHPMD (http://phpmd.org/) and it tells me the code has an NPath complexity of 16244818757303403077832757824.

That looks like a crazily big number to me, suggesting that perhaps PHPMD has broken in some way. Is it even possible for a piece of code written by humans to have such a high NPath complexity? The cyclomatic complexity is 351.

Two possibly important details -

This was procedural code, mixed in with HTML, and PHPMD will only measure object-oriented code. To get around this, I wrapped the whole file in a class with a single function - this is representative of how it's used.

The file consists of a series of nested switch statements, and inside those there are lots of if..else statements - so it's certainly pretty complicated.

Edit

I want to clarify that I'm not questioning whether PHPMD is lying to me. I know that the code is an awful mess, I just wonder if it's possible for any code to be really that bad. It seems like the answer is yes, it's very possible.

答:
According to this description, NPath complexity is exponential in cyclomatic complexity.

Taking just simple if statements, if you have two of these statements, that's essentially 4 routes through your code corresponding to the four possible combinations of true/false for the two statement conditions. Add another if statement and you get 8.

In other words, if all your cyclomatic and NPath complexity was coming from a long list of if statements, then your equaltion would be NPath = 2^cyclomatic. Comparing that with your numbers, 2^351 = 4.6 * 10^105, far, far higher than the NPath complexity you reported.

I don't know how much PHPMD does to avoid counting paths which are actually impossible (e.g. two mutually exclusive conditionals both evaluating to true). Possibly a manual analysis would reveal that a lot of the paths are actually impossible, so the code is written in a way that inflates the NPath metric. To continue the above, if you had a list of 351 if statements, but could verify that only one was ever actually entered, you could turn it into a chain of if...else statements, brining your NPath complexity down from 4.6 * 10^105 to 353.

But with only the information in your question, not knowing how much of that kind of simplification could be done or is already being done by PHPMD, the number seems realistic.


答:
This is entirely possible. Let's assume we have 35 switch-case constructs of 10 cases each, which would give us a rough cyclomatic complexity of 350 when each switch occurs one after the other. The first switch gives us 10 paths. The second switch gives us another independent 10 paths, so that we have 10·10 paths until here. With the third switch, we get 10·10·10=10³ paths, and so on until we get 1035 paths in total! This is even higher than your result of 1.6·1028 paths, which is probably due to a different branching factor, and due to nested control flow statements which reduce the number of paths through your code.

As a worst case scenario for a given cyclomatic complexity c, we can have a maximum of 2c acyclic paths through the code (here: 2351 = 4.6·10105).

The tool's judgement is clear: the code you are dealing with is a convoluted, untestable, and unmaintainable mess. Consider splitting it into smaller, independent functions, and abstracting away repetition. E.g. you could separate HTML generation from the main logic of your PHP script.

Title: Is an NPath complexity of over sixteen octillion realistic? Or have I broken the tool?

Body:
I have just measured a large chunk of PHP code (1153 lines) using PHPMD (http://phpmd.org/) and it tells me the code has an NPath complexity of 16244818757303403077832757824.

That looks like a crazily big number to me, suggesting that perhaps PHPMD has broken in some way. Is it even possible for a piece of code written by humans to have such a high NPath complexity? The cyclomatic complexity is 351.

Two possibly important details -

This was procedural code, mixed in with HTML, and PHPMD will only measure object-oriented code. To get around this, I wrapped the whole file in a class with a single function - this is representative of how it's used.

The file consists of a series of nested switch statements, and inside those there are lots of if..else statements - so it's certainly pretty complicated.

Edit

I want to clarify that I'm not questioning whether PHPMD is lying to me. I know that the code is an awful mess, I just wonder if it's possible for any code to be really that bad. It seems like the answer is yes, it's very possible.


答:
I think the chances are that you do NOT want any code documentation from the programmers.

The reason you state that you think you might want documentation is :

"Can the new programmers do a good job of taking over when there's no report or documentation, etc"

So the documentation isn't for you to read, its not a manual for the product, It dosnt give you any benefit of itself.

If you don't get new programmers during the life span of your product. You will have paid your programmers to write documents that are never used.

In my opinion, your hypothetical new programmers will probably not read them either. Programmers tend not read code documentation for a variety of reasons and this is generally recognized with modern 'agile' programming methodologies.

So I say, Don't ask the programmers to document their code.

However! What you DO need to document are your requirements, and what tests you ran to ensure they were met.

eg.

Requirement 1: "when there is an error, make the button red"

you need these because the hypothetical new programmers will not know what the code is supposed to do.

Your current programmers understand the project, so when you tell them

Requirement 2: 'Make the button blue'

They remember your previous requirement and they will make the button blue when its not errored and red when it is.

The new programmers however, were not around when you asked for requirement 1. so they will make it blue all the time.

You will have to remember all the requirements and tell them:

Requirement 2 : 'make the button blue, unless it is errored in which case it should be
  red'

Its impossible to remember all the requirements for even small projects and whats worse the combination of requirements, ie that the red state overrides the blue state is never actually stated. That's where writing down your tests comes in, you will have tested the app worked after requirement 2 and written

"Tested normal page ok, tested error page ok"

This will tell the new developers that the error page is Supposed to have a red button, and its not a bug which needs fixing.

What you need to protect yourself from losing is that big picture of what your application is supposed to do. That's the thing that only exists in your developers heads at the moment and its really something only you can document.


答:
Ok, here is an answer you will probably not like.

Do not 'correct' the code unless it fails to implement the
  feature.

Here's my reasoning. You are presumably trying to make money. To make money you have to ship completed features quickly. No one is going to pay you more for a 'well coded' computer game.

Most companies have the same problem. Refactor existing code to make it 'better', sometimes even objectively better in terms of speed or reliability OR write new features.

99% of the time they choose to write the new features because the result of simple cost benefit analysis.


答:
C macros and Lisp macros are entirely different. C macros are expanded using string substitution before any other processing is done. Lisp macros are expanded after the input text has been parsed into a syntax tree1, and can use the entire language during expansion. With Lisp macros, you can not only do stupid things like #define begin {, but you can define your own control structures, and even populate arrays at compile-time using whatever code you want.

One reason for not including macros is that anything more complicated than simple string substitution can be very hard to work with in languages with C-style syntax. Another complaint about macros is that they can make code more difficult to read, which can be true if not implemented skillfully. Well-written Lisp macros can actually make the code easier to read.

1except for read macros, which are expanded during the process of creating the syntax tree.

Title: Is macros support in a programming language considered harmful?

Body:
The first abuse that comes to my mind in C is:

```<code>#define if while
</code>```

But at the same time it is extremely handy and powerful when used correctly.

Something similar happens with Common Lisp macros.

Why doesn't all the programming languages support macros like this and what are the alternatives?

Is it they are considered harmful?


问:
Is it appropriate to use the unordered list (ul) element for composite content
I recently had a thought of utilizing the unordered list element to represent a list of composite content (such as a product list with details or an image list with captions).

For example:

```<code><ul>
    <li>
        <img src="awesometoaster.png" alt="toaster">
        <p>Awesome Toaster<p>
        <p>This is an available product</p>
        Buy Now
    </li>
</ul>
</code>```

I have looked into example usages of the element, however many provide very basic one level examples.

```<code><ul>
    <li>Red</li>
    <li>Blue</li>
    <li>Green</li>
</ul>
</code>```

To me, the first example is a logical list of products and would make sense to utilize an unordered list. Would this be a semantic choice to represent this type of content or is there a more appropriate element choice?

答:
Yes, unordered list is very useful in this case. But merely an unordered list looks not so attractive. </p>

<p>So go for Cascading style sheets(CSS) which is very simple and more attractive reusable styling classes can be done. More attractive web designs are possible. If you are new to it then take this tutorial - HTML & CSS. This is really helpfull in learing the basics of web design </p>

Body:
I recently had a thought of utilizing the unordered list element to represent a list of composite content (such as a product list with details or an image list with captions).

For example:

```<code><ul>
    <li>
        <img src="awesometoaster.png" alt="toaster">
        <p>Awesome Toaster<p>
        <p>This is an available product</p>
        <a href="#">Buy Now</a>
    </li>
</ul>
</code>```

I have looked into example usages of the element, however many provide very basic one level examples.

```<code><ul>
    <li>Red</li>
    <li>Blue</li>
    <li>Green</li>
</ul>
</code>```

To me, the first example is a logical list of products and would make sense to utilize an unordered list. Would this be a semantic choice to represent this type of content or is there a more appropriate element choice?

Body:
Yes, unordered list is very useful in this case. But merely an unordered list looks not so attractive.

So go for Cascading style sheets(CSS) which is very simple and more attractive reusable styling classes can be done. More attractive web designs are possible. If you are new to it then take this tutorial - HTML & CSS. This is really helpfull in learing the basics of web design