问:
Should a surrogate key ever be exposed to a user?
Often in a table that has no natural key, it is still useful for users to be able to have a uniquely generated identifier.  If the table has a surrogate primary key (and in such a case you would certainly expect it to) should that key be exposed to the user or should another field be used for that purpose?

One reason not to expose the surrogate key is that now you can't do operations that preserve the relationship between records, but change the key values, such as certain kinds of deletion/re-insertion, many methods of copying data from one database to another, etc.

The main advantage of exposing the surrogate key is the simplicity of using a field you have anyway.

Under what circumstances is it better to directly expose the surrogate key to users?

答:
If a table has no natural key, surrogate keys allow rows like this.

```<code>surrogate_key  some_name
--
1              Wibble
2              Wibble
...
17             Wibble
...
235            Wibble
</code>```

I'd call these artificial keys instead of surrogate keys, but that distinction isn't important for this question.

Now, assuming that there's important data referencing these surrogate keys through foreign keys, how would the end users know which row to update if they don't know the surrogate key values?

Body:
If a table has no natural key, surrogate keys allow rows like this.

surrogate_key  some_name
--
1              Wibble
2              Wibble
...
17             Wibble
...
235            Wibble

I'd call these artificial keys instead of surrogate keys, but that distinction isn't important for this question.

Now, assuming that there's important data referencing these surrogate keys through foreign keys, how would the end users know which row to update if they don't know the surrogate key values?


问:
Java continuous integration with extras
I am very new to continuous integration, but I decided to give it a shot. Unfortunately I found there to be huge quantities of different tools, and each one is sizable and seems to be difficult (I am new so of course it intimidates me).

What I am looking for however is a tool that can

run my junit tests

execute my builds

create the jars

deploy specific jars to specific remote servers

What are the key steps and approaches to filling these requirements?

答:
A Continuous Integration server essentially just does a build as you would on the command line on a regular basis.  Thats the core of it.  The key is to have a build that will automatically run the junit tests, run the static analysis, and assemble the jar.

For this, there are three tools to look at.  From oldest to newest they are ant, maven, and gradle.  Any of these tools will work, the newer ones are more automated.  It is a matter of setting up the tool to do what you want it.

Once you have the build so you can type one command and build (maven package or the like) that does all the parts, it should be a "simple matter" of moving that onto the CI server.

The deployment tool would use another plugin such as the deploy plugin which could do it, or you could write your own script (that is a "build") that invokes as part of a build pipeline.

The key to all of this, however, is first setting up the build so that it can be built with one command.

ContentLicense: CC BY-SA 3.0

Title: Java continuous integration with extras


问:
How to properly take over a complex PHP project
I've been tasked to correct some issues on the backend of a large website project that has been outsourced for some time. The original developers and us are not on good terms so it's not feasible to get them involved.

The technology stack is as follows:

MySQL 5.x

PHP 5.3 (and a variety of supporting libraries)

Apache with mod_rewrite

The problems I am facing are:

No documentation, not even comments

4 index files in root, plus 2 main files in a combo of php and html and 1 default.php, the referenced index file in .htaccess references their local test server.

Duplicate file names / files

Atrocious file system layout ( ultiple js folders, multiple script folders etc )

Reliance on original mysql functions ( not mysqli or PDO )

multiple frameworks, JQuery, various marketplace API's etc.

It has been a highly frustrating several hours trying to sort out where to begin with this mess, let alone how to fix the items I need.

So my question is: What would be the best place to start or If this was dropped on your lap, how would you approach it?

I know this is subjective, and opinions are what I am looking for, so any advice is appreciated.

答:
I think that I would approach it one of these ways:

Talk to the previous developers even if you are on nasty terms

Talk to somebody that was around when the website was first developed/in development

Do a complete redesign

Read through all of the code and make any changes to each line that needs to be changed

(this will take a long long time though)

Tell your boss that you are not in a position to do this

Ask your boss to hire more people to get the job done with you

Try to find out exactly what each page does before doing anything

That is all that I can think of at the moment, but if I have any other ideas I will edit my answer.

OwnerDisplayName: Robert H

OwnerDisplayName: pattyd


答:
I had a similar issue a couple of years ago.

After a lot of research, I found out it would take much less time to build a whole new system than to try to fix the one that was ready. Most important: try to fix that messy code would certainly leave lots of security holes.

As the only think that was truly relevant was the db (which was also a mess), I first planned a db scheme and built a script to migrate the db to fit my scheme and built a new application the right way.

I don't know if you may do something like this but maybe this line of thought may help.

Title: How to properly take over a complex PHP project

Body:
I've been tasked to correct some issues on the backend of a large website project that has been outsourced for some time. The original developers and us are not on good terms so it's not feasible to get them involved.

The technology stack is as follows:

MySQL 5.x

PHP 5.3 (and a variety of supporting libraries)

Apache with mod_rewrite

The problems I am facing are:

No documentation, not even comments

4 index files in root, plus 2 main files in a combo of php and html and 1 default.php, the referenced index file in .htaccess references their local test server.

Duplicate file names / files

Atrocious file system layout ( ultiple js folders, multiple script folders etc )

Reliance on original mysql functions ( not mysqli or PDO )

multiple frameworks, JQuery, various marketplace API's etc.

It has been a highly frustrating several hours trying to sort out where to begin with this mess, let alone how to fix the items I need.

So my question is: What would be the best place to start or If this was dropped on your lap, how would you approach it?

I know this is subjective, and opinions are what I am looking for, so any advice is appreciated.

OwnerDisplayName: Robyflc


答:
I'm going to ignore the possibility of a rewrite, and only address how to attack this particular problem, assuming a rewrite is not in the cards.

First thing to do: spend the time to figure out what it's doing and how, and document it as you go.  Then, break it down in to smaller pieces.  Instead of being overwhelmed by the massive size of the project, figure out what things you can work on atomically.  Some suggestions:

Abstract out the database calls in to a class (either your own, or PDO, or another library)

Restructure the assets so they're more logical

Consolidate the front-end libraries so it's only using one

I'm sure there's a dozen (or a hundred) different areas that need work.  Don't think about that; think about the first one to attack.


答:
My preferred approach is:

Set up some basic documentation yourself

class diagram

ERD of data

Next debug through some parts of the application to get an overview of the architecture. From that you can construct an abstract view. Again, document it.

By the time you are at this point, you should be more familiar with the project.


答:
If it ain't broke, don't fix it. I'm assuming the code has been running functionally for some time, and your business process has assured the previous developers have met the SLA you are now shooting for.  Which means, in lack of bugs or new feature requests, you don't have to touch anything ever again.  Of course you do but it's important to understand this point first. Your goal is not to rewrite or even to understand a complex project. It's to be able to ascertain enough information on requests you do have to make to fix relevant pieces and touch relevant code only.

Strategies for making isolated changes are very different than strategies for understanding or re-architecting whole code bases. If you are asked to make a small change, often the best thing to do is enter your application, probably via an HTTP request in your case, while having your server running under a debugger. Now you can simply watch the logic the code is following and have an idea of the relevant architecture. The debugger is your tour guide through the fog of war.

Consider making a small change with some code rot. Often you will be able to say, "I know this code change will work, even though it's probably bad design." This can be a reasonable choice. But of course you do need to establish that you do in fact know the code change will work, so you will have to study relevant pieces some amount. Keep security risk in mind - if you slap something together and it works well on a few test cases, do you understand the system well enough to be wary of disastrous corner cases?

Your early steps should include getting your code under source control and learning the moving parts in production.  Source control is a big one, obviously, and you want to keep track of changes that you make very well. If you have not been in the habit of making cohesive git commits, this would be a good time to start, because you're likely going to want to be doing things like cherry-pick and subtle rollbacks more than when working on code you know well. Branch intelligently: now in production, changes I've made that I think are safe, changes I've made that are just poking around to see what stuff does but I might want to refer to later anyway.

But beyond that, think of questions like: do you know your environments? If you run the source from your laptop will it break things in production? Or is there a safe development environment? Also, think of components outside the software and account for them - build system, unit tests, logging, monitoring and error notification, etc. It hurts to make a broken change then discover you also broke the monitoring on it.

Be prepared to make the case for an expensive redesign or rearchitecture. As maintenance tasks you have to do on this project get larger in scope or more frequent, and if you really are convinced the code you are working on is poor quality, you will simply have to make the case that replacing it is cheaper in the long run than maintaining it.  Find pieces that can be affordably rewritten rather than rewriting the whole thing. This may mean isolating a data layer or logging system, all one component at a time.

The extreme case is of course to throw out the entire project and rewrite in, say, Ruby from scratch, but if it comes to this, it's probably more because you were not savvy enough than because the code was that awful. You should be able to identify pieces that you understand why are awful and how to turn them into maintainable components and affordably rewrite those with a general sense of the scope of what you are getting into. The worse the code or the less savvy you are, the bigger the piece, but throwing out everything will be a last resort.


问:
Generic params table design
We have a generic parameter table whose important attributes are :

```<code>id number auto increment not null
domain varchar (200) not null
classification varchar (200) not null
param_name varchar (200) not null
value CLOB/text
created_by, created_date, updated etc
</code>```

