问:
How do you explain refactoring to a non-technical person?
How do you go about explaining refactoring (and technical debt) to a non-technical person (typically a PHB or customer)? ("What, it's going to cost me a month of your work with no visible difference?!")

UPDATE Thanks for all the answers so far, I think this list will provide several useful analogies to which we can point the appropriate people (though editing out references to PHBs may be wise!)

答:
"Have you ever played Mouse Trap?  As we stick in new features, change interfaces, and fix bugs, code can start to look a lot like that.  There comes a point where we either have to expend a lot of capital (time and effort, which amount to money) making sure all the moving parts play nicely with each new change or addition, or we can instead set time aside to refactor the design, resulting in fewer moving parts we have to manage each time we make a change.  It may seem, from an end-user's perspective, that the refactor doesn't have any benefits, but the benefit happens every time a new feature is added post-refactor.  The process is faster, introduces fewer bugs, and is less expensive thereafter, not to mention that the refactored code is often more efficient overall.

You may wonder why we let it start to look like Mouse Trap in the first place:

Sometimes getting something done right now means that we have to sacrifice elegance and efficiency to just "make it work".

The language features and other technologies available to us as programmers often change.  Sometimes new features let us replace a finnicky jumble of six moving parts with one.

Oftentimes, when we add feature C to features A and B, we don't know that B will eventually be dropped and D added.  One way to accomplish C may work very well with B, but not very well with D.

In an effort to keep building a better mouse trap, we have to constantly go back and find places to reduce complexity and streamline what we have.  It's the difference between just having software with a lot of features, and having truly high-quality software."


问:
Are there any programming languages that follow a minimalist development approach?
I find it that when languages are considered the same as commercial software, there is always a constant need to add new features to justify new releases.

Can there be or are there languages where version 1.0 is the final version? Of course bug fixes are exempt from this, but the feature set always remains the same?

This way every feature in the language fits together nicely and not seem like they are bolted on after the fact with obsolete features still around because of backwards compatibility.

I assume some academic languages are like this? But are there commercially successful languages that follows this idea? The accompanying library is also free to get new features too, but the language always remains constant.

One example I can give is, one of my favourite languages C#, which I use pretty often, more and more features are being added every release. To take advantages of these, I have to drop actual tasks in hand, and spend considerable time learning these instead of being able to pick up trivial concepts and combine those myself to solve more complex problems with ease.

So I guess I am looking for a minimalist approach where everything is consistent, makes sense, and is as orthogonal as possible.

答:
Others have already said Lisp so I must bring up Forth.  It is very easy to implement and the rules of the language are simple to follow.

It is a stack-based language with a dictionary of "words." You can easily extend the language using some inherit features.

A VERY terse example of turtle graphics:

```<code>\ 8.8 fixed point sine table lookup
-2 var n F9F2 , E9DD , CEBD , AA95 , 7F67 , 4E34 , 1A c,
: s abs 3C mod dup 1D > if 3C swap - then dup E > if
  -1 1E rot - else 1 swap then n + c@ 1+ * ;

0 var x 0 var y 0 var a
0 var q 0 var w
: c 9380 C80 0 fill ; \ clear screen
: k >r 50 + 8 << r> ! ;
: m dup q @ * x +! w @ * y +! ; \ move n-pixels (without drawing)
: g y k x k ; \ go to x,y coord
: h dup a ! dup s w ! 2D + s q ! ; \ heading
: f >r q @ x @ y @ w @ r 0 do >r r + >r over + \ forward n-pixels
  dup 8 >> r 8 >> plot r> r> loop o y ! x ! o r> o ;
: e key 0 vmode cls ; \ end
: b 1 vmode 1 pen c 0 0 g 0 h ; \ begin
: t a @ + h ; \ turn n-degrees
</code>```

Then running it with : squiral -50 50 g 20 0 do 100 f 21 t loop ; gives you:

Credit to this Microsoft employee's blog.

ContentLicense: CC BY-SA 3.0

Body:
Others have already said Lisp so I must bring up Forth.  It is very easy to implement and the rules of the language are simple to follow.

It is a stack-based language with a dictionary of "words." You can easily extend the language using some inherit features.

A VERY terse example of turtle graphics:

\ 8.8 fixed point sine table lookup
-2 var n F9F2 , E9DD , CEBD , AA95 , 7F67 , 4E34 , 1A c,
: s abs 3C mod dup 1D > if 3C swap - then dup E > if
  -1 1E rot - else 1 swap then n + c@ 1+ * ;

0 var x 0 var y 0 var a
0 var q 0 var w
: c 9380 C80 0 fill ; \ clear screen
: k >r 50 + 8 << r> ! ;
: m dup q @ * x +! w @ * y +! ; \ move n-pixels (without drawing)
: g y k x k ; \ go to x,y coord
: h dup a ! dup s w ! 2D + s q ! ; \ heading
: f >r q @ x @ y @ w @ r 0 do >r r + >r over + \ forward n-pixels
  dup 8 >> r 8 >> plot r> r> loop o y ! x ! o r> o ;
: e key 0 vmode cls ; \ end
: b 1 vmode 1 pen c 0 0 g 0 h ; \ begin
: t a @ + h ; \ turn n-degrees

Then running it with : squiral -50 50 g 20 0 do 100 f 21 t loop ; gives you:

Credit to this Microsoft employee's blog.

ContentLicense: CC BY-SA 4.0


问:
When did the standard for packaging Linux source code become .tar.gz?
When browsing open-source projects that are primarily developed for Linux systems and downloading the latest packages, the source code is always stored in a .tar.gz or .tar.bz2 file.

Is there any reason for using .tar.gz or .tar.bz2 rather than something like .zip or .rar or some other compression algorithm (or even leaving it uncompressed if the project is small enough)?