Here the id is unique for the table plus at the functional level there is a unique index on domain, classification, param_name

The value is text of any length in UTF-8. We want to add BLOB, binary data support. Choices are :

add a new column :
blob_value BLOB
OR

add a field 'type' of varchar2 in this table that can be null or 'B', default null. Null or blank means is not - text If B means its a blob. In that case the value will hold an id of a blob table row. The blob table will look like :

id number auto increment
data BLOB

Leave existing table alone and in a new table that references this one:
 parameter_id number primary key,
 data blob, with constraint FOREIGN KEY (parameter_id) REFERENCES Parameter(id)
(suggestion FrankieTheKneeMan thank you)

Advantage of first is that a param can have both a text and a blob or either.

Advantage of second - not sure -> do not need to keep null columns? Current table has 30,000 rows and we expect it to grow to 70,000 out of which 10% will need blob data.

Question: which of these would you choose and why or do you have an alternate ?

答:
It's a one to one relationship of Parameters to blobs - every blob must have a parameter, but not every parameter needs a blob, right?  70000 Rows doesn't seem like that much, so I'd probably just add another column to save you the join when you need blob data (joins can be deceptively expensive).  Additionally, overloading the value of one column based on the value of another is a recipe for trouble.  It's fine if you're the only person who's ever going to touch these tables, and you never forget anything ever.  Since those are rarely the case, I'd advise against it.  There's a false economy of bringing encoding into your tables.

If you're worried about storage space, try something like this on for size - add nothing to the parameter table, and instead make your primary key on your blob table also a foreign key to the param table.  SOmething like:

```<code>parameter_id number primary key //ensures uniqueness
data blob
FOREIGN KEY (parameter_id) REFERENCES Parameter(id) //Ensures that it matches a parameter,
    //As well as adding a bit of speed to your select (and the cost of your inserts).
</code>```

Title: Generic params table design

Body:
It's a one to one relationship of Parameters to blobs - every blob must have a parameter, but not every parameter needs a blob, right?  70000 Rows doesn't seem like that much, so I'd probably just add another column to save you the join when you need blob data (joins can be deceptively expensive).  Additionally, overloading the value of one column based on the value of another is a recipe for trouble.  It's fine if you're the only person who's ever going to touch these tables, and you never forget anything ever.  Since those are rarely the case, I'd advise against it.  There's a false economy of bringing encoding into your tables.

If you're worried about storage space, try something like this on for size - add nothing to the parameter table, and instead make your primary key on your blob table also a foreign key to the param table.  SOmething like:

parameter_id number primary key //ensures uniqueness
data blob
FOREIGN KEY (parameter_id) REFERENCES Parameter(id) //Ensures that it matches a parameter,
    //As well as adding a bit of speed to your select (and the cost of your inserts).


答:
I would start by hunting down and fixing the bugs I was tasked to fix.  Use bug hunting to get familiar with how the code works.  Along the way make mental notes about any glaring problems I might see.  Since you're using mysql_ functions, I'd pay special attention to fixing any possible injection problems.

Resist the urge to launch immediately into re-write mode.  For starters, you may not have the specific domain knowlege necessary for such a step at this point.  Better to at least have a few months with the existing code base before you start evaluating the possibility of a rewrite.  It may be, for example, that some of the 'problems' you see in the code end up making more sense to you as you get familiar with it.


问:
Will object reuse optimize this often-called function?
Suppose I have a function that I need to call a lot, maybe a few thousand times on every mouse down or mouse move. It uses an instance of a function (class), called Transform:

```<code>function func1(a, b, c) {
  var t = new Transform();
  t.rotate(a);
  t.scale(b, c);
  return t.m[0];
}
</code>```

So I'm creating thousands of new transforms as I call this func1 lots.

What if, instead of creating new Transform()s every time, I created a small system to allocate extra transforms only as they are needed, and re-use them:

```<code>window.Util = {
  _CachedTransforms: [],
  tempTransform: function() {
    var arr = Util._CachedTransforms;
    var temp = arr.pop();
    if (temp === undefined) return new Transform();
    return temp;
  },
  freeTransform: function(temp) {
    Util._CachedTransforms.push(temp);
  }
}
</code>```

Then instead I could call func2:

```<code>function func2(a, b, c) {
  var t = Util.tempTransform();
  t.reset();
  t.rotate(a);
  t.scale(b, c);
  var result = t.m[0];
  Util.freeTransform(t);
  return result;
}
</code>```

Using func2 several thousand times, new Transform is only ever called once. This might suggest a benefit, but the numbers from jsperf don't seem to suggest any.

If you want to see these two functions in action as well as the Transform class, take a look at jsperf: http://jsperf.com/transforms

And especially: http://jsperf.com/transforms/2

To simulate it occuring lots during an event, my jsperf test does:

```<code>var a;
for (var i = 0; i < 4000; i++) {
  a += func1(1, i, 3); // vs func2
}
</code>```

There may be better ways to test if this is advantageous or not. Am I missing something?

More broadly, is object reuse like this still a good idea in this scenario, or ever?

答: Is there a reason you even need multiple Transform objects? Wouldn't it be simpler to have Transform be stateless, and have the rotate and scale methods simply return a transformed object? That way you don't have to worry about the state of the Transform, and can safely spawn each function on a different thread, which could lead to significant improvements.

OwnerDisplayName: Simon Sarris


答:
Reducing the time spent allocating objects is a good idea. Its so good in fact that most javascript implementations are already doing it behind the scene. So when you try to implement your own version you just implement a less efficient version of it than the runtime is already giving you.

You can improve performance by not allocating objects. However, your method is essentially still allocating objects, you've just implemented a custom allocator. You probably can't beat the allocator already available in a good javascript implementation.

Title: Will object reuse optimize this often-called function?

Body:
Suppose I have a function that I need to call a lot, maybe a few thousand times on every mouse down or mouse move. It uses an instance of a function (class), called Transform:

```<code>function func1(a, b, c) {
  var t = new Transform();
  t.rotate(a);
  t.scale(b, c);
  return t.m[0];
}
</code>```

So I'm creating thousands of new transforms as I call this func1 lots.

What if, instead of creating new Transform()s every time, I created a small system to allocate extra transforms only as they are needed, and re-use them:

```<code>window.Util = {
  _CachedTransforms: [],
  tempTransform: function() {
    var arr = Util._CachedTransforms;
    var temp = arr.pop();
    if (temp === undefined) return new Transform();
    return temp;
  },
  freeTransform: function(temp) {
    Util._CachedTransforms.push(temp);
  }
}
</code>```

Then instead I could call func2:

```<code>function func2(a, b, c) {
  var t = Util.tempTransform();
  t.reset();
  t.rotate(a);
  t.scale(b, c);
  var result = t.m[0];
  Util.freeTransform(t);
  return result;
}
</code>```

Using func2 several thousand times, new Transform is only ever called once. This might suggest a benefit, but the numbers from jsperf don't seem to suggest any.

If you want to see these two functions in action as well as the Transform class, take a look at jsperf: http://jsperf.com/transforms

And especially: http://jsperf.com/transforms/2

To simulate it occuring lots during an event, my jsperf test does:

```<code>var a;
for (var i = 0; i < 4000; i++) {
  a += func1(1, i, 3); // vs func2
}
</code>```

There may be better ways to test if this is advantageous or not. Am I missing something?

More broadly, is object reuse like this still a good idea in this scenario, or ever?


问:
How do I implement classes in my scripting language?
Let's suppose I have a code file that reads (I'll use Java-ish syntax) and it is being interpreted. Kind of like a ruby script.

```<code>class A{
    int fieldName = 4;
    A(){...}

    void doSomething(){...}

}

A instanceOfA = new A();
A.fieldName = 7;
</code>```

This is what I understand to happen when this file is interpreted.

File is lexed and parsed

AST or Parse tree is generated

Parse tree is walked to generate code in the runtime to represent the class.

Then what happens? How is the definition turned into an instance? And what kind of internal representation is require to represent the class? Does the interpreter keep the AST for the class around for re-processing each time an instance is created or is some other form created?

I've been following the patterns in Terrence Parr's Language Implementations Patterns book. I think understand how to build the symbol table and scope objects. I'm just a little fuzzy on how take a structure like a class and create an instance of it.

答:
Step 3 needs to be expanded a little:  The parse tree is walked to generate code and metadata.  One of the things it generates is information about class A.  This generally isn't done by keeping the original code or parse tree, but by storing the data in some sort of struct or object that holds the relevant information.

At the very least, it needs to keep around all of the information that is needed to instantiate a class, such as how large an instance is, (or what a default/new instance will contain, if it's a dynamic language where class instances aren't fixed-size), which it needs to know in order to allocate memory and set up the object.  If the language supports some form of reflection, it will keep more than that so that metadata about the class can be accessed at runtime.

In this specific case, you'd need a metadata structure that says that this class has a single int field, and that it's initialized to 4 as a default value.  There are several ways you could implement creating an instance.  Here's one:

Each class type has a metadata table that provides certain information, including the instance size and (optionally) a compiler-generated "secret routine" that initializes the object.

The new operator takes the class type and finds its instance size, and allocates memory for it.

It then checks to see if the class has an initialization routine, and if so, calls it.  (This one does: it sets the value of fieldname to 4.)