答:
I don't know about when, but I imagine the reason why it's used is a combination of: tar being traditional (it's very old); easy management from a command line; tar preserving file system info that ZIP or RAR may not; and the two pass process means that compression is more efficient (one big file compressing better than many little files).

bzip2 (.bz2) seems to be displacing gzip (.gz) as it provides better compression, in much the same way that gzip itself displaced the earlier compress (.Z).


问:
Good implementation strategies for encapsulating shared data in a software pipeline
I'm working on re-factoring certain aspects of an existing web service. The way the service APIs are implemented is by having a kind of "processing pipeline", where there are tasks that are performed in sequence. Unsurprisingly, later tasks may need information computed by earlier tasks, and currently the way this is done is by adding fields to a "pipeline state" class.

I've been thinking (and hoping?) that there's a better way to share information between pipeline steps than having a data object with a zillion fields, some of which make sense to some processing steps and not to others. It would be a major pain to make this class thread-safe (I don't know if it would even be possible), there is no way to reason about its invariants (and it's likely it doesn't have any).

I was paging through the Gang of Four design patterns book to find some inspiration, but I didn't feel like there was a solution in there (Memento was somewhat in the same spirit, but not quite). I also looked online, but the second you search for "pipeline" or "workflow" you get flooded with either Unix pipes information, or proprietary workflow engines and frameworks.

My question is - how would you approach the issue of recording the execution state of a software processing pipeline, so that later tasks can use information computed by earlier ones? I guess the major difference with Unix pipes is that you don't just care about the output of the immediately preceding task.

As requested, some pseudocode to illustrate my use case:

The "pipeline context" object has a bunch of fields that the different pipeline steps can populate/read:

```<code>public class PipelineCtx {
    ... // fields
    public Foo getFoo() { return this.foo; }
    public void setFoo(Foo aFoo) { this.foo = aFoo; }
    public Bar getBar() { return this.bar; }
    public void setBar(Bar aBar) { this.bar = aBar; }
    ... // more methods
}
</code>```

Each of the pipeline steps is also an object:

```<code>public abstract class PipelineStep {
    public abstract PipelineCtx doWork(PipelineCtx ctx);
}

public class BarStep extends PipelineStep {
    @Override
    public PipelineCtx doWork(PipelieCtx ctx) {
        // do work based on the stuff in ctx
        Bar theBar = ...; // compute it
        ctx.setBar(theBar);

        return ctx;
    }
}
</code>```

Similarly for a hypothetical FooStep, which might need the Bar computed by BarStep before it, along with other data. And then we have the real API call:

```<code>public class BlahOperation extends ProprietaryWebServiceApiBase {
    public BlahResponse handle(BlahRequest request) {
        PipelineCtx ctx = PipelineCtx.from(request);

        // some steps happen here
        // ...

        BarStep barStep = new BarStep();
        barStep.doWork(crx);

        // some more steps maybe
        // ...

        FooStep fooStep = new FooStep();
        fooStep.doWork(ctx);

        // final steps ...

        return BlahResponse.from(ctx);
    }
}
</code>```

答:
This looks like a Chain Pattern in GoF.

A good starting point would be to look at what commons-chain does.

A popular technique for organizing the execution of complex processing flows is the "Chain of Responsibility" pattern, as described (among many other places) in the classic "Gang of Four" design patterns book. Although the fundamental API contracts required to implement this design patten are extremely simple, it is useful to have a base API that facilitates using the pattern, and (more importantly) encouraging composition of command implementations from multiple diverse sources.

Towards that end, the Chain API models a computation as a series of "commands" that can be combined into a "chain". The API for a command consists of a single method (execute()), which is passed a "context" parameter containing the dynamic state of the computation, and whose return value is a boolean that determines whether or not processing for the current chain has been completed (true), or whether processing should be delegated to the next command in the chain (false).

The "context" abstraction is designed to isolate command implementations from the environment in which they are run (such as a command that can be used in either a Servlet or Portlet, without being tied directly to the API contracts of either of these environments). For commands that need to allocate resources prior to delegation, and then release them upon return (even if a delegated-to command throws an exception), the "filter" extension to "command" provides a postprocess() method for this cleanup. Finally, commands can be stored and looked up in a "catalog" to allow deferral of the decision on which command (or chain) is actually executed.

To maximize the usefulness of the Chain of Responsibility pattern APIs, the fundamental interface contracts are defined in a manner with zero dependencies other than an appropriate JDK. Convenience base class implementations of these APIs are provided, as well as more specialized (but optional) implementations for the web environment (i.e. servlets and portlets).

Given that command implementations are designed to conform with these recommendations, it should be feasible to utilize the Chain of Responsibility APIs in the "front controller" of a web application framework (such as Struts), but also be able to use it in the business logic and persistence tiers to model complex computational requirements via composition. In addition, separation of a computation into discrete commands that operate on a general purpose context allows easier creation of commands that are unit testable, because the impact of executing a command can be directly measured by observing the corresponding state changes in the context that is supplied...


答:
Refactoring - is like organizing your clothes cabinet / Tool Drawer.

You dont throw away your clothes /tools just because they are all over the place.

You could argue that they should never get disorganized. But they do.

Just like code does. Especially as it grows over time.

And if you dont clean it up, you will keep wondering what happened to that t-shirt you loved or that wrench that you always need but can never find!

Title: How do you explain refactoring to a non-technical person?

Body:
How do you go about explaining refactoring (and technical debt) to a non-technical person (typically a PHB or customer)? ("What, it's going to cost me a month of your work with no visible difference?!")

UPDATE Thanks for all the answers so far, I think this list will provide several useful analogies to which we can point the appropriate people (though editing out references to PHBs may be wise!)

ContentLicense: CC BY-SA 2.5


问:
Date calculation algorithm
I'm working on a project to schedule a machine shop, basically I've got everything covered BUT date calculations, I've got a method called schedule (working on PHP here):

```<code>public function schedule($start_date, $duration_in_minutes)
</code>```

Now my problem is, currently I'm calculating end time manually because time calculations have the following rules:

During weekdays, work with business hours (7:00 AM to 5:00 PM)

Work on Saturdays from 7:00 AM to 2:00 PM

Ignore holidays (in Colombia we have A LOT of holidays)

I already have a lookup table for holidays, I also have a Java version of this algorithm that I wrote for a previous version of the project, but that one's also manual.

Is there any way to calculate an end time from a start time given duration?, my problem is that I have to consider the above rules, I'm looking for a (maybe?) math based solution, however I currently don't have the mind to devise such a solution myself.

I'll be happy to provide code samples if necessary.

答:
What you can do is as below:

Keep the timezone of Columbia as default when you are using this function.

take an array of dates which having holiday and skip those dates all hours in using this.

check whether it is Saturday, than keep only limited hours you want.

for all other days keep working hours in calculations.

    a) for weekdays/Saturday you will have to check for timings like 7am to 5pm and 7am to 2pm and with conditions and looping of each minutes increment and also condition to check about duration. That's it.

Its bit told simply but without code, this is enough.

Title: Date calculation algorithm


问:
How to get hardware specific ID
We have an application that we need to ensure that our APPLICATION DATA should not be used (or opened) in different computers with same users. For that we thought about getting harddisk GUID as a part of data encryption private key. In this case raid disks, virtual PCs would fail and wouldn't be able to open the data. We need some advice about how to get a proper id to strict user-per computer but not user-harddisk.

Note: Both Mac and Windows supported

Edit: it was about application data, but not the application itself. Sorry for wrong asking

答: Maybe the MAC Adress of the Network adapter might be a proper solution for you. But even this cannot asure you a 100% unique ID because the Adapter can be built into another PC. But no matter what you do without a service based application you cannot 100% control who is allowe</p>

Title: How to get hardware specific ID


答:
There are a few thoughts that leap to mind, first of which is that I don't have enough information.

Does each step produce data used beyond the pipeline, or do we only care about the results of the last stage?

Are there many big data concerns? ie. memory concerns, speed concerns, etc

The answers would probably make me think more carefully about the design, however based on what you said there are 2 approaches I would probably consider first.

Structure each stage as it's own object.  The nth stage would have 1 through n-1 stages as a list of delegates.  The each stage encapsulates the data and the processing of the data; reducing overall complexity and fields within each object.  You can also have later stages access the data as needed from much earlier stages by traversing the delegates. You still have pretty tight coupling across all the objects because it's the results of the stages (ie. all the attrs) that are important, but it's significantly reduced and each stage/object is probably more readable and understandable.  You could make it thread safe by making the list of delegates lazy and using a thread safe queue to populate the delegate list in each object as needed.

Alternatively I would probably do something similar to what your doing.  A massive data object that goes through functions representing each stage.  This is often much faster and light weight, but more complex and error prone because of it's just a big pile of data attributes.  Obviously not thread-safe.

Honestly I done the later one more often for ETL and some other similar problems.  I was focused on performance because of the amount of data rather than maintainability.  Also, they were one-offs which wouldn't be used again.

Title: Good implementation strategies for encapsulating shared data in a software pipeline

Body:
I'm working on re-factoring certain aspects of an existing web service. The way the service APIs are implemented is by having a kind of "processing pipeline", where there are tasks that are performed in sequence. Unsurprisingly, later tasks may need information computed by earlier tasks, and currently the way this is done is by adding fields to a "pipeline state" class.

I've been thinking (and hoping?) that there's a better way to share information between pipeline steps than having a data object with a zillion fields, some of which make sense to some processing steps and not to others. It would be a major pain to make this class thread-safe (I don't know if it would even be possible), there is no way to reason about its invariants (and it's likely it doesn't have any).

I was paging through the Gang of Four design patterns book to find some inspiration, but I didn't feel like there was a solution in there (Memento was somewhat in the same spirit, but not quite). I also looked online, but the second you search for "pipeline" or "workflow" you get flooded with either Unix pipes information, or proprietary workflow engines and frameworks.

My question is - how would you approach the issue of recording the execution state of a software processing pipeline, so that later tasks can use information computed by earlier ones? I guess the major difference with Unix pipes is that you don't just care about the output of the immediately preceding task.

As requested, some pseudocode to illustrate my use case:

The "pipeline context" object has a bunch of fields that the different pipeline steps can populate/read:

```<code>public class PipelineCtx {
    ... // fields
    public Foo getFoo() { return this.foo; }
    public void setFoo(Foo aFoo) { this.foo = aFoo; }
    public Bar getBar() { return this.bar; }
    public void setBar(Bar aBar) { this.bar = aBar; }
    ... // more methods
}
</code>```

Each of the pipeline steps is also an object:

```<code>public abstract class PipelineStep {
    public abstract PipelineCtx doWork(PipelineCtx ctx);
}

public class BarStep extends PipelineStep {
    @Override
    public PipelineCtx doWork(PipelieCtx ctx) {
        // do work based on the stuff in ctx
        Bar theBar = ...; // compute it
        ctx.setBar(theBar);

        return ctx;
    }
}
</code>```

Similarly for a hypothetical FooStep, which might need the Bar computed by BarStep before it, along with other data. And then we have the real API call:

```<code>public class BlahOperation extends ProprietaryWebServiceApiBase {
    public BlahResponse handle(BlahRequest request) {
        PipelineCtx ctx = PipelineCtx.from(request);

        // some steps happen here
        // ...

        BarStep barStep = new BarStep();
        barStep.doWork(crx);

        // some more steps maybe
        // ...

        FooStep fooStep = new FooStep();
        fooStep.doWork(ctx);

        // final steps ...

        return BlahResponse.from(ctx);
    }
}
</code>```


答: In essence, archiving and compressing are two different operations. The tar.gz very clearly shows the intention: a compressed archive whereas a .zip or .rar just shows it's some compressed stuff.</p>

Title: When did the standard for packaging Linux source code become .tar.gz?

Body:
When browsing open-source projects that are primarily developed for Linux systems and downloading the latest packages, the source code is always stored in a .tar.gz or .tar.bz2 file.

Is there any reason for using .tar.gz or .tar.bz2 rather than something like .zip or .rar or some other compression algorithm (or even leaving it uncompressed if the project is small enough)?


答:
It's traditional, ubiquitous, and it works.  Plus I thought it was somewhat self apparent.

Update

My apologies, I forget most people don't know what I know or have experience as an administrator in heterogeneous environments.

Tradition as in a custom or practice ingrained over time.  We know it has basis in history because tar derives from Tape ARchive referencing the old tape backup technology.  It has a long history in the various Unix operating systems dating back to 1979 in 7th edition Unix where it replaced tp.  Linux systems are usually an amalgamation of the Linux Kernel and GNU software of which GNU tar is a part of.  All this tar history means a majority of experienced technical people know how to use it without having to refer to documentation because it's been ingrained.  For newer users there is plenty of documentation because the software has been around for so long.

Ubiquitous as in appearing or found everywhere.  A somewhat accepted misuse is where the appearance isn't universal, but in large enough percentage of the population to be accepted as ubiquitous.  7th Edition Unix is the ancestor of the biggest versions of Unix including Sun OS/Solaris, AIX, HPUX, AIX, BSD, etc. There is also a high degree of cross-compatibility across the different implementations of tar on unix.  Since MacOS (since OS 10) has been based on BSD it also has tar.  Linux uses GNU software which includes GNU Tar so tar is available on all flavors of Linux.  AND, while not available as a builtin there are many implementations of tar available on Windows including GNU Tar through cygwin and natively.  GNU Tar in particular is available on most Unices and Windows making it the good choice for file migrations across OSes.

Works as in it's been functioning for a long time without major modifications.  It's available on all major platforms out of the box (except for Windows, where it's available as additional software).  The format is also supported on all major platforms which facilitates interchange between platforms. Not only is it still used as a way to make easily portable archives, but a tar-pipe is a standard Unix idiom for copying directory trees, especially across heterogenous environments. In short, it's been around and still in heavy use because it does what it does well.


问:
Functions returning pointers
C++ noob here. I have a very basic question about a construct I found in the C++ book I am reading.

```<code>// class declaration
class CStr {
  char sData[256];
 public:
  char* get(void);
};

// implementation of the function
char* CStr::get(void) {
  return sData;
}
</code>```

So the Cstr::get function is obviously meant to return a character pointer, but the function is passing what looks like the value (return sData). Does C++ know to return the address of the returned object? My guess would have been that the function definition would be return &sData.

答:
In C and C++ returning the name of an array is same as returning the Address of the first element in an array hence you can return the same address in three different ways :

return sData;

return &sData;

return &sData[0];

all the three statements return the same address.

Title: Functions returning pointers


答:
The point of re-factoring is to simplify the design and remove inefficiencies. This makes it easier to fix bugs and add new features in the future.

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

If you continue to add new features to code, re-factoring will quickly pay for itself. This will be visible in lower error rate, faster debugging and quicker fixes.


问:
How to properly include field validation in a Software Documenation
I'm developing a software documentation in a project, and much of it are just CRUD or CRUD based functions. As you can imagine, a lot of the rules are constraints about fields validation, things like length, range, data type and masks of the field.

Writing all those rules would be cumbersome to write and to read, so I'm wondering, what are the option available to include such rules in a software documentation, in a way that it is not tedious to write/read it all?

Edit - Clarification

The rules and being taken from an old desktop legacy application, and we are going to document the current validations, features and forms; so the application will be implemented in a more up-to-date (web) platform, considering usability and consistency in the new system. The documentation is handwritten using the Sybase PowerDesigner tool, but the document can be written in doc inside the tool.

Some of it are cross-field validation rules, for example;

For a person of type X, residing on country Y, the value of field A must be validated using the B rule.

For a person of type X, residing on country Z, the value of field A must be validated using the C rule, and the field D, validated through E rule.

Type X, country Y, field A, field D, etc, are all values extracted from fields on the forms.

答:
So you have an old legacy application at hand which contains already all the rules you are going to document, and you are looking for a way to somehow "extract" some of the rules out of it, without writing them down manually.

Actually, if that is possible depends completely on the technology and architecture of that application. You did not tell us anything about those things, so I can give you only some very general advice.

The key factor here is how much meta data the sources of the old legacy system contain. By "meta data" I mean any kind of machine readable, self-describing information. If there is some metadata, you can use it as input for some kind of doc generator you will have to write.

For example, if the legacy application is database-founded, there is a good place to start with. Almost any serious database allows the extraction of table names, attribute names, attribute data types, db constraints etc. in a programmatic way. So either you write yourself a program which extracts those information out of the DB, or you use the reverse engineering capabilities  of PowerDesigner which allow you to generate a complete ER model within minutes.

If the application is not database founded, or the validation rules are not implemented as database constraints, the task is typically getting harder. Does the old technology used allow to determine which forms are available? Does it allow to extract which attributes are on each form, and was there a standard way to add validation rules by configuration instead of coding? Learn enough about the old technology to answer that kind of questions. Then you may have a chance to save some manual documentation work.

However, features and validation rules of the old legacy application which are buried in some pile of hand-written code can almost never be extracted automatically. Don't expect any "magic bullet" to to solve this problem for you - there is none, this part of the docs you will have to write manually. Find out about the rules either by reading the existing docs of the old application, by reading/debugging the source code of that application or by try-and-error using the application.

EDIT: you asked for a way to avoid tedious writing work as well as tedious reading. My answer above was how to avoid tedious writing. And I guess the reading of such validation rules will be always a little bit tedious, independently of the form you choose.

However, if there is no existing meta data available, it may be good idea to create such metadata during your documentation process, for example, within your PowerDesigner models. PowerDesigner is tool where AFAIK you can store all model data in a central repository. Due to the manual, it has scripting capabilitities (it seems to have a COM API which can can be accessed by any COM capable programming language from outside) and it may also be possible to extend the PowerDesigner meta model to your needs. So instead of writing all your validation rules into separate documents in a verbal form, learn enough about your PowerDesigner tool that you can store that information in a machine-readable form there. Then develop a doc generator using the inbuild scripting capabilities or the COM API.

This way, you can keep the documentation source very compact, without much redundancy. The generated docs will have 100% consistent layout, and if needed they can be easily tailored for different purposes. If the "readers" of the docs don't like the form, just change the generator and regenerate the docs again.

Of course, this effort only pays for applications of a certain size. I have done something similar in the past for two different CASE tools, and in reality it is easier than it may sound at a first glance.


问:
Does auto make C++ code harder to understand?
I saw a conference by Herb Sutter where he encourages every C++ programmer to use auto.

I had to read C# code some time ago where var was extensively used and the code was very hard to understand—every time var was used I had to check the return type of the right side. Sometimes more than once, because I forgot the type of the variable after a while!

I know the compiler knows the type and I don’t have to write it, but it is widely accepted that we should write code for programmers, not for compilers.

I also know that is more easy to write:

```<code>auto x = GetX();
</code>```

Than:

```<code>someWeirdTemplate<someOtherVeryLongNameType, ...>::someOtherLongType x = GetX();
</code>```

But this is written only once and the GetX() return type is checked many times to understand what type x has.

This made me wonder—does auto make C++ code harder to understand?

答:
I'm quite surprised that no one pointed out yet that auto helps if there is no clear type. In this case, you either work around this problem by using a #define or a typedef in a template to finding the actual usable type (and this is sometimes not trivial), or you just use auto.

Suppose you got a function, that returns something with platform-specific type:

```<code>#ifdef PLATFROM1
__int256 getStuff();
#else //PLATFORM2
__int128 getStuff();
#endif
</code>```

Witch usage would you prefer?

```<code>#ifdef PLATFORM1
__int256 stuff = getStuff();
#else
__int128 stuff = getStuff();
#endif
</code>```

or just simply

```<code>auto stuff = getStuff();
</code>```

Sure, you can write

```<code>#define StuffType (...)
</code>```

as well somewhere, but does

```<code>StuffType stuff = getStuff();
</code>```

actually tell anything more about x's type? It tells it is what is returned from there, but it is exactly what auto is. This is just redundant - 'stuff' is written 3 times here - this in my opinion makes it less readable than the 'auto' version.

OwnerDisplayName: Felics

Body:
I'm quite surprised that no one pointed out yet that auto helps if there is no clear type. In this case, you either work around this problem by using a #define or a typedef in a template to finding the actual usable type (and this is sometimes not trivial), or you just use auto.

Suppose you got a function, that returns something with platform-specific type:

#ifdef PLATFROM1
__int256 getStuff();
#else //PLATFORM2
__int128 getStuff();
#endif

Witch usage would you prefer?

#ifdef PLATFORM1
__int256 stuff = getStuff();
#else
__int128 stuff = getStuff();
#endif

or just simply

auto stuff = getStuff();

Sure, you can write

#define StuffType (...)

as well somewhere, but does

StuffType stuff = getStuff();

actually tell anything more about x's type? It tells it is what is returned from there, but it is exactly what auto is. This is just redundant - 'stuff' is written 3 times here - this in my opinion makes it less readable than the 'auto' version.


问:
Where do the parser and service objects fit in MVC?
Do NSURLConnection service objects and XML/JSON parser objects fall within the controller layer or the model layer? Why?

Is it OK to have business logic in the controller? Or should it be in the model layer only?

Can the model layer be represented by NSArray/NSDictionary objects or should it be strictly structured with custom objects to comply with the MVC pattern, given that my app doesn't require persistent storage.

答:
All your business rules (and application) should be in the model layer of your application. The controller should just be collecting (from models to views) and sending (from URL requests to models) the data.

Your models can be composed in two layers, the business logic (and application) and your data access layer. Your data access layer execute queries (SQL, NoSQL, Web Service or even text files).

Your models should not be "aware" of the type of storage you are using. This way, you can change and combine different data access mecanism (your users are in a database and the rest of the data comes from a web service for example).

To cleanly integrate your data access layer in your models you should rely on dependency injection


问:
Should database queries be abstracted out of the page itself?
When writing page generation in PHP, I often find myself writing a set of files littered with database queries. For example, I might have a query to fetch some data about a post directly from the database to display on a page, like this:

```<code>$statement = $db->prepare('SELECT * FROM posts WHERE id=:id');
$statement->bindValue(':id', $id, PDO::PARAM_INT);
$statement->execute();
$post = $statement->fetch(PDO::FETCH_ASSOC);
$content = $post['content']
// do something with the content
</code>```

These quick, one-off queries are usually small, but I sometimes end up with large portions of database interaction code which begins to look pretty messy.

In some cases, I've solved this problem by creating a simple library of functions to handle my post-related db queries, shortening that block of code to a simple:

```<code>$content = post_get_content($id);
</code>```

And that's great. Or at least it is until I need to do something else. Maybe I need to get the five most recent posts to display in a list. Well, I could always add another function:

```<code>$recent_posts = post_get_recent(5);
foreach ($recent_posts as $post) { ... }
</code>```

But that ends up using a SELECT * query, which I usually really don't need anyway, but is often too complicated to reasonably abstract. I eventually end up with either a massive library of database interaction functions for every single use case, or a series of messy queries inside every page's code. And even once I've built these libraries, I'll find myself needing to do one tiny join that I hadn't used before, and I suddenly need to write another highly-specialized function to do the job.

Sure, I could use the functions for general use cases and queries for specific interactions, but as soon as I start writing raw queries I begin to slip back into direct access for everything. Either that, or I'll get lazy and will start doing things in PHP loops that should really be done directly in the MySQL queries, anyway.

I'd like to ask those more experienced with writing internet applications: is the maintainability boost worth the extra lines of code and possible inefficiencies that the abstractions may introduce? Or is simply using direct query strings an acceptable method for handling database interactions?

答:
When you have too many specialized query functions you could try breaking them into composable bits.  For instance

```<code>$posts = posts()->joinWithComments()->orderBy("post.post_date")->first(5);
</code>```

There is also a hierarchy of abstraction levels you might find useful to keep in mind.  You have

mysql API

your mysql functions, such as select("select * from posts where foo = bar"); or maybe more composable as select("posts")->where("foo = bar")->first(5)

functions that are specific to your application domain, for instance posts()->joinWithComments()

functions that are specific to a particular page, such as commentsToBeReviewed($currentUser)

It pays a lot in terms of ease of maintenance to respect this order of abstractions.  The pages scripts should use only level 4 functions, level 4 functions should be written in terms of level 3 functions, and so on.  It's true that this takes a bit more time upfront but it will help keep your maintenance costs constant over time (as opposed to "oh my gosh they want another change!!!")

Body:
When you have too many specialized query functions you could try breaking them into composable bits.  For instance

$posts = posts()->joinWithComments()->orderBy("post.post_date")->first(5);

There is also a hierarchy of abstraction levels you might find useful to keep in mind.  You have

mysql API

your mysql functions, such as select("select * from posts where foo = bar"); or maybe more composable as select("posts")->where("foo = bar")->first(5)

functions that are specific to your application domain, for instance posts()->joinWithComments()

functions that are specific to a particular page, such as commentsToBeReviewed($currentUser)

It pays a lot in terms of ease of maintenance to respect this order of abstractions.  The pages scripts should use only level 4 functions, level 4 functions should be written in terms of level 3 functions, and so on.  It's true that this takes a bit more time upfront but it will help keep your maintenance costs constant over time (as opposed to "oh my gosh they want another change!!!")


答:
The main reason to use a pipeline design is that you want to decouple the stages. Either because one stage may be used in multiple pipelines (like the Unix shell tools), or because you gain some scaling benefit (ie, you can easily move from a single-node architecture to a multi-node architecture).

In either case, each stage in the pipeline needs to be given everything that it needs to do its job. There's no reason that you can't use an external store (eg, database), but in most cases it's better to pass the data from one stage to another.

However, that doesn't mean that you must or should pass one big message object with every possible field (although see below). Instead, each stage in the pipeline should define interfaces for its input and output messages, that identify just the data that stage needs.

You then have a lot of flexibility in how you implement your actual message objects. One approach is to use a huge data object that implements all the necessary interfaces. Another is to create wrapper classes around a simple Map. Still another is to create a wrapper class around a database.


问:
Motivation and pitfalls (?) of the auto keyword in C++11
I was recently wondering why the keyword auto was chosen in C++11 to mark a variable whose type must be inferred by the compiler, like in

```<code>auto x = 1;
</code>```

Since

var seems more common in other programming languages (e.g. C#, Scala, JavaScript), and

As far as I understand the new semantics of auto breaks backward compatibility (it was rarely used but had a different meaning in previous revisions of C++, see e.g. here)

I wanted to ask if there was a special reason for choosing auto (in favour of var or any other keyword). Was there any specific discussion about this issue before the C++11 standard was released?

Also, are there any possible incompatibilities we should watch out for when recompiling legacy C++ code with a C++11 compiler?

答:
Almost every word you might think of adding as a keyword to a language has almost certainly been used as a variable name or some other part of working code. This code would be broken if you made that word a keyword.

The incredibly lucky thing about auto is that it already was a keyword, so people didn't have variables with that name, but nobody used it, because it was the default. Why type:

```<code>auto int i=0;
</code>```

when

```<code>int i=0;
</code>```

meant exactly the same thing?

I suppose somewhere on the planet there was some small amount of code that used 'auto' the old way. But it could be fixed by removing the 'auto' and it would be working again. So it was a pretty obvious choice to repurpose the keyword.

I also happen to think it's a clearer meaning. If you've worked with variants and such, when you see var you may think that the declaration is somehow less strongly typed than if you pressed all the keys yourself on the keyboard to specify the type of the variable. To me, auto makes it clearer that you're asking the compiler to automatically deduce the type, which is just as strong as if you had specified it yourself. So it really was a very lucky break that made a good name available to the committee.

To clarify the (small) breaking:

If you had

```<code>auto int i=0;
</code>```

and tried to compile with a C++ 11 compiler, you will now get an error such as

error C3530: 'auto' cannot be combined with any other type-specifier

This is trivial, you just remove either the auto or the int and recompile.

There is a bigger problem though. If you had

```<code>auto i = 4.3;
</code>```

C and the really old C++ would make i an int (as it would if you left off auto - default declaration was int). If you have gone a really long time without compiling this code, or have been using old compilers, you could have some of this code, at least in theory. C++ 11 would make it a double since that's what 4.3 is. (Or maybe a float, I'm still in Boxing Day mode, but the point is, not an int.) This might introduce subtle bugs throughout your app. And without any warnings or errors from the compiler. People in this boat should search globablly for auto to make sure they weren't using it the old way before they move to a C++ 11 compiler. Luckily, such code is extremely rare.

Body:
Almost every word you might think of adding as a keyword to a language has almost certainly been used as a variable name or some other part of working code. This code would be broken if you made that word a keyword.

The incredibly lucky thing about auto is that it already was a keyword, so people didn't have variables with that name, but nobody used it, because it was the default. Why type:

auto int i=0;

when

int i=0;

meant exactly the same thing?

I suppose somewhere on the planet there was some small amount of code that used 'auto' the old way. But it could be fixed by removing the 'auto' and it would be working again. So it was a pretty obvious choice to repurpose the keyword.

I also happen to think it's a clearer meaning. If you've worked with variants and such, when you see var you may think that the declaration is somehow less strongly typed than if you pressed all the keys yourself on the keyboard to specify the type of the variable. To me, auto makes it clearer that you're asking the compiler to automatically deduce the type, which is just as strong as if you had specified it yourself. So it really was a very lucky break that made a good name available to the committee.

To clarify the (small) breaking:

If you had

auto int i=0;

and tried to compile with a C++ 11 compiler, you will now get an error such as

error C3530: 'auto' cannot be combined with any other type-specifier

This is trivial, you just remove either the auto or the int and recompile.

There is a bigger problem though. If you had

auto i = 4.3;

C and the really old C++ would make i an int (as it would if you left off auto - default declaration was int). If you have gone a really long time without compiling this code, or have been using old compilers, you could have some of this code, at least in theory. C++ 11 would make it a double since that's what 4.3 is. (Or maybe a float, I'm still in Boxing Day mode, but the point is, not an int.) This might introduce subtle bugs throughout your app. And without any warnings or errors from the compiler. People in this boat should search globablly for auto to make sure they weren't using it the old way before they move to a C++ 11 compiler. Luckily, such code is extremely rare.


问:
How should I organize bugs in redmine?
I'm helping to reogranize several redmine projects; although I have a lot of experience with issue tracking systems, I've never worked with redmine before.

What is the best way to organize Issues in Redmine so that they can be easily grouped by:

feature (e.g. "Upload a file", "Login to site", "Send message")

system component (e.g. front-end, back-end, database), and

target version ("beta 1", "beta 2" "GA")

Right now, most "Bugs" are child issues of "Features"; unfortunately, this means that the Target Version of each bug is automatically populated with the Target Version of the parent feature. Is there some way to fix this?

答:
Assuming that one can move bugs to their own item (not sub features), the way to relate bugs and features is to relate them to each other.  This will fix the target version being populated correctly and allow you to use the roadmap with its intended functionality.

The next consideration is "are features actually things to do? or are they general areas of the site?"

If you look at how Redmine organizes itself you will see "Category" being used.  These are what I believe your 'features' really are.  This becomes even easier to work with - you set up the categories in your project and the category becomes a drop down on the issues page.  The roadmap can then show what categories are going out in the next target version very cleanly.  Reports can easily be generated against categories.

The system component I believe would be best served with a custom field that allows a list (possibly the multiple, though you might also consider separate sub-tasks under an issue with one for each task - "modify database" and "modify back-end" for a single bug could be assigned to different people).

If in doubt, Redmine issue tracking for itself is likely the best example of how to organize Redmine.

Title: How should I organize bugs in redmine?


问:
How do open source projects maintain quality?
How do open source projects maintain quality?
What keeps the projects from people with relatively little programming experience checking in poor quality codes?</p>

答:
Some don't.

Those that work have a single person (or if very large a group with well defined responsibilities) who vet everything and only let what meets their standards into the official codebase. (Private branches = private problems).


问:
Should I use both WCF and ASP.NET Web API
We already have a WCF API with basichttpbinding.
Some of the calls have complex objects in both the response and request.

We need to add RESTful abilities to the API.
at first I tried adding a webHttp endpoint, but I got

```<code>At most one body parameter can be serialized without wrapper elements
</code>```

If I made it Wrapped it wasn't pure as I need it to be.

I got to read this, and this (which states "ASP.NET Web API is the new way to build RESTful service on .NET").

So my question is, should I make 2 APIs(2 different projects)? one for SOAP with WCF and one RESTful with ASP.NET Web API? is there anything wrong architecturally speaking with this approach?

答:
This isn't really a direct answer to your question, but an alternative for you to explore.

In addition to my other answer, you can also check out another .NET web service framework called ServiceStack. Some good points about it:

Open source.

Support both SOAP and REST endpoints out of the box.

Focus on performance, e.g. fastest text serializers in .NET, Redis support.

Adhere to best practices, e.g. Martin Fowler's EAA, message-based web service.

Extensive documentation at GitHub Wiki.

Good support at StackOverflow with the servicestack tag, by the project creator Demis Bellot (aka. mythz).

Notable mentions comparing ServiceStack and ASP.NET Web API:

ServiceStack vs ASP.Net Web API on StackOverflow.

ServiceStack versus ASP .NET Web API on LinkedIn.

If you want to know more about ServiceStack, be sure to check out their official site, with codes and documentation at GitHub, and a presentation at slideshare.


问:
What data structure could a word processor use to map the user's caret position/text selection to its internal representation of the document?
Word processors (e.g. Microsoft Word) display documents to the user as styled text. The user can select a part of this text and apply styles to it, and edit the text.

The word processor must (I guess) have an internal representation of the document that indicates which bits of the text displayed to the user should be styled differently. But the user doesn't interact with this internal representation. They interact with the text, by using the caret and selecting portions of it.

What data structure might the word processor use to efficiently map the text with which the user interacts to its internal model of the document?

答:
I assume it is using some kind of tree representation. Nodes of this tree would define styling , eg. all text under this node has this style and end leafs of this tree would be raw text. Then by editing the leaves, you edit the raw text, but formatting remains same. This also allows for nesting of styles.

Selecting the text usually means picking node where selection starts and node where selection ends, thus allowing you select different styled and formatted text. Then by applying formatting to the selection, you apply complex modification to this tree.

Displaying this tree then might result in complex visual document.

You might also check out LaTex, which is pretty much creation of rich visual documents and DTP from it's internal representation. Because LaTex documents are by definition readable and processable by computers, it might also be used as internal representation of those documents.


答:
Controller's job should be to just handle request , validate it and call appropriate model component to do the actual job and once control comes back send the response back to client/view.

So things like parsing or any actvity/processing which is specific to service should be done at Model layer.

Title: Where do the parser and service objects fit in MVC?

Body:
Do NSURLConnection service objects and XML/JSON parser objects fall within the controller layer or the model layer? Why?

Is it OK to have business logic in the controller? Or should it be in the model layer only?

Can the model layer be represented by NSArray/NSDictionary objects or should it be strictly structured with custom objects to comply with the MVC pattern, given that my app doesn't require persistent storage.


答:
There are an infinite number of ways to do it, but the basic concept isn't that hard.  Say you used html for your internal representation:

```<code><strong>bold text here</strong> non-bold.
</code>```

If your GUI widget tells you the cursor is after the 4th character, all you have to do is count to the 4th character, but when you come to something inside angle brackets, you don't count it, but instead keep track of what formatting it is applying or unapplying.

Obviously, for a large document you don't want to count characters from the beginning every time you press a key, so they use more efficient data structures, but the basic concept is the same.  You have some sort of mapping between visible characters and their metadata.

Title: What data structure could a word processor use to map the user's caret position/text selection to its internal representation of the document?

Body:
Word processors (e.g. Microsoft Word) display documents to the user as styled text. The user can select a part of this text and apply styles to it, and edit the text.

The word processor must (I guess) have an internal representation of the document that indicates which bits of the text displayed to the user should be styled differently. But the user doesn't interact with this internal representation. They interact with the text, by using the caret and selecting portions of it.

What data structure might the word processor use to efficiently map the text with which the user interacts to its internal model of the document?

Body:
There are an infinite number of ways to do it, but the basic concept isn't that hard.  Say you used html for your internal representation:

<strong>bold text here</strong> non-bold.

If your GUI widget tells you the cursor is after the 4th character, all you have to do is count to the 4th character, but when you come to something inside angle brackets, you don't count it, but instead keep track of what formatting it is applying or unapplying.

Obviously, for a large document you don't want to count characters from the beginning every time you press a key, so they use more efficient data structures, but the basic concept is the same.  You have some sort of mapping between visible characters and their metadata.


问:
is it possible to monitor more than one stream simultanously?
E.g.

- $stream1 is the STDOUT of a child process and $stream2 is the STDERR of the same child process

- $stream1 is one child process and $stream2 is another child process

Is there a possiblility in perl to monitor two or more streams at the same time?

So we loop as long as anything pops-up in any of the streams and we take whatever comes first either in $stream1 or $stream2.

Something like

```<code>while (my $line = <$stream1 or $stream2> ) {
    #do something with the $line
}
</code>```

??

答:
Sure there is - it's Perl, after all - just not with quite such an elegant syntax.

Monitoring several streams boils down to judicious use of the select syscall, and in Perl that means using the four-argument version of select, which wraps this syscall. Many people find this a bit too cumbersome and low-level, so of course there is a module which further wraps the pattern for your convenience.


答:
You can't, and it's a terrible idea anyway.  People use multiple computers, and even on their primary computer, they generally change their computer hardware more frequently than their software.  Back when I used software like yours, I would disable that protection so I could properly use the software I paid for.  Now, I don't even bother, and just buy from your less draconian competitors instead.

People can set their own MAC addresses, so that's not really a solution.  Also, routers change the MAC address on packets, so a central server has no access to it.

If you really want to restrict by hardware, the only real way to do it is to supply your own dongle that must be attached to the computer.  Yes, you can move the dongle, but you're still restricting use to a physical piece of hardware, so you can't just email someone a license key.  You almost never see these because they're annoying for both users and distributors.

The most common form of user restriction nowadays is probably the license server.  The software contacts a server to obtain a license, and must release the license before it can be used again somewhere else.  This lets a user use software on multiple computers, but only one at a time, which really should be your goal here.  It's still a little annoying for users, but acceptable if the software is high quality.

Title: How to get hardware specific ID

Body:
We have an application that we need to ensure that our APPLICATION DATA should not be used (or opened) in different computers with same users. For that we thought about getting harddisk GUID as a part of data encryption private key. In this case raid disks, virtual PCs would fail and wouldn't be able to open the data. We need some advice about how to get a proper id to strict user-per computer but not user-harddisk.

Note: Both Mac and Windows supported

Edit: it was about application data, but not the application itself. Sorry for wrong asking


问:
How do I design a DAL when I have to deal with relationships?
Say I'm developing a bug tracker, where a ticket belongs to at most one milestone, and a milestone can have many tickets. When a milestone is deleted (from the database), all tickets associated with that milestone must have their relationship unset (i.e. set to null). This is a simple relationship.

The classes are fairly simple, and map directly to a database:

```<code>public class Ticket {
    public ObjectId Id { get; set; }
    public string Title { get; set; }
    public ObjectId MilestoneId { get; set; }
}

public class Milestone {
    public ObjectId Id { get; set; }
    public string Title { get; set; }
}
</code>```

Now comes the tricky part: where and how do I reset the MilestoneId fields? One possible solution is to write a data access layer by creating one giant class with all data accessing methods for all kinds of objects, in this case tickets and milestones. Another possible solution is to write several classes (e.g. TicketProvider and MilestoneProvider), one for each kind of object, that provide data accessing methods such as Find, Save and Destroy.

The latter appeals more to me since I don't like monsterous classes, but there is one caveat: the method that deletes milestones has to reset the MilestoneIds of all associated tickets to null. This means that MilestoneProvider, which is responsible for manipulating milestones, suddenly deals with tickets!

How are relationships commonly dealt with in data access layers, and how can I prevent violation of SRP? Should I put the entire DAL in one class, or should I separate it and if so, how can I best do that?

答: Create a readonly property in the parent class, check whether the retrieved child id is nil den increment it or assign it from db.</p>


问:
Design Parts DB
I'm developing a tool that handles (electrical) parts. The parts can be created, viewed, modified, deleted, grouped and so on...

In order to make this question useful for future visitors I like to keep this question universal since managing parts in a DB is very common no matter what parts are in the DB (CDs, cars, food, students, ...).

I am thinking of 3 different DB designs:

Using a parts table and derived tables for specialized part attributes.

```<code>Parts      (id, part_type_id, name)
PartTypes  (id, name)
Wires      (id, part_id, lenght, diameter, material)
Contacts   (id, part_id, description, picture)
</code>```

Using only specialized part tables.

```<code>Wires      (id, name, lenght, diameter, material)
Contacts   (id, name, description, picture)
</code>```

Using a Parts-, PartTypes-, ValueTypes- and PartValues table that contain all values.

```<code>PartTypes  (id, name)
ValueTypes (id, part_type_id, name)
Parts      (id, part_type_id, name)
PartValues (part_id, value_type_id, value)
</code>```

Which one to prefer and why? Or is there a better one?

I am concerned about the DB queries. I don't want the queries become overly slow or complicated.

Update

The number of types in the DB are pretty much given and static since they rest on a international standard and will be enhanced seldomly.

答:
I go option 3

Option 1 is bad because you don't want your joins to be based off a filed value. ( ie If type ="Wire" join to TblWire)

Option 2 is bad because you have no way of reporting on your inventory as a whole

Title: Design Parts DB


问:
Are there any programming languages that follow a minimalist development approach?
I find it that when languages are considered the same as commercial software, there is always a constant need to add new features to justify new releases.

Can there be or are there languages where version 1.0 is the final version? Of course bug fixes are exempt from this, but the feature set always remains the same?

This way every feature in the language fits together nicely and not seem like they are bolted on after the fact with obsolete features still around because of backwards compatibility.

I assume some academic languages are like this? But are there commercially successful languages that follows this idea? The accompanying library is also free to get new features too, but the language always remains constant.

One example I can give is, one of my favourite languages C#, which I use pretty often, more and more features are being added every release. To take advantages of these, I have to drop actual tasks in hand, and spend considerable time learning these instead of being able to pick up trivial concepts and combine those myself to solve more complex problems with ease.

So I guess I am looking for a minimalist approach where everything is consistent, makes sense, and is as orthogonal as possible.

答:
I think Python's a reasonable candidate for a language with minimalism as one of its design goals. It's based around a relatively small number of core concepts, and version 3 attempted to, amongst other things, simplify the language a bit by removing some features.

(Granted, that's not the same as a feature set that stayed the same from version 1, but I think that's a fairly arbitrary way to evaluate languages, given that language authors can call it version 1 whenever they want.)


答:
Option 3 is more generic and can accommodate more use cases.

Going option 3 you may need more joins and complex queries for simple features, in option 2 you'd need complex queries for "big" features like inventory and reports, and may need use unions to accomplish that.

You can always simplify you queries in options 3 using Views, if you very often needs only the Wire or Contact, make a View for each of them. You can optimize it if it becomes necessary.

Title: Design Parts DB

Body:
I'm developing a tool that handles (electrical) parts. The parts can be created, viewed, modified, deleted, grouped and so on...

In order to make this question useful for future visitors I like to keep this question universal since managing parts in a DB is very common no matter what parts are in the DB (CDs, cars, food, students, ...).

I am thinking of 3 different DB designs:

Using a parts table and derived tables for specialized part attributes.

```<code>Parts      (id, part_type_id, name)
PartTypes  (id, name)
Wires      (id, part_id, lenght, diameter, material)
Contacts   (id, part_id, description, picture)
</code>```

Using only specialized part tables.

```<code>Wires      (id, name, lenght, diameter, material)
Contacts   (id, name, description, picture)
</code>```

Using a Parts-, PartTypes-, ValueTypes- and PartValues table that contain all values.

```<code>PartTypes  (id, name)
ValueTypes (id, part_type_id, name)
Parts      (id, part_type_id, name)
PartValues (part_id, value_type_id, value)
</code>```

Which one to prefer and why? Or is there a better one?

I am concerned about the DB queries. I don't want the queries become overly slow or complicated.

Update

The number of types in the DB are pretty much given and static since they rest on a international standard and will be enhanced seldomly.


答:
I would tend to not option #3.

Option #3 is name-value pair setup violating normalization.

Ideally, one attempts to have some level of normalization of the database.  Strive for complete normalization and then denormalize as necessary when it is identified for customization or performance issues.

Consider the query "what are the name and part IDs for all wires made of copper"

Structure #1 is

```<code>select
  name, parts.id
from
  wire, parts
where
  wire.material = 'copper'
  and wire.part_id = parts.id
</code>```

Structure #2 is

```<code>select id, name from wire where material = 'copper'
</code>```

Structure #3 is

```<code>select
  parts.name,
  parts.id,
from
  parts, part_types, part_values, value_types
where
  part_types.name = "wire"
  and parts.part_type_id = part_types.id
  and value_types.name = "material"
  and value_types.id = part_values.type_value_id
  and part_values.value = "copper"
</code>```

Consider also the complication of inserts and deletes from the system.

Some further reading on why not #3 -- The curse of the name value pair

Title: Design Parts DB

Body:
I would tend to not option #3.

Option #3 is name-value pair setup violating normalization.

Ideally, one attempts to have some level of normalization of the database.  Strive for complete normalization and then denormalize as necessary when it is identified for customization or performance issues.

Consider the query "what are the name and part IDs for all wires made of copper"

Structure #1 is

select
  name, parts.id
from
  wire, parts
where
  wire.material = 'copper'
  and wire.part_id = parts.id

Structure #2 is

select id, name from wire where material = 'copper'

Structure #3 is

select
  parts.name,
  parts.id,
from
  parts, part_types, part_values, value_types
where
  part_types.name = "wire"
  and parts.part_type_id = part_types.id
  and value_types.name = "material"
  and value_types.id = part_values.type_value_id
  and part_values.value = "copper"

Consider also the complication of inserts and deletes from the system.

Some further reading on why not #3 -- The curse of the name value pair


答: If you have an application with more than one (experience) developer, bad code won't go into the main branch, since you won't get write access if you don't prove you meet their standards. </p>

Body:
How do open source projects maintain quality?
What keeps the projects from people with relatively little programming experience checking in poor quality codes?</p>


问:
Why is naming a table's Primary Key column "Id" considered bad practice?
My t-sql teacher told us that naming our PK column "Id" is considered bad practice without any further explanations.

Why is naming a table PK column "Id" is considered bad practice?

答:
I find people here cover pretty much every aspect but I want to add that "id" is not and should not be read as "identifier" it's more of an "index" and surely it does not state or describe the row's identity. (I may have used wrong wording here, please correct me if I did)

It's more or less how people read the table data and how they write their code. I personally and most likely this is the most popular way I see more frequently is that coders write the full reference as table.id, even if they don't need to do union's or/and joins. For example:

```<code>SELECT cars.color, cars.model FROM cars WHERE cars.id = <some_var>
</code>```

That way you can translate it to English as "Give me color and model of that car that is numbered as ." and not as "Give me color and model of that car that is identified as number ." The ID does not represent the car in any way, it's only car's index, a serial number if you will. Just like when you want to take the third element from an array.

So to sum up what I wanted to add is that it's just a matter of preference and the described way of reading SQL is the most popular.

Though, there are some cases where this is not used, such as (a far more rare example) when the ID is a string that is really describing. For example id = "RedFordMustang1970" or something similar. I really hope I could explain this at least to get the idea.

Body:
I find people here cover pretty much every aspect but I want to add that "id" is not and should not be read as "identifier" it's more of an "index" and surely it does not state or describe the row's identity. (I may have used wrong wording here, please correct me if I did)

It's more or less how people read the table data and how they write their code. I personally and most likely this is the most popular way I see more frequently is that coders write the full reference as table.id, even if they don't need to do union's or/and joins. For example:

SELECT cars.color, cars.model FROM cars WHERE cars.id = <some_var>

That way you can translate it to English as "Give me color and model of that car that is numbered as ." and not as "Give me color and model of that car that is identified as number ." The ID does not represent the car in any way, it's only car's index, a serial number if you will. Just like when you want to take the third element from an array.

So to sum up what I wanted to add is that it's just a matter of preference and the described way of reading SQL is the most popular.

Though, there are some cases where this is not used, such as (a far more rare example) when the ID is a string that is really describing. For example id = "RedFordMustang1970" or something similar. I really hope I could explain this at least to get the idea.


问:
Is there a database programming language with encapsulation to prevent the injections?
One of things that annoys me about SQL is that it can't think in terms of objects and it's lack of encapsulation makes me constantly have to escape commands to prevent injections.

I want a database language that can be polymorphic and secure. I have searched online for non-procedural database programming languages and so far my google search has been unsuccessful.

I know in languages like php there are ways to prevent the injections by making the PHP encapsulated well, but not all database programming situations involve embedding the database language in another language.

In situations where it's database programming only, is there a database programming language that is object oriented in itself? If not, are they working on one?

答:
SQL actually has encapsulation built into the language, specifically in the part you're talking about, for preventing injection.  The basic idea is, if you're escaping your SQL queries as you build them, you're doing it wrong.

Wrong way:

```<code>SQL = 'select * from MY_TABLE where NAME = ' + Escape(nameParam);
RunQuery(SQL);
</code>```

Query encapsulation in SQL is called using parameters.  It looks something like this:

```<code>SQL = 'select * from MY_TABLE where NAME = :name';
Params.Add(nameParam);
RunQuery(SQL, Params);
</code>```

This sends the query parameters to the database as something separate from the query itself, so it doesn't get parsed as part of the string, making injection impossible.  The database engine substitutes the parameter in for the param token (:name).

This also has efficiency benefits.  On the client side, you don't have to concatenate strings, and you can usually declare your SQL strings as constants.  And on the database side, the DB engine can cache a parametrized query and use the same query plan if you reuse it multiple times, making data access faster.

Exactly how parameters work on the client side varies, based on the language database, and DB access library you're using.  Look at your documentation to figure out how it's done.  But AFAIK all SQL databases support it, so you shouldn't have much trouble being able to use them.

Body:
SQL actually has encapsulation built into the language, specifically in the part you're talking about, for preventing injection.  The basic idea is, if you're escaping your SQL queries as you build them, you're doing it wrong.

Wrong way:

SQL = 'select * from MY_TABLE where NAME = ' + Escape(nameParam);
RunQuery(SQL);

Query encapsulation in SQL is called using parameters.  It looks something like this:

SQL = 'select * from MY_TABLE where NAME = :name';
Params.Add(nameParam);
RunQuery(SQL, Params);

This sends the query parameters to the database as something separate from the query itself, so it doesn't get parsed as part of the string, making injection impossible.  The database engine substitutes the parameter in for the param token (:name).

This also has efficiency benefits.  On the client side, you don't have to concatenate strings, and you can usually declare your SQL strings as constants.  And on the database side, the DB engine can cache a parametrized query and use the same query plan if you reuse it multiple times, making data access faster.

Exactly how parameters work on the client side varies, based on the language database, and DB access library you're using.  Look at your documentation to figure out how it's done.  But AFAIK all SQL databases support it, so you shouldn't have much trouble being able to use them.


问:
Is true multithreading really necessary?
So yeah, I'm creating a programming language. And the language allows multiple threads. But, all threads are synchronized with a global interpreter lock, which means only one thread is allowed to execute at a time. The only way to get the threads to switch off is to explicitly tell the current thread to wait, which allows another thread to execute.

Parallel processing is of course possible by spawning multiple processes, but the variables and objects in one process cannot be accessed from another. However the language does have a fairly efficient IPC interface for communicating between processes.

My question is: Would there ever be a reason to have multiple, unsynchronized threads within a single process (thus circumventing the GIL)? Why not just put thread.wait() statements in key positions in the program logic (presuming thread.wait() isn't a CPU hog, of course)?

I understand that certain other languages that use a GIL have processor scheduling issues (cough Python), but they have all been resolved.

答:
If there is no shared mutable state then it makes life a lot simpler because you don't need to synchronise between processes. At that point you have an actor model as in Erlang.

The other problem you have is that if you are counting on the programmer to call thread.wait() or the like then you have the possibility of a misbehaving program bringing down the whole system.

I would suggest you take a good look at Both Erlang and Clojure as they both have some of the aspects of what you are looking for.


答:
Option 3: (sometimes)

Option 3 is the "EAV" design. In theory it is nice because the fields are taken out of the table structure and become data. But it gives terrible performance. It also disallows the use of proper indexing. And it makes queries much more complicated.

I would only use EAV in special circumstances. I have used EAV to calculate auxiliary parts needed for orders and it worked well.  But be very weary of using it as the design for your core tables.

Option 2: (never?)

Option 2 is a no no. What about the shared fields? Are you going to duplicate the table structure for every shared field? It would require you to include unions in reports of the entire system.

Option 1: (winner!)

Option 1 may seem a little too basic but it is probably the best bet for your core tables. All the parts use the same master table for shared fields so it avoids unions in your reports. It has great performance allowing the proper use of indexing. Queries are in the traditional style and are simple.

The downside of option 1 is you can't add fields dynamically. But do you really want to? By dynamically adding fields you are performing database design at run-time.

Title: Design Parts DB


答:
Most projects have version control systems, where the code development goes in branches. New features are accepted to unstable branches, or even in a branch-per-feature or branch-per-fix manner. When a new branch is tested and it's clear that the code is of good quality, it can be merged into the main branch, or into beta-testing branch, from where, after fixes if necessary, it goes into or becomes itself the production branch.

Read about Mercurial http://hginit.com/ and Git http://progit.org/book/ version control systems.

Title: How do open source projects maintain quality?


问:
Labeling algorithm for points
I need an algorithm to place horizontal text labels for multiple series of points on the screen (basically I need to show timestamps and other information for a history of moving objects on a map; in general there are multiple data points per object). The text labels should appear close to their points--above, below, or on the right side--but should not overlap other points or text labels.

Does anyone know an algorithm/heuristic for this?

答: It may come as a surprise to you that (if you want to ensure that none of the labels overlap) the problem you describe is NP-hard. On the other hand, many approximation algorithms have been devised that are perfectly useful in practice. It really depends on how difficult your specific constraints are. (Disclaimer: I wrote my Master's thesis on the subject -- available here -- so I'm probably exactly the wrong person to ask!) As always, Wikipedia and Google are good starting points. And if you're really a glutton, an exhausting (though not exhaustive) list of papers on the subject can be found here.

Title: Labeling algorithm for points


问:
How do I prevent unknowningly duplicating code?
I work on a rather large code base. Hundreds of classes, tons of different files, lots of functionality, takes more than 15 minutes to pull down a fresh copy, etc.

A big problem with such a large code base is that it has quite a few utility methods and such that do the same thing, or has code that doesn't use these utility methods when it could. And also the utility methods aren't just all in one class (because it'd be a huge jumbled mess).

I'm rather new to the code base, but the team lead who's been working on it for years appears to have the same problem. It leads to a lot of code and work duplication, and as such, when something breaks, it's usually broken in 4 copies of basically the same code

How can we curb this pattern? As with most large projects, not all code is documented(though some is) and not all code is... well, clean. But basically, it'd be really nice if we could work on improving the quality in this respect so that in the future we had less code duplication, and things like utility functions were easier to discover.

Also, the utility functions are usually either in some static helper class, in some non-static helper class that works on a single object, or is a static method on the class which it mainly "helps" with.

I had one experiment in adding utility functions as Extension methods(I didn't need any internals of the class, and it definitely was only required in very specific scenarios). This had the effect of preventing cluttering up the primary class and such, but it's not really anymore discoverable unless you already know about it

答:
The simple answer is that you really can't prevent code duplication. You can however "fix it" through a difficult continuous repetitive incremental process that boils down into two steps:

Step 1. Start writing tests on legacy code (preferably using a testing framework)

Step 2. Rewrite/refactor the code that is duplicated using what you've learnt from the tests

You can use static analysis tools to detect duplicated code and for C# there are loads of tools that can do this for you:

StackOverflow - What Tool to Find Code Duplicates in C# Projects

Tools like this will help you find points in code that does similar things. Continue to write tests to determine that they really do; use the same tests to make the duplicate code simpler to use. This "refactoring" can be done in multiple ways and you can use this list to determine the correct one:

Refactor to Patterns Catalogue

Furthermore there is also a whole book about this topic by Michael C. Feathers, Working Effectively with Legacy Code. It goes in depth different strategies you can take to change the code to the better. He has a "legacy code change algorithm" which is not far off from the two step process above:

Identify change points

Find test points

Break dependencies

Write tests

Make changes and refactor

The book is a good read if you're dealing with brown-field development, i.e. legacy code that needs to change.

In this case

In the OP's case I can imagine the untestable code is caused by a honey pot for "utility methods and tricks" that take several forms:

static methods

use of static resources

singleton classes

magic values

Take note that there is nothing wrong with these, but on the other hand they're usually hard to maintain and change. Extensions methods in .NET are static methods, but are also relatively easy to test.

Before you go through with the refactorings though, talk with your team about it. They need to be kept on the same page as you before you proceed with anything. This is because if you're refactoring something then chances are high you'll be causing merge conflicts. So before reworking something, investigate it, tell to your team to work on those code points with caution for a while until you're done.

Since the OP is new to the code there are some other things to do before you should do anything:

Take time to learn from the codebase, i.e. break "everything", test "everything", revert.

Ask someone from the team to review your code before committing. ;-)

Good luck!


答:
There are 2 possible solutions:

Prevention - Try to have as good documentation as possible. Make every function properly documented and easy to search through whole documentation. Also, when writing code, make it obvious where the code should go, so it is obvious where to look. Limiting amount of "utility" code is one of the key points of this. Every time I hear "lets make utility class", my hair goes up and my blood freezes, because it is obviously a problem. Always have quick and easy way to ask people to know the codebase whenever some feature already exists.

Solution - If prevention fails, you should be able to quickly and efficiently solve the problematic piece of code. Your development process should allow to quickly fixing duplicate code. Unit testing is perfect for this, because you can efficiently modify code without fear of breaking it. So if you find 2 similar pieces of code, then abstracting them into a function or class should be easy with little bit of refactoring.

I personally don't think prevention is possible. The more you try, the more it is problematic to find already existing features.

Title: How do I prevent unknowningly duplicating code?

Body:
I work on a rather large code base. Hundreds of classes, tons of different files, lots of functionality, takes more than 15 minutes to pull down a fresh copy, etc.

A big problem with such a large code base is that it has quite a few utility methods and such that do the same thing, or has code that doesn't use these utility methods when it could. And also the utility methods aren't just all in one class (because it'd be a huge jumbled mess).

I'm rather new to the code base, but the team lead who's been working on it for years appears to have the same problem. It leads to a lot of code and work duplication, and as such, when something breaks, it's usually broken in 4 copies of basically the same code

How can we curb this pattern? As with most large projects, not all code is documented(though some is) and not all code is... well, clean. But basically, it'd be really nice if we could work on improving the quality in this respect so that in the future we had less code duplication, and things like utility functions were easier to discover.

Also, the utility functions are usually either in some static helper class, in some non-static helper class that works on a single object, or is a static method on the class which it mainly "helps" with.

I had one experiment in adding utility functions as Extension methods(I didn't need any internals of the class, and it definitely was only required in very specific scenarios). This had the effect of preventing cluttering up the primary class and such, but it's not really anymore discoverable unless you already know about it


问:
is it okay to remove copyright info from a free, open source API even if you are explicitly told not to do so?
Just wondering if text such as the following, which appears inside the source files of a free, open source API, means anything in a court of law</p>

```<code>    // Permission is hereby granted, free of charge, to any person obtaining a copy
    // of this software and associated documentation files (the "Software"), to deal
    // in the Software without restriction, including without limitation the rights
    // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    // copies of the Software, and to permit persons to whom the Software is
    // furnished to do so, subject to the following conditions:
    //
    // The above copyright notice and this permission notice shall be included in
    // all copies or substantial portions of the Software.
    //
    // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    // THE SOFTWARE.
</code>```

答:
No, it's not OK to remove it.

Even if you could get away with it from a legal perspective, it would be ethically wrong to do so.

As to whether it will stand in a court: I'm no lawyer, but it looks to me like it's a pretty simple license, which takes it's power from the original author's copyright interest in the work. In that way, it's similar to other licenses like the GPL, which have been found valid in courts in several countries. It's also MUCH simpler in concept and execution than (for instance), the GPL, which I suspect would make it easier to enforce. The only thing that seems at all fuzzy to this layman is the definition of 'substantial portions'.

I suppose the remaining question is whether anyone would sue you over it. That would depend almost completely on what you did with the stripped version, and whether anyone could possibly know what you'd done.

For instance, if you stripped the notices and put it into an internal company product, then only the other devs would have any chance of knowing, and they might be unlikely to recognize it, and even if they did, they might well not be inclined to alert the author.

On the other hand, if you stripped the notices and distributed the source under your own name, then you'd be more likely to get someone noticing and doing something about it.


答:
Open source or not, the file is copyrighted unless it specifically states that it is not (creations of the government, things on which the copyright has expired and things explicitly placed in the public domain).  Copyrights are enforceable in court.

Open source actually depends on copyright for its enforcement (the ability to restrict who makes derivative works is at the heart of the GPL).

To that extent, removing a copyright notice is mentioned copyright law as a criminal offense.  The copyright notice is independent of the enforceability of a license.

Title: is it okay to remove copyright info from a free, open source API even if you are explicitly told not to do so?

Body:
Just wondering if text such as the following, which appears inside the source files of a free, open source API, means anything in a court of law</p>

```<code>    // Permission is hereby granted, free of charge, to any person obtaining a copy
    // of this software and associated documentation files (the "Software"), to deal
    // in the Software without restriction, including without limitation the rights
    // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    // copies of the Software, and to permit persons to whom the Software is
    // furnished to do so, subject to the following conditions:
    //
    // The above copyright notice and this permission notice shall be included in
    // all copies or substantial portions of the Software.
    //
    // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    // THE SOFTWARE.
</code>```


答:
No, It is not.

At least GPL, MS-PL, CC and text in your example does not permit as per license terms.

If there is a license that explicitly states that attribution to author is not required(Optional) and license copy is also not required (Optional), then you could remove the copyright.


答:
I've designed a number of languages and come to realize there are different needs for threads or parallelism.

One is raw performance. If a program is CPU-bound and there is a way to parallelize it across multiple cores then clearly one would want that.

The other, and far more common need, in my experience, is to simplify the representation of sequences of activities where those sequences are, in some sense, independent of each other.

The obvious case is listening on multiple input streams and responding to requests on those streams.

A case I work with a lot has to do with pharmacologic modeling, where a subject may get one medication on one schedule, another on another, and have observations on yet another schedule, while simultaneously dealing with adverse events and alarms. Treating this as a purely event-driven process is possible, but the coding is very clumsy.

In these cases, what is needed is a way to clearly express what one is trying to say, and it has little to do with being CPU-bound and needing performance. For these needs, non-preemptive parallelism works better, and is much less prone to race conditions.

Title: Is true multithreading really necessary?

Body:
So yeah, I'm creating a programming language. And the language allows multiple threads. But, all threads are synchronized with a global interpreter lock, which means only one thread is allowed to execute at a time. The only way to get the threads to switch off is to explicitly tell the current thread to wait, which allows another thread to execute.

Parallel processing is of course possible by spawning multiple processes, but the variables and objects in one process cannot be accessed from another. However the language does have a fairly efficient IPC interface for communicating between processes.

My question is: Would there ever be a reason to have multiple, unsynchronized threads within a single process (thus circumventing the GIL)? Why not just put thread.wait() statements in key positions in the program logic (presuming thread.wait() isn't a CPU hog, of course)?

I understand that certain other languages that use a GIL have processor scheduling issues (cough Python), but they have all been resolved.


问:
Where do the parser and service objects fit in MVC?
Do NSURLConnection service objects and XML/JSON parser objects fall within the controller layer or the model layer? Why?

Is it OK to have business logic in the controller? Or should it be in the model layer only?

Can the model layer be represented by NSArray/NSDictionary objects or should it be strictly structured with custom objects to comply with the MVC pattern, given that my app doesn't require persistent storage.

答:
I don't think you should apply a hard rule as where service modules should be applied. Most of the time services are used by the model, but there is quite a bit of variability.

For example, a view that loads a resource from a URL will interact with a network service, or a controller may use a parser service after pulling data from a model and adapting that data to a view.


答:
How do closed source projects maintain quality? What keeps the projects from people with relatively little programming experience checking in poor quality codes?

The same way:

code review

testing

static typing

static analysis

metrics

consistent coding styles

consistent guidelines

shame (because everybody in the world can see who wrote that crappy code)

But really the answer is: most don't. In both cases, open and closed source. After all, programming is subject to the Pareto Principle and Sturgeon's Revelation (“Ninety percent of everything is crud”) just like everything else.

In Linux, for example, in almost 100% of all cases where a company releases a previously closed source driver as open source, that driver needs a considerable amount of work before it can be merged into the kernel tree, simply because its quality is so bad. In some cases, it is so bad that the code is basically unsalvageable and has to be rewritten from scratch.

So, in Linux, the way that quality gets maintained is that low quality contributions get rejected, but there is a mentoring process helping people to write better quality code.


问:
Starting off with web dev with php
I'm currently working with Java / C++. I'm interested in web development and am planning to shift my stream. I heard that PHP is a good platform to start off and also it does not require that much of knowledge in technologies like JSP / Servlets or frameworks like springs / struts / hibernate.

I have basic ideas about HTML and Javascript as well. I have gone through previous posts in SO and found out the relevant resources as well:

http://net.tutsplus.com/tutorials/php/the-best-way-to-learn-php/

http://www.webhostingtalk.com/archive/index.php/t-1028265.html

http://www.killerphp.com/

http://phpforms.net/tutorial/tutorial.html

http://www.php5-tutorial.com/ etc.

Now, my question is: I heard of PHP frameworks like CodeIgniter, Zend Frameworkd and Yii.

Doesn't learning PHP & MySql implicitly makes us aware of these frameworks?

Am I making a good choice in stating with PHP?

Is it a good idea to shift streams?

答:
Two words: Avoid PHP. It was great in 2002 (as was ASP) but in 2013, it's a horrible platform. For 2013 I would suggest C# ASP.NET (BTW, very different from horrible ASP from 2002) or Python. I'd recommend the following in the decreasing order of preference:

C# language (ASP.NET or Mono as the platform. Though Microsoft's support and continuous refinement of the .NET platform deserves respect. C# v5 in .NET 4.5 is ridiculously elegant (lambdas, async methods, dynamic AND static typing etc). This from a former Linux kernel hacker :) ). This is especially true since you have a C++/Java background; you'll be productive really quick.

Python (very close to #1 above, though MS is pouring a LOT of money and talent into .NET to pull away)

Ruby (I personally prefer Python over Ruby)

C++/Java (even if it's outdated, since you have a background in it)

(other languages)

x86 assembly

smoke signals

original ASP

PHP (ok, so the above 3 were a joke to get to this)

Title: Starting off with web dev with php