It then goes through and checks the class's parent class to see if it has an initialization routine, and so on until it's gone all the way up the chain to the base class.

Then it calls the constructor with the params you supplied, and returns the result.


问:
Primer on moving around in MVC
It was suggested on my Stack Overflow question that this might be better suited to this site, so I'm cross-posting it.

I'm working on my first ground-up build of an MVC site. I have a collection of views, a collection of models, and I've tested most of my views and fixed the obvious bugs.

The last step I need to do is tie the views together - to enable the user to click links/buttons and move between them.

Most of my Google searches for Actions and ActionLinks in MVC/Razor lead me back to StackOverflow, to very specific questions which don't really help me out - the questions assume what I'm trying to learn.

I'm trying to learn at a high level the way to pass various things to controller methods (i.e. override the controller method for a view to accept 2 parameters versus 3, or to accept POST data, understand what will be passed along from one view to another action from an Html.Action call, etc).

答:
I don't know if you have had the chance to read ASP.NET's Intro to MVC or not, but that is what I used to get started on linking one view to another and back. If your controllers use parameters, but you want some (or all) of them to be optional and you send data back and forth, you can use optional parameters.

As far as posting data, that really depends on how you roll it up and send it off. My personal opinion is to roll it into JSON and play with it from there. MVC's JsonAction works beautifully for that. An alternative that I may be beaten for even suggesting, would be to use the ViewBag to pass minor amounts data around. It works in a pinch, but there are safer and more robust ways to move data around for manipulation.

Title: Primer on moving around in MVC


问:
PHP Simplest XML tokenizer for string processing?
I need to do some text processing tasks with short XML fragments.
The section "details" shows an example... My solution is to use a tokenizer based on regular expresions, but it is not elegant and not uses any build-in function. The candidate build-in functions (that others indicates to me) are strtok and  SimpleXML.

So, my question have two parts:

My assumptions are correct? There are no other "candidates", only strtok and SimpleXML? Is correct to think DomDocument as an "elephant" (with big CPU overhead) for a simple text processing task?

How to use SimpleXML to do the same (illustred)  task? PS: I not need all algorithm or implementation, only some clues.

Details

PHP offers a tokenizer, strtok, very simple, and I not see how to use it with XML string.
The option, SimpleXML, is perhaps heavy for tasks like ''text processing'' (see this example and the below), and is more than a tokenizer.

What exactly I whant to say with "tokenizer" and "text processing"? See example below. I used a "regex parser", but I would like an algorithm based on some built-in function like SimpleXML, if it is simpler and faster.

```<code> $xmlFrag = '
   <p align="center">  Hello world!</p>
   <p class="test"><i>  Beautiful</i> day today.</p>';

 // TOKENIZING TAGS AND ENTITIES:
 $reg=array();
 $xmlFrag = preg_replace_callback(
    '/<!\-\-.+?\-\->|<.+?>|&[a-z0-9]+;/is',
    function ($m) {
        global $reg; $reg[]=$m[0]; $n=count($reg)-1;
        return "##$n#";
    },
    $xmlFrag
 );
 echo $xmlFrag;     // results:
 //  ##0###1# Hello world!##2#  ##3###4###5# Beautiful##6# day today.##7#

 // PROCESS THE TEXT: any, in one step. Example: lower, upper, change orthography, etc.
 $xmlFrag = strtoupper($xmlFrag);
 echo $xmlFrag;
 //  ##0###1# HELLO WORLD!##2#  ##3###4###5# BEAUTIFUL##6# DAY TODAY.##7#

 // EXPAND TOKENS:
 $xmlFrag = preg_replace_callback(
    '/##([0-9]+)#/is',
    function ($m) { global $reg; return $reg[$m[1]]; },
    $xmlFrag
 );
 echo $xmlFrag;
 //  <p align="center">  HELLO WORLD!</p>
 //  <p class="test"><i>  BEAUTIFUL</i> DAY TODAY.</p>
</code>```

Using SimpleXML

How to implement a SimpleXML algorithm to resolve the illustrated problem (code above)? PROBLEMS:

Load a XML with named entities (as   in the example).

Traverse XML to get only text nodes. With $sx->xpath('//text()'); I can not edit the nodes.

Using DomDocument

It is out of context, because my XML fragments are short and DomDocument imposes a big CPU overhead (? is this a preconception?) for the simple text processing.

答:
Sorry, I find (!), and have a misconception about DomDocument (it is not an "elephant"):

DomDocument have comparable performance (times) with SimpleXML.

There are a simple algorithm to solve my problem!

```<code> $dom = new DOMDocument;
 $dom->loadXML($xmlFrag);
 $xpath = new DOMXpath($dom);
 $elements = $xpath->query("//text()");
 foreach ($elements as $element) // loop for text processing:
     $element->nodeValue = strtoupper($element->nodeValue);
 print $dom->saveXML();
</code>```

Performance (execution times for a 10000 loop):

DOMDocument (implementation above): 0.481 seconds;

regex tokenizer (implemention of the question): 0.571 seconds;

SimpleXML (no implementation, only simulating iniciatizations and process): 0.481 seconds.
@IMSoP shows that "traverse and edit" is more complex with SimpleXML than DOM.

Body:
Sorry, I find (!), and have a misconception about DomDocument (it is not an "elephant"):

DomDocument have comparable performance (times) with SimpleXML.

There are a simple algorithm to solve my problem!

 $dom = new DOMDocument;
 $dom->loadXML($xmlFrag);
 $xpath = new DOMXpath($dom);
 $elements = $xpath->query("//text()");
 foreach ($elements as $element) // loop for text processing:
     $element->nodeValue = strtoupper($element->nodeValue);
 print $dom->saveXML();

Performance (execution times for a 10000 loop):

DOMDocument (implementation above): 0.481 seconds;

regex tokenizer (implemention of the question): 0.571 seconds;

SimpleXML (no implementation, only simulating iniciatizations and process): 0.481 seconds.
@IMSoP shows that "traverse and edit" is more complex with SimpleXML than DOM.


答:
It shouldn't matter whether you expose the keys or not to the end user.  Your application should perform the necessary authorization such that simply knowing an order id, for example, can't allow them access to something they normally wouldn't have access to.

caveat: this assumes a web based or n-tier application where server side authorization is possible/feasable.  If you have a VB app thats directly executing sql, thats a whole 'nother issue.

Title: Should a surrogate key ever be exposed to a user?

Body:
Often in a table that has no natural key, it is still useful for users to be able to have a uniquely generated identifier.  If the table has a surrogate primary key (and in such a case you would certainly expect it to) should that key be exposed to the user or should another field be used for that purpose?

One reason not to expose the surrogate key is that now you can't do operations that preserve the relationship between records, but change the key values, such as certain kinds of deletion/re-insertion, many methods of copying data from one database to another, etc.

The main advantage of exposing the surrogate key is the simplicity of using a field you have anyway.

Under what circumstances is it better to directly expose the surrogate key to users?


问:
CQRS and validations
I'm starting to introduce myself in CQRS concepts, but I get stucked with the following situation:
Supouse you have an entity that must have an unique name.  In order to verify that, prior to create the entity you must make a query, thus you are verifing against the query subsystem.
But what happens if the syncronization has not been happened between the command system and the query system yet?  Other client just had sent the same name before you.
What happens in that case?</p>

答:
Well, you should not use the query subsystem for validations - use the command subsystem for that. Look into the picture in Fowler's article here - validations are typically placed at the command model side. If, for example, you try to give an entity a unique name, your command subsystem should throw an exception if that name was already used before. The initiator of that command should expect that this may happen, even when he has used the query subsystem before to find a "free" name.

That is, of course, for the case of "eventual consistency" between those different models, where there is a delay between the synchronisation. If you have a system where both models are strictly kept consistent, rules can be obviously different.

Title: CQRS and validations


问:
What is the reason for using lowercase for the first word in a local variable (eg, employeeCount, firstName)
I take a good deal of criticism from other programmers due to my use of full proper casing for all my variables.  For example, your typical programmer will use employeeCount for a variable name, but I use EmployeeCount.  I use full proper casing for everything, be it a void method, return method, variable, property, or constant.  I even follow this convention in Javascript.  That last one really rustles people's jimmies.

The typical reason given as to why I shouldn't follow this "non-standard" casing convention is because full proper case should be reserved for properties and void methods.  Local variable and methods that return a value should have the first word in lowercase like int employeeCount = getEmployeeCount().

However, I don't understand why.

When I question this, it seems that I just get an arbitrary answer of that's the standard.  Whatever the answer is, it usually always boils down to That's just the way it is and I don't question it.  I just follow it..  Arbitrary answers are never good enough for me.

Ever since my early days of programming Excel 97 macros with the Office IDE, I've never needed a casing convention to tell me whether or not something is a local variable or property.  This is because I've always used a very intuitive naming convention.  For example, GetNuggetCount() clearly suggests a method that goes somewhere an gets a count of all the nuggets.  SetNuggetCount(x) suggests that you are assigning a new value to the count of nuggets.  NuggetCount all by itself suggests a property or local variable that is simply holding a value.  To that last one, one may be tempted to say, "Ah ha!  That is the question.  Property or variable?  WHICH IS IT?"  To that, I'd reply with, "Does it really matter?"

So here's the tl;dr;:  What are the objective, logical, non-arbitrary reasons to use lowercase for the first word in your variable or return method?

Edit:  For MainMa

Replace this code with the first code sample in your answer and see how well your argument holds up:

```<code>public void ComputeMetrics()
{
    const int MaxSnapshots = 20;

    var Snapshots = this.LiveMeasurements.IsEnabled ?
        this.GrabSnapshots(MaxSnapshots, this.cache) :
        this.LoadFromMemoryStorage();

    if (!Snapshots.Any())
    {
        this.Report(LogMessage.SnapshotsAreEmpty);
        return;
    }

    var MeasurementCount = Measurements.Count();
    this.Chart.Initialize((count + 1) * 2);

    foreach (var s in Snapshots)
    {
        this.Chart.AppendSnapshot(s);
    }
}
</code>```

答:
For me it comes down to expectation.

When I read most code, I expect anything that starts with a lowerCase to be a local variable or a function (in C# that would be just a variable).  If I see a local variable in ProperCase, I would likely stumble and get confused for a while, thinking that it's either a class name or a property or something else.  That would cause me to re-read the code, and would annoy me.

That is likely what's happening in your case.

Plus, it's convenient to be able to tell what role a variable plays just by looking at the first letter, and it avoids clashes between an instance name and a class name.


问:
GIT Permissions
There is something not clear for me and this is how to prevent other people read my code. The thing is that I want people create their own branches but not to view the other's branches. If someone is responsible for networking, I don't want this guy to view graphics codes. S/He must be forced to work on his branch only.</p>

答:
You could let each individual create their section of the code in a submodule and then include all of the submodules into the main project. This would add a lot of complexity to the whole process though.

The git-submodule has this to say about them:

Submodules allow foreign repositories to be embedded within a dedicated subdirectory of
  the source tree, always pointed at a particular commit.

You create a submodule just as you would a normal repo and include it in the main repo like so:

```<code>git submodule add <repository>
</code>```

where <repository> is the url to the repo to include.

The main question is why do you need to enforce this level of isolation and what happens if one part of the project has a dependancy on another one?

Edit

As the questioner has indicated that they want to protect IP from third party espionage action I have the following suggestion:

In stead of extracting the code for each person into a separate repository tree have the main IP that you want to keep separate contained in a "black box" library and have the development of that take place on a private repository by trusted developers. The untrusted developers can then develop the code that consumes this library in a less restricted repository.

This approach would have the advantage of requiring fewer repositories which will hopefully ease the process of development somewhat.

Title: GIT Permissions

Body:
You could let each individual create their section of the code in a submodule and then include all of the submodules into the main project. This would add a lot of complexity to the whole process though.

The git-submodule has this to say about them:

Submodules allow foreign repositories to be embedded within a dedicated subdirectory of
  the source tree, always pointed at a particular commit.

You create a submodule just as you would a normal repo and include it in the main repo like so:

git submodule add <repository>

where <repository> is the url to the repo to include.

The main question is why do you need to enforce this level of isolation and what happens if one part of the project has a dependancy on another one?

Edit

As the questioner has indicated that they want to protect IP from third party espionage action I have the following suggestion:

In stead of extracting the code for each person into a separate repository tree have the main IP that you want to keep separate contained in a "black box" library and have the development of that take place on a private repository by trusted developers. The untrusted developers can then develop the code that consumes this library in a less restricted repository.

This approach would have the advantage of requiring fewer repositories which will hopefully ease the process of development somewhat.


问:
How do you come up with algorithms?
I picked up some Project Euler questions today and decided to find more effective ways to Answer the questions  l had already answered.

So on the question about finding the sum of the even Fibonacci terms up to 4 million; I noticed that if we had a separate sequence for the even Fibonacci terms (starting with 0 & 2 as the first & second terms respectively), the progression would be [0,2,8,34,144,610,...]
If two values from two successive terms are known, then the next term could be gotten with this expression:

```<code>[ T(n) = (4 * T(n-1)) + T(n-2) ]
...
Where;
T(n) : is the nth term,
T(n-1) : is the (n-1)th term,
T(n-2) : is the (n-2)th term,
and '4' is a constant.
</code>```

However, so far I've been unable to derive an adequate expression to find the value in an arbitrary position without knowing the values of the two preceding terms.

My question:

Is this how equations (/algorithms) are derived?

Is this an efficient algorithm?

Footnote:
The other less efficient method (in my opinion), is to:

Create a function to generate all the numbers in the Fibonacci sequence under 4 million,

Get the even numbers among them,

Find their sum.

答:
This should probably be closed as too broad.  I mean, I'll refer to you to Polya's How To Solve It, which is something of a classic, but this list could go on too indefinitely.

A little more specifically -

Sort of. Yes, by a lot of thinking and reworking, but I do happen to know the closed form for Fibonacci off the topic of my head, since I majored in math and worked on problem sets that led me in this direction enough for me to figure out big parts of it on my own - "guided self discovery," if you will.  But, as a professional programmer, you spend your time not so much on this type of thinking and problem solving as you do researching, googling, and asking around until you find something.

There are certainly more efficient ways to do this. It's a personal decision on your part whether you want to figure out as much as you can on your own, or look up other ways.  My recommendation?  First one, then the other.

OwnerDisplayName: Takwas

Title: How do you come up with algorithms?


问:
Should I ask/tell my boss before freelancing?
I am currently working as an intern at a consulting firm. I am soon to move to a full time employee once I graduate next semester, and I love working there. However, as a student, I lack money and I have met a business owner outside of work who has offered to hire me for some freelance web development.

Because I met this individual outside of work, I feel it would not be a conflict of interest to freelance for him. However, the work his is wanting me to do is very similar to what I already do for my current boss.

Should I speak with my boss before considering the offer?

Edit: I understand that I cannot take IP from work, and I am not in a contract, I'm employed at will.

答:
You should check your local state/province/whatever's laws concerning this issue as a first step. If the rules are sane and distinguish work done away from work as being only your concern then you are not obligated to tell your boss anything. However, you know your boss better than anyone here will and may already have some clue as to his reaction. As long as no contract or law stands in your way you can do what you want to do.

In the past I have not shared with employers when I did work on my time that was not relevant to them. And, I don't share with clients information about work I do for other clients or my employer when it isn't relevant. Unless the work you are doing could create a conflict of interest I'd just keep it to yourself.

ContentLicense: CC BY-SA 2.5


答:
A closed-form expression (called Binet's formula) for terms of the Fibonacci sequence is well-known:  Fₙ = (φⁿ-ψⁿ)/√5, where φ=(1+√5)/2 and ψ=(1-√5)/2.  You might be able to prove that formula via the Master theorem for recurrences.  In any case, either by inspecting Binet's formula or by numerically calculating ratios of consecutive terms of the Fibonacci sequence, you should quickly observe that Fₙ is on the order of φ times larger than Fₙ₋₁.  Since φ is about 1.618, this implies that Fₙ grows rapidly enough with n that it soon exceeds 4 million.

Here is an example of some python code that computes Fibonacci values less than a limit.

```<code>def smallFib(fmax):
    a, b = 0, 1
    while b<fmax:
        print b
        a, b = b, a+b
</code>```

Run the code (that is, enter the code into a python interpreter, and then say smallFib(4000000)) and you will see that in fact only about 33 terms of the Fibonacci sequence are less than 4 million.  Thus, it makes sense to just do the simple thing, and add up the 11 of those terms that are even.  (To test if a number is even and add it to a sum if so, you can say if not b&1: sum += b.)

Note that Binet's formula does not give any apriori information about whether a term will be even or odd.  As it happens, every third Fₙ is even, so you could just compute F₃, F₆, F₉..., but to know that every third Fₙ is even you need to either inspect the numbers or prove something about Fibonacci numbers.  In many cases, using a slightly-complicated closed formula is not likely to save time compared to computing values via an extremely simple recurrence.

Summary:  Don't use a complicated approach when a simple approach will do.  Learn an interpreted language like python so that you can run simple tests to find out if a simple approach is good enough.

Title: How do you come up with algorithms?

Body:
I picked up some Project Euler questions today and decided to find more effective ways to Answer the questions  l had already answered.

So on the question about finding the sum of the even Fibonacci terms up to 4 million; I noticed that if we had a separate sequence for the even Fibonacci terms (starting with 0 & 2 as the first & second terms respectively), the progression would be [0,2,8,34,144,610,...]
If two values from two successive terms are known, then the next term could be gotten with this expression:

```<code>[ T(n) = (4 * T(n-1)) + T(n-2) ]
...
Where;
T(n) : is the nth term,
T(n-1) : is the (n-1)th term,
T(n-2) : is the (n-2)th term,
and '4' is a constant.
</code>```

However, so far I've been unable to derive an adequate expression to find the value in an arbitrary position without knowing the values of the two preceding terms.

My question:

Is this how equations (/algorithms) are derived?

Is this an efficient algorithm?

Footnote:
The other less efficient method (in my opinion), is to:

Create a function to generate all the numbers in the Fibonacci sequence under 4 million,

Get the even numbers among them,

Find their sum.

Body:
A closed-form expression (called Binet's formula) for terms of the Fibonacci sequence is well-known:  Fₙ = (φⁿ-ψⁿ)/√5, where φ=(1+√5)/2 and ψ=(1-√5)/2.  You might be able to prove that formula via the Master theorem for recurrences.  In any case, either by inspecting Binet's formula or by numerically calculating ratios of consecutive terms of the Fibonacci sequence, you should quickly observe that Fₙ is on the order of φ times larger than Fₙ₋₁.  Since φ is about 1.618, this implies that Fₙ grows rapidly enough with n that it soon exceeds 4 million.

Here is an example of some python code that computes Fibonacci values less than a limit.

def smallFib(fmax):
    a, b = 0, 1
    while b<fmax:
        print b
        a, b = b, a+b

Run the code (that is, enter the code into a python interpreter, and then say smallFib(4000000)) and you will see that in fact only about 33 terms of the Fibonacci sequence are less than 4 million.  Thus, it makes sense to just do the simple thing, and add up the 11 of those terms that are even.  (To test if a number is even and add it to a sum if so, you can say if not b&1: sum += b.)

Note that Binet's formula does not give any apriori information about whether a term will be even or odd.  As it happens, every third Fₙ is even, so you could just compute F₃, F₆, F₉..., but to know that every third Fₙ is even you need to either inspect the numbers or prove something about Fibonacci numbers.  In many cases, using a slightly-complicated closed formula is not likely to save time compared to computing values via an extremely simple recurrence.

Summary:  Don't use a complicated approach when a simple approach will do.  Learn an interpreted language like python so that you can run simple tests to find out if a simple approach is good enough.


问:
Improving the efficiency of containers with dynamically allocated objects
This is not strictly related to C++ but its type system serves to illustrate the problem well.

Assume:

We have a generic template Container<T> (such as a std::vector<T>) which stores an unspecified number of elements of the same type T on the heap.  Each element is allocated and deallocated via the constructor and destructor of T.

A type M that stores m elements on the heap (so M itself is a kind of container).  However, the value of m is not known at compile time, so it cannot be used as a template parameter to M.

Problem:

If we try to use a type Container<M>, accessing the elements of M inside this container would require two pointer dereferences, which in general has worse performance than if all elements of M were laid out contiguously.

Non-ideal solution:

Create a separate class ContainerFixed<T> that manages the memory of T directly, if T is assumed to have the same size throughout the container.  T would also have to exchange information about its storage with the containing class.  However, if we implement another kind of container, then we have to repeat this process again.

The problem arises because the container class is oblivious of the storage requirements of T so it defers the allocation to T itself; if the container had known that T only requires a fixed (though not known at compile time) number of elements then this issue could have been avoided.

Now I feel as though that if there was some way to communicate to the container that M has a definite size m (as in M<m>, which is not legal in C++), then from the type signature of Container<M<m> > one can potentially deduce that a faster allocation scheme is possible.  (It's a bit like dependent types, in a way.)  That is, any Container1<Container2<m> > can be allocated more efficiently as a "flattened" container.

What would be a more general solution to this problem?  I don't think this is something that can be easily solved in C++ (feel free to prove me wrong), so I would certainly like to hear if this is something that other languages can solve in a much simpler way (perhaps with more sophisticated type systems).

答:
I think you could more or less solve this by having an API similar to allocators, whereby a container could specify how to allocate its metadata and elements contiguously. That is, a container would provide an “unboxed mode” in which it would presumably be immutable, or at least of fixed size. You couldn’t allocate unboxed containers on the stack because their sizeof is not a compile-time constant, but you could use this API when constructing a nested container.

This would seem to work naturally for std::vector and std::array, but for std::list and std::deque (which is typically implemented as a linked list of fixed-size chunks) or tree structures such as std::map, it’s not necessarily clear what such “unboxing” would actually mean. Do you stand to gain from allocating all the nodes in the tree contiguously, but still traversing them with lots of pointer indirections? Without benchmarking it’s hard to say.


问:
When should we stop work and make tool?
As a software engineer, we are always eager to get effective tools to boost our productivity.
And in our daily work, we are often unsatisfactory with the existing tools and would like to have better ways such as better GDB script config, Vim script and some Python script to make boring things automatic.

However, it is actually a trade-off since making tools also needs time and energy. It does not give productivity boosting immediately. Therefore, how do you judge whether it is time to stop work and to make some tools to ease your future pain?

答:
I "make tools" when one of these is true:

The task is annoying me

The risk of human error in the task is too big

The "risk" for the 2nd option doesn't have to be huge - the cost of building one small tool is usually small, so if all you save is the risk of running a 10-minute build again once a week, it will usually repay itself very fast.

I try to make tools as small as possible - just make the task a little bit easier now, and maybe improve again next time.

This means you only fix the biggest pain each time, and not creating fixes to problems that don't really hurt you.

Title: When should we stop work and make tool?


问:
How does GDI/+ work and can it be replaced with my own code?
On wikipedia it says that GDI is an API and core operating system component responsible for representing graphical objects and transmitting them to output devices.

I'm not finding much on what GDI+ actually does so I'm wondering, is GDI+ replaceable with gui frameworks like wxWidgets and GTK+ or are those frameworks rather built on top of GDI+?

When drawing to screen with GDI+ it seems it makes sure one doesn't draw outside of the application's window. Is it actually GDI+ doing this and if not, what is? If it is GDI then doesn't everything have to go through GDI+ to promise this functionality and not let applications paint anywhere they want?

Where does the framebuffer come into all of this? I would imagine that whatever controls the coordinate transforms controls the framebuffer as well. However it seems applications have much control of framebuffers and how to use them. I see that OpenGL has multiple types of framebuffers and functions for generating framebuffers, deleting them, ect. And I'm reading that they are stored in video memory. I would imagine that gui frameworks that are not as heavily involved with the GPU don't store theirs in video memory. So how does this stuff work and interact with the transformations?

答:
1) GDI+ is Windows' library that handles low-level screen drawing... lines, bitmap copying, that kind of stuff. You don't replace it. Other GUI frameworks on Windows are implemented on top of GDI. GDI+ itself is theoretically implemented on top of DirectX.

2) GDI knows about clipping areas, but not really about windows or their borders; when you're drawing in a window, it talks to the USER library, which does know about window positions, to figure out the appropriate clipping area. There's a certain amount of blurring of responsibilities here; some functions that "rationally" belong in USER are in GDI for performance or historical reasons.

3) A frame buffer can be an bitmap in RAM that might eventually be copied to video memory, or it can be video memory directly mapped into the CPU's address space. If you're using GDI, don't think about frame buffers. If you use OpenGL or DirectX, you use the frame buffers those interfaces provide.


问:
Code formatting SQL queries
Should I break SQL queries in different lines? For example in the project I am working on, we have a query that is taking 1600 columns! 1600 + tab chars. I wrote queries like this:

```<code>   "SELECT bla , bla2 , bla FROM bla " .
     "WHERE bla=333 AND bla=2" .
      "ORDER BY nfdfsd ...";
</code>```

But they demanded me to put them in one line and said that my style is bad formatting. Why it is bad practice?

答:
A query that is 1600 columns sounds like it needs some serious review by a good DBA.

If a query is complex I'll wrap it. If it's straightforward I'll leave it as a single line unless it's going to be too long, then I'll start wrapping it again.

It's all about manageability and comprehending what it is supposed to do so wrapping or not wrapping can be decided on the fly, unless your organization has some code formatting rules about it.

Re: it being bad coding practice. Hardly! It's very good practice. There are no good reasons I know of to use a query that long, and many good reasons to reformat it. As I said before, a skilled DBA probably needs to work on it.

Title: Code formatting SQL queries


答:
With experience I have found that just pushing hard on the grunt work is usually the most time-efficient.  Making a tool is often tempting. I give up resisting when:

The tool has more than one purpose.  A good chess player accomplished two things with each move: block an opponents piece and free up a bishop.  A beginner would probably need two turns to do that.  Likewise, I consider if the tool would only do one thing, or with small extra effort do two, e.g. help fix some raw data  files, and also create artificial test data.

Future usefulness. It might save me time for this weeks' work, but is it likely to save me or someone time on a new project next week?

It is a good time to learn a new language, library, design technique or whatever, and I have the time to do it.  The tool is a beneficial side effect of doing something education, using time already granted for education.

When we're having serious problems getting things to work.  Like skydiving without a parachute, you really should take the time to make or buy a parachute.  If you can't get any meaningful experimental results, or the new web app won't work at all, you just gotta stop and make or buy a tool to measure what you can't see, drive components, or replace part of the system. When the work is totally hung up in need of a tool, I don't care about future use or multiple use. Necessity weighs enough.

Title: When should we stop work and make tool?

Body:
As a software engineer, we are always eager to get effective tools to boost our productivity.
And in our daily work, we are often unsatisfactory with the existing tools and would like to have better ways such as better GDB script config, Vim script and some Python script to make boring things automatic.

However, it is actually a trade-off since making tools also needs time and energy. It does not give productivity boosting immediately. Therefore, how do you judge whether it is time to stop work and to make some tools to ease your future pain?


问:
For what reasons  should I choose C# over Java and C++?
C# seems to be popular these days. I heard that syntactically it is almost the same as Java. Java and C++ have existed for a longer time. For what reasons should I choose C# over Java and C++?</p>

答:
You should chose the best language for your expected environment and your expertise.

Chose C# if you are working in a Microsoft only environment.  While C# is standardized under ISO/IEC 23270:2003, Microsoft's version remains the only complete implementation.  Several key parts of the language are not covered by the standard and are thus subject to Microsoft's patents. No one else will implement a completely compatible version of the language for other systems, so in effect, you are vendor locked to Microsoft Windows and .Net for as long as you use the language. If you are looking for skills to use in the mobile market, best to look to another language.

Java works, but has a good deal of overhead, in part due to such features as garbage collection.  Java is also not standardized by ISO/IEC, so you have no guarantees if you switch platforms and versions of Java, only Sun/Oracle's best intentions.  If you are eventually planning to work with Android, this is definitely the way to go.  Android's programming is basically Java, with a few changes.

C++ is standardized and almost all compilers follow the international standard, so you have guaranteed behavior BUT the language does not protect you from yourself.  You have to perform cleanup and overflow checking on your own.  This is not hard.  C/C++ programmers have been doing these for many years.  Apple uses Objective C for everything, so if you want to aim for Apple, I recommend you try this instead.

If you see yourself leaving Windows behind at some point, I'd suggest learning both C/C++ and Java - both of which are marketable at this time.


问:
How to provide a ubiquitous object without including it in every parameter list
I'm writing a small C++ class, Block, to transform serialized data into a memory structure, and supply the structured data to callers through several accessor methods.  I've tried to keep its scope specific and limited.  The users of the class are very low-level - they, too, are very narrow in their focus and have as few external dependencies as possible.

This is how I've been taught to engineer things if at all possible.  By minimizing dependencies and creeping featurism, it's easier to unit test, and easier to reuse.

The problem is that my class depends upon someone else's class, Metadata.  It, too, does one very specific thing: it reads data that defines the characteristics of the data stream I'll be transforming from a database table and passes it to me.  His class checks for mySQL errors, which should be rare, and logs any errors to a Log object.

This Log object appears in all of our company's applications.  Instantiating it is a big deal - it wants Job numbers, it wants a lot of configuration information from the database that's normally put there in production by account managers using a GUI.  You have to do a lot of work before your program can instantiate the Log.  Yet this tiny, low-level class (Metadata) with one tiny task wants it to be passed in, by me.  My object certainly has no business instantiating the Log, so I have to take it as a parameter from whoever calls me.  And so forth, up the calling hierarchy.

I can understand why management wants a class to encapsulate and standardize message logging.  But the need for it to be passed to, and through, just about every method is extremely ugly, and makes testing and reuse much more difficult.

This kind of problem must be fairly common.  How can this be done without cluttering up the signature of every method you write?  Is this a legitimate case for Globals?  Is there some kind of Object Oriented approach?  And, is this a God object?

答:
A God Object does everything for everyone. It's an unstructured program hiding in the guise of an OOP class, but one that is way too large by any measure.

In contrast, both your class and the Log are reasonable-size classes that do one thing and do it well. Your only problem is that the Log has to be available everywhere. If this is really the case, and it is clear that there will be only one Log object in the process, then making it global is the appropriate thing to do.

(There is a lot of hate for global variables (and for singleton objects) based on the horrible mess they make when used them for anything else, such as intermediate results, error codes, or even loop counters (shudder), but as always there's a spectrum of reasonable and unreasonable things you can do with them. Your case sounds like just about the most reasonable use for a global I can think of.)


答:
Since the logger is some kind of infrastructure it is ok to not pass it around in every call.

In the java and c# world usually every class that need a logger has a static private logger that the class gets from a logger factory

```<code>using log4net;
namespace MyNamespace
{
   public class MyClass
   {
      private static readonly ILog log = log4net.LogManager.GetLogger("MyNamespace.MyClass");

      public void someFunction() {
         log.debug("someFunction was called");
      }
</code>```

This approach assumes that the logger stays always the same instance so the performance overhead is minimal (only one factory call per class).

Alternativly a more dynamic logger that can be changed at runtime could be used through a public static method (singelton)

```<code>namespace MyNamespace
{
   public class MyClass
   {
      public void someFunction() {
         Global.getLogger().debug("someFunction was called");
      }
</code>```

[update 2013-07-14]

answering chaps questions:

In the classlibrary log4net every class gets its own logger instance.
The parameter in log4net.LogManager.GetLogger("MyNamespace.MyClass") is the name of the logger. through configuration you can tell the "MyNamespace.MyClass" logger
  - to be enabled/disabled
  - that every logging line should be prefixed with "MyNamespace.MyClass"

Title: How to provide a ubiquitous object without including it in every parameter list

Body:
I'm writing a small C++ class, Block, to transform serialized data into a memory structure, and supply the structured data to callers through several accessor methods.  I've tried to keep its scope specific and limited.  The users of the class are very low-level - they, too, are very narrow in their focus and have as few external dependencies as possible.

This is how I've been taught to engineer things if at all possible.  By minimizing dependencies and creeping featurism, it's easier to unit test, and easier to reuse.

The problem is that my class depends upon someone else's class, Metadata.  It, too, does one very specific thing: it reads data that defines the characteristics of the data stream I'll be transforming from a database table and passes it to me.  His class checks for mySQL errors, which should be rare, and logs any errors to a Log object.

This Log object appears in all of our company's applications.  Instantiating it is a big deal - it wants Job numbers, it wants a lot of configuration information from the database that's normally put there in production by account managers using a GUI.  You have to do a lot of work before your program can instantiate the Log.  Yet this tiny, low-level class (Metadata) with one tiny task wants it to be passed in, by me.  My object certainly has no business instantiating the Log, so I have to take it as a parameter from whoever calls me.  And so forth, up the calling hierarchy.

I can understand why management wants a class to encapsulate and standardize message logging.  But the need for it to be passed to, and through, just about every method is extremely ugly, and makes testing and reuse much more difficult.

This kind of problem must be fairly common.  How can this be done without cluttering up the signature of every method you write?  Is this a legitimate case for Globals?  Is there some kind of Object Oriented approach?  And, is this a God object?

Body:
Since the logger is some kind of infrastructure it is ok to not pass it around in every call.

In the java and c# world usually every class that need a logger has a static private logger that the class gets from a logger factory

using log4net;
namespace MyNamespace
{
   public class MyClass
   {
      private static readonly ILog log = log4net.LogManager.GetLogger("MyNamespace.MyClass");

      public void someFunction() {
         log.debug("someFunction was called");
      }

This approach assumes that the logger stays always the same instance so the performance overhead is minimal (only one factory call per class).

Alternativly a more dynamic logger that can be changed at runtime could be used through a public static method (singelton)

namespace MyNamespace
{
   public class MyClass
   {
      public void someFunction() {
         Global.getLogger().debug("someFunction was called");
      }

[update 2013-07-14]

answering chaps questions:

In the classlibrary log4net every class gets its own logger instance.
The parameter in log4net.LogManager.GetLogger("MyNamespace.MyClass") is the name of the logger. through configuration you can tell the "MyNamespace.MyClass" logger
  - to be enabled/disabled
  - that every logging line should be prefixed with "MyNamespace.MyClass"


答:
In relation to C++ vs C# (as i'm not proficient enough in Java), what i'm missing here is the ability to access lowlevel stuff on Windows. For example, you cannot develop a native display driver in C# (yet), but you can with C++. This does not make C++ better. I see C++ versus C# as Assembly versus C.

C# is in my view much more efficient if you look at the time it takes to actually implement a feature. The performance penalty of the .Net runtime is negligible for 99% of the applications developed. It may be of significance if you are running a tight loop, yes by all means, but most of the time an application is idle, waiting for any kind of input, signal or interrupt (disk IO, button click, network, animation completion).

The CLR library with all his functions has another big benefit. When i was training C# to junior developers, most of them said they liked the logical naming convention of classes, members and namespaces. Finding a feature of method was logical across the SDK, something that Visual Basic 5 was seriously flawed at. This has helped them tremendously in adopting the library. After learning the syntax of a language, getting to learn a new library is significant into getting a good grasp of any SDK. It saves you from reinventing the wheel.

Body: C# seems to be popular these days. I heard that syntactically it is almost the same as Java. Java and C++ have existed for a longer time. For what reasons should I choose C# over Java and C++?</p>


问:
Comparing performance of different C++ self-made tree data structures
I have two tree data-structures that I made in C++ , and they give a response for range queries/point queries in that program. I am using Ubuntu. I need help in understanding the way to compare the performance of these two data structures (for answering the query in that program) in external memory. How can I do this?

I searched a lot on the Internet, and I didn't find any clear idea on how this is done. I know I can measure disk I/O, memory consumption, CPU usage, etc. using Ubuntu's dstat, and iostat commands. I need some accurate and professional way to do this.

答:
Write a test program executing the same set of queries against the same set of data using either the first or the second data structures. Measure the running time for both scenarios. Compare.

Of course, you should make sure that your test queries are representative for the kind of queries you may have to execute in production. And you should make the number of queries big enough to be sure you measure actually the running time of the queries (and not the start-up time of your test program, for example).

EDIT: to your comment: for getting information about disk IO or memory consumption, I think you may look into the Linux "/proc" filesystem and check if it contains what you are after. For example, /proc/<your process id here>/smaps gives you the memory usage.


答:
It depends on what you consider as making a tool.  Arguably I make loads of them in ways that other devs would consider frivolous... Because I make them for just about everything except the most basic filesystem commands.

I use 2 rationales to support that.

It's an extension of the DRY principle. If we want to repeat something,
manual effort is the least effective use of human resources.

It's an effective way to record what I did, so if I built something then I (or
someone else) may want to refer back to how I did it weeks or months
later and it keeps the log of work with the project.

Occasionally they grow into bigger tools and gain interactive functions, but if they don't they still have value as a record.

Title: When should we stop work and make tool?


问:
Are the technologies used in an application part of the architecture, or do they represent implementation/detailed design details?
When designing and writing documentation for a project an architecture needs to be clearly defined: what are the high-level modules of the system, what are their responsibilities, how do they communicate with each other, what protocols are used etc. But in this list, should the concrete technologies be specified or this is actually an implementation detail and need to be specified at a lower level?

For example, consider a distributed application that has two modules which communicate asynchronously via AMQP protocol, mediated by a message broker. The fact that these modules use the Spring AMQP library for sending and receiving messages is a fact that needs to be specified in the architecture or is a lower-level detailed design/implementation detail?

答:
using AidanCully definition

Architecture is that which is hardest to change.

you can decide yourself if technology/library is architecture or implementation detail.

If you hide the technology/library behind abstraction layer/facade then this abstraction becomes part of the architecture and the technology/library is implementation detail.

If you use the technology/library directly (without hiding it behind an abstraction) then technology/library is part of the architecture.

Example: In the context of MessageQueing you can

use RabbitMQ broker directly  (as part of the architecture)

use spring-amqp abstraction (as part of the architecture) so using RabbitMQ is an implementation detail

Implement your own Message-facade (as part of the architecture) so using amqp, asynchron operation, the existence of a queue are all implementation details.

Example: In Microsoft.net you can

use the mssql-ado.net database provider directly (as part of the architecture)

or you can use the oledb-database-abstraction (as part of the architecture) so mssql becomes an implementation detail

or you can use a repository  (as part of the architecture) to hide the existence of a database as an implementation detail


问:
Overloading to support multiple related types (especially pointers)

Problem

I was just trying to debug a set of file-manipulation routines I wrote for a program I am working on. One of them kept returning an INVALID_HANDLE error.

Explanation

I figured out what the problem was. It turns out that because I provided several overloads so that I could call the function with either a file handle or filename, I ended up creating ambiguous overloads.

For example (not variadic functions; the ellipses are just for simplification purposes):

```<code>INT CopyFileSection ( HANDLE fIn, HANDLE fOut, … );
INT CopyFileSection ( HANDLE fIn, TCHAR* fOut, … );
INT CopyFileSection ( TCHAR* fIn, HANDLE fOut, … );
INT CopyFileSection ( TCHAR* fIn, TCHAR* fOut, … );
</code>```

The first one (HANDLE, HANDLE) does the main work while the others just open the file pointed to by the filename and call the first function.

The problem is that a HANDLE is just a pointer, so the compile can’t figure out which one I am calling (even though to me it was obvious), and ends up calling HANDLE, HANDLE even when I pass a pointer to a string, so naturally it fails since the pointer is not a file handle.

Question

I want to provide maximum flexibility, so short of re-writing to use std::string instead of TCHAR* for the filenames (which I actually did include as well), what suggestions are there to deal with this sort of scenario?

Related

As a related side note—a separate question?—I was wondering about the ease, safety, and feasibility of providing overloads for all (or at least a set of) possible permutations.

For example, with a function that takes two files, you could use HANDLE, TCHAR*, and string (probably others, but in this case we’ll stick with these three). This means there are up to nine overloads just for the files: HH, HT, HS, TH, TT, TS, SH, ST, SS. Let alone if there are other arguments that could provide more overloads. Surely there must be a better way to both provide flexibility in calling the function and clean, understandable, and maintainable code.

答:
The easiest way to limit the combinatorial explosion of your overloads is to introduce a small helper class that can accept all the various types and convert them to a single common type.

For example

```<code>class FileHelper {
public:
    FileHelper(HANDLE& h) : handle(h) {}
    FileHelper(const TCHAR* fName) : handle(openFile(fName) {}
    FileHelper(const std::string& fName) : handle(openFile(fName) {}

    HANDLE getHandle() const { return handle; }
private:
    HANDLE handle;
}

INT CopyFileSection ( FileHelper fIn, FileHelper fOut, … );
</code>```

There is only one overload of CopyFileSection and that overload takes two FileHelper instances as stand-ins for a pair of file handles. The FileHelper class takes care of accepting the different possibilities (existing handle, file name, etc.) and obtaining a file handle for each of them.

Note that the first FileHelper constructor takes a non-const HANDLE reference. This was done deliberately to inhibit conversions from types that could be converted implicitly to a HANDLE, such as (other) pointer types. This has the side-effect that you also can't pass directly handles that were returned by a function, but they need to be stored in a variable first.

Body:
The easiest way to limit the combinatorial explosion of your overloads is to introduce a small helper class that can accept all the various types and convert them to a single common type.

For example

class FileHelper {
public:
    FileHelper(HANDLE& h) : handle(h) {}
    FileHelper(const TCHAR* fName) : handle(openFile(fName) {}
    FileHelper(const std::string& fName) : handle(openFile(fName) {}

    HANDLE getHandle() const { return handle; }
private:
    HANDLE handle;
}

INT CopyFileSection ( FileHelper fIn, FileHelper fOut, … );

There is only one overload of CopyFileSection and that overload takes two FileHelper instances as stand-ins for a pair of file handles. The FileHelper class takes care of accepting the different possibilities (existing handle, file name, etc.) and obtaining a file handle for each of them.

Note that the first FileHelper constructor takes a non-const HANDLE reference. This was done deliberately to inhibit conversions from types that could be converted implicitly to a HANDLE, such as (other) pointer types. This has the side-effect that you also can't pass directly handles that were returned by a function, but they need to be stored in a variable first.


问:
Is there a proper way to allow access to private list by reference?
I'm trying to provide a by-reference getter to a list of objects in a class. My setup looks something roughly like this:

```<code>class c_Container
{
public:
    c_Item* Get(int uid);
private:
    c_Item itemList[10];
}

class c_Item
{
public:
    int uid;
}

c_Item* c_Container::Get(int uid)
{
    for (int i = 0; i < 10; i++)
    {
        if (itemList[i].uid == uid)
        {
            return &itemList[i];
        }
    }

    return NULL;
}
</code>```

This is a simplistic example showing usage, usually a c_Item object would have other methods that would do other things. We'd want to obtain the c_Item object from itemList by reference or by address so that we can directly modify it.

When compiling, I get a lint error something like "Exposing low access member 'itemList'". If I try to return by reference instead of returning a pointer, I get the same thing. I guess I understand why, but I can't conceive of a better way to obtain an object from a container class like this by reference. I can fix the error by making itemList public, but that seems like unnecessary access.

Outside of creating wrapper methods in c_Container for all of c_Item's methods (which seems redundant), is there a better way to handle a situation like this?

答:
Container classes are an exception to the general rule that you should not provide public access to private members (by returning a pointer or reference in a getter).

However, a lint tool is not smart enough to determine if the container exception should apply to your Get method or not, so it tries to make the safe assumption and generates a warning.
Most lint tools can be given additional information through source code annotations. Check the documentation for your tool to see how it can be informed that the warning for this function is a false-positive and should be suppressed.


问:
Learning basic graphics programming
After learning the basics of computing simple die throwing games and calendar applications, I want to explore simple graphics - drawing and moving around geometric objects is ok to start with, eventually adding pixel graphic of course.

I've taken an introductory Java course but would rather do it in C++, Python or a combination of them (that's what we will eventually be using in school). I also want to learn the principles behind it, not just blindly applying incomprehensible syntax to make the compiler happy.

Some posts seem to imply SFML is a solid choice, so I thought I'd get a book covering it and work through it, but there only seems to be ONE book on SFML available, and that one hasn't been reviewed at all. Not in the mood for a $30 gamble, so I'm feeling kind of lost!

How should I approach learning basic graphics programming?

答:
SFML is indeed a good choice to begin with, at least in my opinion. From what I've heard, it's easier than SDL and Allegro. It's also in C++ while the two others are more C based. Personnaly, it's the one I'm trying to pick up at the moment.

SFML offers binding for many other languages (C, Python, Ruby, etc.) and many custom bindings can be found. It is based on five modules and you can use whichever you need: Graphics, Window, Audio, Network, System. It works under Window/Mac/Linux. It can also use OpenGL.

As for the book, I do not know about it. However, the SFML wiki is quite good and offer a lot of resources to start working with it. Furthermore, the SFML wiki forwards to some tutorials and helpful pages to start working with the library. For instance, I found the CodingMadeEasy youtube video series that goes through SFML 2.0 over a few hours and is a useful introduction. Paired with the documentation and wiki pages, it shouldn't be hard to pick up, for only $0.

Title: Learning basic graphics programming


问:
Can continuous delivery work in a big enterprise environment with lots of connected systems?
Much has been said lately of continuous delivery. It does sound appealing, but runs against the grain of convention wisdom in big corporations.

Jez Humble - Continuous Delivery

Thoughtworks Presentation - Continuous Delivery - Part 1

Thoughtworks Presentation - Continuous Delivery - Part 2

Assuming the following:

You have a number of remote systems connected via ESB

You have an established system with several years of coding changes applied to it

This is a website that allows financial transactions

There are multiple backend systems responsible for processing different types of transactions

Currently production releases assume a multi $10K investment in a manual regression test

Can Continuous Delivery be implemented in such an environment? (ie is the underlying assumption behind Continuous Delivery that you invest a large amount in automated regression testing that is coordinated across systems?)

(Surely automated unit tests can prove a system is not incorrect, but can't prove it is correct).

答:
Plenty of large enterprises are doing continuos delivery -- I'd think Amazon or Google would qualify.

I think the conventional wisdom it runs into in large places is a wetware issue. There is some group that "owns" delivery and they are not going to like losing seats when you eliminate their manual testing routine and the black magic of a "deployment."

On a technical level you are correct about tests and that applies to human tests as well. Probably the key thing to figure out is how to deal with rollbacks more than how to deliver the product.


问:
65.000.000.000 tests to run
I was asked about how to run a suite of 65.000.000.000 tests and I wonder if it is normal to have a project with such a huge amount of tests.

Have you worked in projects with this characteristic?

答:
Although there have been several good suggestions here on how to try to sneak by with fewer tests, I seriously doubt your system has only 65 billion input combinations. That is less than 36 bits of input. Let's assume you had already taken all the advice given above.

If each test takes about a millisecond to run and you distribute the tests across only 10 processors (one normal PC), the test will run in a little over 69 days. That is a while, but not completely unreasonable. Distribute across 100 processors (a dozen normal PC's or one reasonable server PC) and the tests will complete in a under 7 days. You could run these every week to check for regressions.

Title: 65.000.000.000 tests to run


问:
When and for what purposes should the const keyword be used in C for variables?
While getting my code reviewed here the issue of using the const keyword came up. I understand that it is used for implementing read-only behaviour on variables.

I am confused about what are the various situations when it can be useful.

Should it be used for the sake of clarity in function prototypes?

Should it be used as a security measure during code development?

Should it be used in the scope of various functions for declaring run-time constants?

Should it be used at all?

These question are just examples of the confusion that I am facing. The general confusion is

When should be the const keyword used in C programming?

What are the various types of benefits that can be gained by using this keyword in C?

Are there any cons of using const keyword?

It has been pointed that this question may be too broad due to all these questions in the detail of my question. I just wanted to clarify that these questions are just to clarify the confusion regarding the main question.

When and for what purposes should the const keyword be used in C for variables?

It can also be rephrased as

The proper use of const keyword in C` with the pros and cons of the same.

答:
Yes, it's basically the TheLQ's answer.

Is a security measure for the programmer so you don't modify a variable, and to not call functions that may modify them. In an array or structure the const specifier indicates that the values of their contents won't be modified, and even the compiler will not allow you to do so. You still can easily change the value of the variable with just a cast however.

In what I have usually see, it's mostly used to add constant values in code, and to indicate that the array or structure won't be modified if you call a particular function. This last part is important, because when you call a function that WILL modify your array or structure, you may want to keep the original version, so you create a copy of the variable and then pass it to function. If that is not the case, you don't require the copy, obviously, so for example you can change,

```<code>int foo(Structure s);
</code>```

to

```<code>int foo(const Structure * s);
</code>```

and not getting the copy overhead.

Just to add, note that C has particular rules with the const specifier. For example,

```<code>int b = 1;
const int * a = &b;
</code>```

is not the same as

```<code>int b = 1;
int * const a = &b;
</code>```

The first code won't allow you to modify value points by a. * a = 3; will error out.
In the second case, the pointer is constant but its contents is not, so the compiler will allow you to say * a = 3; without a compiler error, but you can't make a to be a reference to another thing.

Body:
Yes, it's basically the TheLQ's answer.

Is a security measure for the programmer so you don't modify a variable, and to not call functions that may modify them. In an array or structure the const specifier indicates that the values of their contents won't be modified, and even the compiler will not allow you to do so. You still can easily change the value of the variable with just a cast however.

In what I have usually see, it's mostly used to add constant values in code, and to indicate that the array or structure won't be modified if you call a particular function. This last part is important, because when you call a function that WILL modify your array or structure, you may want to keep the original version, so you create a copy of the variable and then pass it to function. If that is not the case, you don't require the copy, obviously, so for example you can change,

int foo(Structure s);

to

int foo(const Structure * s);

and not getting the copy overhead.

Just to add, note that C has particular rules with the const specifier. For example,

int b = 1;
const int * a = &b;

is not the same as

int b = 1;
int * const a = &b;

The first code won't allow you to modify value points by a. * a = 3; will error out.
In the second case, the pointer is constant but its contents is not, so the compiler will allow you to say * a = 3; without a compiler error, but you can't make a to be a reference to another thing.

ContentLicense: CC BY-SA 4.0


问:
How to justify migration from Java 6 to Java 7?
We were migrating from Java 6 to Java 7. The project is behind schedule and risks being dropped, in which case it will continue to use Java 6.

What are the specific improvements in Java 7 that we could go back to our manager with and convince him it is important to use JDK 7? Looking for bug fixes that  I could highlight in Oracle Java 7 (with respect to Java 6). Fixes in security, performance, Java 2D/printing, etc. will be more sellable in my case. Compiler fixes for example, will not of much use.

[I am going through many sites like Oracle adoption guide, bug database, questions on Stack Overflow].

Update: Thanks for the answers.  We rescheduled the update to next release.  Closest we got was security.  Accepting the highest voted answer.

答:
try-with-resources is a feature that's worth upgrading to Java 7 for, all on it's own.  Resource leaks / memory leaks are a big risk in Java development and TWR reduces that risk significantly.

I'll add the that new NIO.2 File abstraction and Asynchronous capabilities are also worth moving to if your application has File/Networking I/O features.


答:
My rule of thumb is that when I have to do something for the third time, it's time to either write a little script to automate it, or rethink my approach.

I'm not making a full-blown "tool" at this point, just a little script (usually bash or python; perl would work too, or even PHP) that automates what I did manually before. It's basically an application of the DRY principle (or the Single Source Of Truth principle, which is in essence the same thing) - if you have to change two source files in tandem, there has to be some common truth that they share, and that truth has to be factored out and stored in one central place. It's great if you can solve this internally by refactoring, but sometimes, this isn't feasible, and that's where the custom scripts come in.

Then later, the script may or may not evolve into a full-blown tool, but I usually start out with a very specific script with lots of things hard-coded into it.

I hate grunt work with a passion, but I also strongly believe that it is a sign of bad or incorrect design. Being lazy is an important quality in a programmer, and it better be the kind where you go through great lengths to avoid repetitive work.

Sure, sometimes the balance is negative - you spend three hours refactoring your code or writing a script to save you one hour of repetitive work; but usually, the balance is positive, more so if you consider costs that aren't directly apparent: human failure (humans are really bad at repetitive work), smaller codebase, better maintainability due to reduced redundancy, better self-documentation, faster future development, cleaner code. So even if the balance appears negative right now, the codebase will grow further, and that tool you wrote to generate web forms for three data objects will still work when you have thirty data objects. In my experience, the balance is usually estimated in favor of grunt work, probably because repetitive tasks are easier to estimate and thus under-estimated, while refactoring, automating and abstracting are perceived as less predictable and more dangerous, and thus over-estimated. It usually turns out that automating isn't that hard after all.

And then there's the risk of doing it too late: it's easy to refactor three
brand new data object classes into shape and write a script that generates web forms for them, and once you've done that, it's easy to add 27 more classes that also work with your script. But it's close to impossible to write that script when you have reached a point where there are 30 data object classes, each with hand-written web forms, and without any consistency between them (a.k.a. "organic growth"). Maintaining those 30 classes with their forms is a nightmare of repetitive coding and semi-manual search-replace, changing common aspects takes thirty times as long as it should, but writing a script to solve the problem, which would have been a lunch break no-brainer when the project started out is now a frightful two-week project with the dreading prospect of a month-long aftermath consisting of fixing bugs, educating users, and possibly even giving up and reverting to the old codebase. Ironically, writing the 30-class mess took way longer than the clean solution would have, because you could have been riding the convenient script all that time. In my experience, automating repetitive work away too late is one of the major problems in long-running large software projects.

Title: When should we stop work and make tool?


答:
I just remembered this:

The problem with this of course is that in real life situation you can't easily measure those data to select the right cell in the table. And as it was mentioned in other answers, there are other variables (the risk of error, task is too boring to do it even once, ...) you need to add to the equation.

So my answer is that it really depends on the situation and you can not hope to get any "correct" answer for all the situations. After all life would be boring if we had cookbooks for everything.

Title: When should we stop work and make tool?