问:
Is it okay to not completely understand code functionality?
As I am currently struggling with learning WCF for a project at work, for the past several days I have been looking at online tutorials and examples on the best way to make a WCF client; and today, when I told my boss I was having a hard time finding good tutorials because some of them would not go into details with their examples (for instance showing a piece of code that works but not explaing why exactly, or making an example with just a few lines instead of at a larger scale), he told me that I should not try to understand them completely, because there are times where a code will just do what it does and I should leave it at that (he gave me the example that when doing calculus, for instance, we use formulas that we don't know how they were conceived or how they work, we just know that they do and we use them).

And this bothered me because I have always been told that it's really important to understand your code, and that just copying and pasting without knowing HOW it works is practically a sin; which is why I always take my time in understanding something before moving forward with it. And it's not like I'm trying to understand how a particular class works at an assembly language level, I just want to know why a set of instructions does the trick, and why another one doesn't, or why both do and under what circumstances. But my boss tells me that I will end up wasting time obsessing over these little details, and I should just skip it. So my question is, is he right? Is it okay to understand your code only to a certain extent and keep going, and have I only been obsessing over little things that don't matter?

答:
The sole purpose of software abstractions is to hide functional details.  Were it not for those abstractions, it would not be possible to progress beyond a certain point in computing, because systems would simply collapse under the weight of their own complexity.  Human brains can only comprehend so much information at once.

Consider what happens when you write a method.  When you write a method, what you are doing is hiding some bit of software functionality behind a method call.  Once that method is written and proven to work by writing unit tests about that method, you no longer have to think about what's inside that method unless you need to change something about its implementation.

Large software systems are built upon many layers of these abstractions.  You have a microcode layer in the processor, machine code, address and data buses, language compilers, object-orientation, data structures, domain-specific languages, and so on.  You have libraries built on top of other libraries, which in turn are built on top of an operating system.  You don't fully understand how any of that stuff works either, but you're still able to successfully write computer programs that do something useful.

That said...

You can't just copy/paste code without understanding how it works.  The person who tries to make his program work by copy pasting code that he doesn't understand is setting himself up to fail.  You need to understand the code you write.  That doesn't mean that you have to know how WCF works internally, but you do need to know what the purpose of WCF is, how to write code that properly interfaces it, and how the code you write functions in concert with it.  Many copy/paste programmers don't even have a decent understanding of the programming language they are copy/pasting, let alone in-depth knowledge of the libraries they are using.

So you need to have some decent skills, and you need to understand the code you write (or paste) that calls WCF.  But you don't need to have in-depth knowledge about how WCF works internally.

Similarly, programmers who think they can stitch together a program by randomly wiring up software patterns are missing the point.  We call those folks Cargo Cult programmers.


答:
There are three different parts to understanding software:

First is understanding why a piece of software (as big as an application or as small as a single function) exists. You need to know the point of it, why it was written.

Next I think is understanding what a piece of code does.

Finally is knowing how a piece of code works, what it's internals look like and do.

Which of these you need to have a grip on in order to understand a piece of software differs depending on what you need to do with that code.

For example, take .NET's String.ToUpper() method. I know what this method does, and why you would want to use it, but I don't know how it's written (that's an implementation detail) and I don't really care - as long as I can use properly. I won't ever need to modify this method, so my understanding of the internals isn't necessary.

If I was copying code off the Internet, I need to make entirely sure of what the code does and why. If I was just copying it and never modifying it (unlikely) then I don't feel any need to understand how it works. But if I was going to be modifying it (likely) then I'll need to know how it works - otherwise I'm just using guesswork to modify the code, and that's probably not going to end well.

ContentLicense: CC BY-SA 3.0

Title: Is it okay to not completely understand code functionality?

Body:
As I am currently struggling with learning WCF for a project at work, for the past several days I have been looking at online tutorials and examples on the best way to make a WCF client; and today, when I told my boss I was having a hard time finding good tutorials because some of them would not go into details with their examples (for instance showing a piece of code that works but not explaing why exactly, or making an example with just a few lines instead of at a larger scale), he told me that I should not try to understand them completely, because there are times where a code will just do what it does and I should leave it at that (he gave me the example that when doing calculus, for instance, we use formulas that we don't know how they were conceived or how they work, we just know that they do and we use them).

And this bothered me because I have always been told that it's really important to understand your code, and that just copying and pasting without knowing HOW it works is practically a sin; which is why I always take my time in understanding something before moving forward with it. And it's not like I'm trying to understand how a particular class works at an assembly language level, I just want to know why a set of instructions does the trick, and why another one doesn't, or why both do and under what circumstances. But my boss tells me that I will end up wasting time obsessing over these little details, and I should just skip it. So my question is, is he right? Is it okay to understand your code only to a certain extent and keep going, and have I only been obsessing over little things that don't matter?


问:
Scrum Daily meeting: Punctuality over Full team presence?
My understanding is that a Daily Scrum meeting should be very quick, hosted in a friendly way and that it requires all the team members present. Because it is objective is to have everyone up to date with what everybody else is doing.

I like Scrum Daily Meetings that are held like that.

In my latest project our Daily Scrums are more like a Status Update meeting. Although the position is that we are holding Scrums and practicing proper Agile.

We are a distributed team, in 2 different countries, and the people that is in the same Country are not in the same office. As consequence we have virtual Scrums.

The problem is that our meetings always start on time, many people calls before the actual start time, so they actually start at the very first second of the meeting. Without any tolerance for small delays.

For example the last time we were on the phone and the person coordinating the meeting checked if everyone was on, and we said one of our team members was not on yet but he was calling. And I was told to start sharing without waiting for my team member.

Also everyone has a lot of meetings, and sometimes they are back to back with the Scrum meeting, so it is understandable if they arrive during the first or second minute of the meeting.

Is that the normal for teams practicing Daily Scrums? It is the first time that happens to me.

I can not find any bibliography directly about it. Although the presence of all team members is stressed, it is stressed also that the meetings should always start at the same time. But I imagine there can be a small delay tolerance.

I even read on a blog someone suggesting that the Scrum Master can place penalties if someone arrives "5 seconds" late. I thought the Scrums were supposed to be friendly, and having a penalty like that seems counter productive.

What is the recommended approach in a situation like this?

答:
If you wait for people, it teaches them it's OK to be late. If you start on the minute, people will be taught they need to be there on time if they want to participate. Programming is a professional activity that requires at least a modicum of discipline. </p>

<p>That being said, the point of the daily standup is to discuss what the team did yesterday, what they are doing today, and to make everyone aware of roadblocks. The scheduled time should be "first thing in the morning when everyone is available", not necessarily a specific time on the clock. The end goal is to work together as a team, not follow strict rules. If your team is very new to agile, sticking to the clock is good way to build your team skills. If you're a mature team, do what works for your team. </p>

Body:
If you wait for people, it teaches them it's OK to be late. If you start on the minute, people will be taught they need to be there on time if they want to participate. Programming is a professional activity that requires at least a modicum of discipline.

That being said, the point of the daily standup is to discuss what the team did yesterday, what they are doing today, and to make everyone aware of roadblocks. The scheduled time should be "first thing in the morning when everyone is available", not necessarily a specific time on the clock. The end goal is to work together as a team, not follow strict rules. If your team is very new to agile, sticking to the clock is good way to build your team skills. If you're a mature team, do what works for your team.


答:
I think the answer is context.

One of the most powerful techniques for managing code complexity—which is the real job of a software engineer, in my mind—is abstraction. An electrical engineer does not have to reprove Maxwell's equations in order to develop a new product, and I do not need to know anything about a car in order to use a steering wheel. Both are important abstractions because they allow us to intuit and use things without understanding them. This in turn allows us to build bigger abstractions.

As an aside, because abstraction is so important I think it is sometimes good to even enforce it with other developers. For example, in my office we sometimes have one developer write the unit tests for a block of code before the block of code is written by a second developer. It enforces the idea of simple interfaces and clear abstractions.

That said, abstraction is no excuse for not understanding how code works when it matters that you know how it works. Refactoring code is an obvious scenario in which the implementation details matter quite a bit. I don't need to know how a car works in order to drive it, but a mechanical engineer and a mechanic should both understand how a car works, arguably in different ways.

As a second aside, one of my first lessons on the job was to never touch code I didn't truly understand. For example, I was once working on a new feature and noticed another line of code in the module that didn't make sense, so I "fixed" it and then released a bug. That taught me a pretty big lesson, which is to admit when I don't readily understand a piece of code and to recognize that good and complex and nontrivial code can be non-obvious. I'm pretty new to software development, but I have found the idea that "good code is easy to read" to be an insidious one that no software developer I know puts into real practice. Sure, don't write obscure or bad code, but hard problems often require complex code. Don't be upset if it takes you time to understand things. My favorite Feynman quote is, "But it is not complicated; there's just a lot of it."

So when do you abstract and when do you take apart the Swiss clock? I suppose it depends on when you're wearing the watch and when you're building it. My own opinion is that the best people in any field are T-shaped, meaning they understand their work in a larger context—something that is only achieved through abstraction—but also know what they need to know deeply.


问:
How should I create object after database insert PHP
I have just been working on a new project and doing things the same way I have for years now. However for the first time, I am constantly thinking about scalability and performance of both the application code and the database.

So in times past, I have been more than happy to insert a new row, then grab the last_insert_id and then translate this into an object by calling the getObjectById(id) method from within whichever persistence framework is in use. I find this is good practice because it will ensure that you are returning exactly what is stored in the database and any error will be picked up there and then, rather than next time you ask for the object.

The other way, since you have all the data required to build the object right in front of you, is to simply create the new object from the supplied data and simply set the objectId once the statement is verified as complete. I have always felt as though there are still some unknowns which can occur, and if there are any triggers in the database which transform the data in any way, then you will have a mismatch in state which is bad.

However, thinking purely about performance, I am obviously taking a hit by running multiple queries to create the object (insert plus select) which adds overhead and I would like to make the application both as fast and secure as possible.

My question is, what would be the most appropriate approach for performance, scalability, security and then for the trade-off between the 3?

答:
You have a performance problem when your system does not meet its functional requirements.

So unless your users are complaining or you fail to meet a Service Level Agreement you do not have a performance problem.

In your case its very unlikely that the extra "insert"/"select" would involve an overhead which would be noticeable to an end user, or measurable in terms of the overall system performance.

After all you will probably insert the data at some point anyway, and invoking a select on an object you inserted less than a millisecond ago will not involve any database I/O. In fact you will not get any delays due to IO activity until you "COMMIT" your work. Inserting earlier will give the database a chance to log your change before you commit so your process  might actually be faster than the alternative.

"If it ain't broke don't fix it "


问:
foreach in list or foreach in list.where
I don't know what to call this question.

This is my example:

```<code>foreach (var item in lstItem.Where(item => stock.ItemCode == item.ItemCode))
{
     stock.ItemName = item.ItemName;
     stock.ItemUnitName = item.ItemUnitName;
     stock.BrandName = item.BrandName;
     stock.FamilyName = item.FamilyName;
}
</code>```

or

```<code>// Assume list has items
var list = lstItem.Where(item => stock.ItemCode == item.ItemCode);
foreach (var item in list)
{
     stock.ItemName = item.ItemName;
     stock.ItemUnitName = item.ItemUnitName;
     stock.BrandName = item.BrandName;
     stock.FamilyName = item.FamilyName;
}
</code>```

Which one is better?

答:
There are two interesting questions wrapped into one here.

First, is it better to break up more complex expressions into simpler ones, and perhaps take the opportunity to give the variables helpful names?

This is often a really good idea, but in this case the code might better read as:

```<code>var wanted_items = lstItem.Where(item => stock.ItemCode == item.ItemCode);
foreach (var item in wanted_items)
</code>```

Second, are there performance issues in breaking up expressions like this?

Not so easy to answer, in the general case. In most languages a construct of this kind would lead to all items of the list being processed to filter out those required, and then individual items processed again to apply the assignment. If there is only one match then the first pass will (on average) examine twice as many items as needed.

But this is C# and Linq, so now the list will be either an iterator or it will be translated into SQL, both of which optimise processing, to a greater or lesser extent. In this particular case the performance will be (should be) exactly the same whether the expression is split or not, but there are closely related constructs in which splitting the expression like this can crystallise a particular path for execution and have quite severe performance impact.

Ultimately, you should always write the most readable code you can using the best possible algorithms and best possible use of underlying framework libraries. If you then have concerns for performance, you need to benchmark and measure before even thinking about changing the code.

Body:
There are two interesting questions wrapped into one here.

First, is it better to break up more complex expressions into simpler ones, and perhaps take the opportunity to give the variables helpful names?

This is often a really good idea, but in this case the code might better read as:

var wanted_items = lstItem.Where(item => stock.ItemCode == item.ItemCode);
foreach (var item in wanted_items)

Second, are there performance issues in breaking up expressions like this?

Not so easy to answer, in the general case. In most languages a construct of this kind would lead to all items of the list being processed to filter out those required, and then individual items processed again to apply the assignment. If there is only one match then the first pass will (on average) examine twice as many items as needed.

But this is C# and Linq, so now the list will be either an iterator or it will be translated into SQL, both of which optimise processing, to a greater or lesser extent. In this particular case the performance will be (should be) exactly the same whether the expression is split or not, but there are closely related constructs in which splitting the expression like this can crystallise a particular path for execution and have quite severe performance impact.

Ultimately, you should always write the most readable code you can using the best possible algorithms and best possible use of underlying framework libraries. If you then have concerns for performance, you need to benchmark and measure before even thinking about changing the code.


问:
Choice between 1-dimensional and 2-dimensional array
I'm implementing the Chessboard class to represent the chessboard. I've to implement the transformations (reflections and rotations) on the chess board possible.

The possible transformations includes the combination of:

 1. Vertical Reflection
 2. Horizontal Reflection
 3. Diagonal Reflection
```

<p>Thus, we've <strong>8</strong> possible transformations for chess board.</p>

<p>There are <strong>64</strong> squares on the Chessboard numbered <strong>[0..63]</strong>.</p>

<p>Thus, to represent the total resulting values after the transformations is <strong>8*64</strong> (No.of Transformations * Chessboard_Size).</p>

<p>There are two fundamental ways to represent the <strong>transformed_board</strong> using Arrays:</p>

<pre class="lang-none prettyprint-override"><code>One-Dimensional Array with transformed_board[8*64]
Two-Dimensional Array with transformed_board[8][64]
</code>```

Questions:

Which approach is better?

What are the pros and cons of each approach?

How will effect the performance with respect to time factor?

答:
1 dimension or 2 dimension arrays actually have same data structure in memory.

The elements will be in contiguous memory block. So, performance wise, it will be the same, if you use same indexing.

2 dimensions is probably easier to read, and manipulate (easier to write board[1][3] than board[1*64 + 3])


答:
Both of your examples are functionally equivalent.

The reason for this is that an enumeration is not evaluated until it is absolutely needed.  Looking at your second example:

```<code>var list = lstItem.Where(item => stock.ItemCode == item.ItemCode);
foreach (var item in list)
{
 stock.ItemName = item.ItemName;
 stock.ItemUnitName = item.ItemUnitName;
 stock.BrandName = item.BrandName;
 stock.FamilyName = item.FamilyName;
}
</code>```

What happens is that list is not a list.  Rather it is an enumerator of lstItem with the Where condition on it.  That enumerator gets evaluated once for each iteration of the foreach loop.

The reason for this is that this will allow for maximum performance if the foreach loop is exited early.  The enumerator might have to do some complex calculations when it is run and so short circuiting out can, in some cases, result in much faster code.

It's best not to think of var list = lstItem.Where(item => stock.ItemCode == item.ItemCode); as giving you a list.  Rather, it's giving you an object which will return the next item when it's asked until it runs out of items.  Theoretically it could go on forever and it's entirely possible to write an enumerator that cycles around on itself.

Personally, I prefer your first code snippet as it requires less reading.  Note that when the compiler optimises your code, the temporary list variable will get optimised away unless it's used later on.

Title: foreach in list or foreach in list.where

Body:
I don't know what to call this question.

This is my example:

```<code>foreach (var item in lstItem.Where(item => stock.ItemCode == item.ItemCode))
{
     stock.ItemName = item.ItemName;
     stock.ItemUnitName = item.ItemUnitName;
     stock.BrandName = item.BrandName;
     stock.FamilyName = item.FamilyName;
}
</code>```

or

```<code>// Assume list has items
var list = lstItem.Where(item => stock.ItemCode == item.ItemCode);
foreach (var item in list)
{
     stock.ItemName = item.ItemName;
     stock.ItemUnitName = item.ItemUnitName;
     stock.BrandName = item.BrandName;
     stock.FamilyName = item.FamilyName;
}
</code>```

Which one is better?

Body:
Both of your examples are functionally equivalent.

The reason for this is that an enumeration is not evaluated until it is absolutely needed.  Looking at your second example:

var list = lstItem.Where(item => stock.ItemCode == item.ItemCode);
foreach (var item in list)
{
 stock.ItemName = item.ItemName;
 stock.ItemUnitName = item.ItemUnitName;
 stock.BrandName = item.BrandName;
 stock.FamilyName = item.FamilyName;
}

What happens is that list is not a list.  Rather it is an enumerator of lstItem with the Where condition on it.  That enumerator gets evaluated once for each iteration of the foreach loop.

The reason for this is that this will allow for maximum performance if the foreach loop is exited early.  The enumerator might have to do some complex calculations when it is run and so short circuiting out can, in some cases, result in much faster code.

It's best not to think of var list = lstItem.Where(item => stock.ItemCode == item.ItemCode); as giving you a list.  Rather, it's giving you an object which will return the next item when it's asked until it runs out of items.  Theoretically it could go on forever and it's entirely possible to write an enumerator that cycles around on itself.

Personally, I prefer your first code snippet as it requires less reading.  Note that when the compiler optimises your code, the temporary list variable will get optimised away unless it's used later on.


问:
Shouldn't Android's TextView.getText() return String instead of possibly mutable CharSequence?
I've just spent hours debugging some code because I forgot (actually never considered it) that TextView.getText() returns CharSequence that may be in fact a mutable class...

Shouldn't it return (immutable) String instead? I mean I can't imagine a situation when you want to share a state with a text field, at least not by default.

Isn't that something that can be objectively called a design mistake in a library?

答:
Well, most immediate justification for this design decision can be found in method javadocs:

you can cast the return value from this method to Spannable or Editable...

Casts mentioned above are possible only because Spannable and Editable implement CharSequence; String wouldn't allow for that.

For a deeper understanding of the design motivation, take a look at class javadocs:

TextView is a complete text editor...

Above means that TextView object is designed to support frequent changes of its content.

If getText would return immutable String, this would mean a high chance of creating multiple objects while working with TextView. This in turn would go against general approach preferred in Android and outlined in Avoid Creating Unnecessary Objects guidelines:

Object creation is never free. A generational garbage collector with per-thread allocation pools for temporary objects can make allocation cheaper, but allocating memory is always more expensive than not allocating memory.

As you allocate more objects in your app, you will force a periodic garbage collection, creating little "hiccups" in the user experience. The concurrent garbage collector introduced in Android 2.3 helps, but unnecessary work should always be avoided.

Thus, you should avoid creating object instances you don't need to...

For the sake of completeness, it is worth noting that reasoning in above guidance implicitly involves mobile applications specifics.

In particular, one can imagine desktop or server platforms having more sophisticated garbage collection, allowing developers to design immutable objects at their discretion, without worrying much about performance implications.

At mobile platforms, API designers have to take into account resource limitations of mobile devices (memory, processor, power consumption etc) that can block implementation of theoretically better approaches.


问:
Use of MIT-Licensed OSS with GPL Dependencies
I have been assigned to audit third-party dependencies for one of my company's products to make sure we aren't in danger of running afoul of any licenses. This is probably a job for a lawyer, but such is life when you work at a small company.

At my company, we are using CS2J, an open-source project, to translate C# to Java. CS2J is itself MIT-licensed, and we use it in two ways. First, we use it as an internal tool to translate our source code from one language to another. Second, it comes with a support library (a jar file) that the translated files reference. We package this support library with our main distribution.

It turns out that the support library depends on JavaMail, a GPL-licensed product. (There's technically another license option, but it has the same copyleft clause.) I believe at one time it had something other than a GPL license, but that is no longer the case.

We had been planning on to ship the support library (CS2JSupport.jar) and JavaMail (mail.jar) as its dependency. I have a few questions:

Is CS2J allowed to be licensed under the MIT license in the first place if it's distributed with a GPL dependency?

If we are shipping mail.jar as a dependency of our dependency, does that mean the copyleft applies to us? Or does it just apply to CS2J?

We have a close relationship with the CS2J author. If we asked the CS2J author to make available a CS2JSupport.jar that had mail.jar included inside the jar, then is CS2JSupport simply a derivative work of mail.jar? And since the derivative work is covered under the MIT license instead of the GPL license, would that exempt my company from the copyleft even if we wouldn't be exempt in the situation described in #2?

答:
As Ross Patterson notes in his answer, the JavaMail library is not simply GPL licensed, but GPLv2 with Classpath exception. This is an important distinction, because it makes a world of difference for the answers to your questions.

The Classpath exception to the GPLv2 license effectively restricts the copyleft nature of the GPLv2 to the JavaMail library itself (in a way similar to the LGPL does).

To answer the specific questions:

As the classpath exception restricts the GPL terms to apply only to the JavaMail library, there is no problem in having a non-GPL work (library or program, in this case an MIT-licensed library) depend on it.

Even if CS2J depends on a library that uses the regular GPL license, the CS2J sources themselves can have a different license. The only 'difficulty' then is that the license must be compatible with the GPL, because the terms and conditions of the GPL would have extended to CS2J.

Due to the Classpath exception, the copyleft of JavaMail is contained within JavaMail itself. Without that exception, the copyleft would have extended also to your software.

Requesting the authors of CS2J to physically include JavaMail in their CS2JSupport.jar would make the CS2JSupport library a derived work from JavaMail that must be licensed under the GPL (with or without the Classpath exception), so that would not give you a route for exemption from the GPL copyleft terms. At best, the situation remains as is (your software depends on a GPL library with classpath exception) and at worse you suddenly have a dependency on a full GPL licensed library and must open up your own software as well.


问:
What's so bad about pointers in C++?
To continue the discussion in Why are pointers not recommended when coding with C++?

Suppose you have a class that encapsulates objects which need some initialisation to be valid - like a network socket.

```<code>// Blah manages some data and transmits it over a socket
class socket; // forward declaration, so nice weak linkage.

class blah
{
  ... stuff
  TcpSocket *socket;
}

~blah {
   // TcpSocket dtor handles disconnect
   delete socket; // or better, wrap it in a smart pointer
}
</code>```

The ctor ensures that socket is marked NULL, then later in the code when I have the information to initialise the object.

```<code>// initialising blah
if ( !socket ) {
   // I know socket hasn't been created/connected
   // create it in a known initialised state and handle any errors
   // RAII is a good thing !
   socket = new TcpSocket(ip,port);
}

// and when i actually need to use it
if (socket) {
   // if socket exists then it must be connected and valid
}
</code>```

This seems better than having the socket on the stack, having it created in some 'pending' state at program start and then having to continually check some isOK() or isConnected() function before every use.

Additionally if TcpSocket ctor throws an exception it's a lot easier to handle at the point a Tcp connection is made rather than at program start.

Obviously the socket is just an example, but I'm having a hard time thinking of when an encapsulated object with any sort of internal state shouldn't be created and initialised with new.

答:
The pointer is definitely not a bad thing, it gives you direct access to the memory, for the best performance.

Sometimes it is difficult to track the lifetime, when the pointer needs to be passed around classes, this is where the smart pointer can help. If you can sacrifice the little performance impact, then yes, use smart pointer if it is available.

The bad thing about using smart pointer is the dependency of the header file for the class. With raw pointer, you can just forward declare the class/struct, and have a cleaner dependency during compilation.

You must also ensure the smart pointer you use is thread-safe in case of multi-threading application.

If your class is simple enough, I would say stick with regular pointer than a smart one.

Title: What's so bad about pointers in C++?


问:
Unique ID algorithm
I've got a route that contains objects. Each one has value 0 or 1. I need unique route ID which will identify any objects order. Currently I'm doing it using binary number that is converted to decimal (see picture).

The problem is, that amount of objects in route is up to 15. So, decimal number will be very big (up to 32767) with many values, that will never be used.

How to convert that number, to another unique value, but much smaller (<255)? I need to do that, only by using simple arithmetical operators (+,-,*,div).

答:
It's impossible because each route may be reached (or not?).
You have as many routes as 2^15

Maybe You have to consider fact that some of them will never appears (is it true?).
So You can number only this of them which can be reached. This will decrease Your number of ways.

To decrease number of routes to be from 0 to 255 You have to eliminate about 2^7 routes.
This may mean that seven objects will have always the same value (0 or 1).

For example

ffff1101fff10111

ffff0101fff00101

ffff0111fff10100

etc...

Title: Unique ID algorithm


答:
You have the equivalent of 15 bits of information that you must save.  The largest binary number represented by 15 bits is 32767, and it is by no means no coincidence that this is also the maximum number of possible combinations (-1).

You cannot reduce this number without first providing some sort of simplification rule (i.e. the number must be an odd number, the number must be a palindrome, etc.).  Otherwise any combination of the 15 bits is allowed.

While you may perform mathematical operations to simplify this number just the same, you'd be losing information in the process, and hence it would be one-directional (you could not figure out the original number by reversing the mathematical operation(s)).

Title: Unique ID algorithm

Body:
I've got a route that contains objects. Each one has value 0 or 1. I need unique route ID which will identify any objects order. Currently I'm doing it using binary number that is converted to decimal (see picture).

The problem is, that amount of objects in route is up to 15. So, decimal number will be very big (up to 32767) with many values, that will never be used.

How to convert that number, to another unique value, but much smaller (<255)? I need to do that, only by using simple arithmetical operators (+,-,*,div).


问:
How to show to management that unit testing is cheaper in the long run than manual testing?
In the company I work for there is a requirement that all the code should be covered by a test of any kind because they want to have as few user reported defects as possible.

With this is mind I decided to put a policy that the code should be unit tested to C0 (100% coverage of each line, not each condition).

Now others say that this is more expensive that doing manual test.

Intuitively I would say that this is wrong as each time you do a change you have to retest everything manually and this is probably more effort than just executing the tests and updating the ones that need to be updated but I don't find a way to justify myself with numbers, papers or other information.

Can you give me some good points to proof my approach to the people I report to?

EDIT: Thanks to all that helped on the question. I see that there were some key points missing on it:

This is a new product that we started developing one year ago with testing in mind so we use DI everywhere and everything is prepared for testing.

We already have a commercial product that allows us to reach a 100% coverage as we can mock almost everything, including .Net classes so we can truly isolate classes (JustMock).

We have tools to calculate testing coverage.

We are not removing testers and manual testing. We are removing manual testing done by developers. We have a separate SQ team but management wants that the number of bugs that reach the SQ team is as small as possible so developers must reach 100% coverage by any mean before delivering code to the SQ team. So what I did was to replace developer manual testing with automated testing (unit and integration tests) and that's what management wants to revert.

The question is not the same as the "duplicated" one as I already have a 100% coverage requirement.

答:
Whilst there is merit in having unit tests, most people take it too far - firstly trying for 100% unit test coverage is trying to turn your company into this. You need a more pragmatic approach,especially as unit testing does not guarantee your application is bug-free, you still need plenty of integration testing to prove all the isolated bits work together.

Manual testing is best replaced with automated integration test tools. There are plenty around (eg Cucumber or SpecFlow) that should be much more easily recognised as something to replace the manual testing without going into the maintenance nightmare of 100% unit test coverage.

Unit testing is often abused, 100% unit test coverage is definitely a bad smell.


答:
First, @JamesAnderson's answer is pointing out to really good points. I also think that you're unnecessarily paranoid about the performance at this point.

Talking about your question, I usually do it differently. Instead of inserting the data into the database and then loading it back again and creating an instance of a class base on that data, I usually create the instance of the class first, and then I use a method like $obj->save() to insert the data into the database; but doing so is really depends on how Robust you have designed your Database and Classes.

For example:

Have you implemented a proper encapsulation? Specially a solid setter for fields that should be stored in the database? Or are you exposing any important class properties via public accessor in which they could be modified out of control?

Does your database tables accept NULL values when it's not necessary, instead of failing the operation? Or did you set up some Default Values for some fields that might not be really wise and possibly problematic in the future?

The above list could goes much longer, but the point is that if you could trust the data that you have within your objects, and also if you could trust your database that it will insert the correct data or it will fail in any other cases -- then no InsertID will be returned that is a sign of failure; If you meet these points in your design and implementation, then you won't need to insert the data and then load it again to make sure about the integrity of data.

Title: How should I create object after database insert PHP

Body:
I have just been working on a new project and doing things the same way I have for years now. However for the first time, I am constantly thinking about scalability and performance of both the application code and the database.

So in times past, I have been more than happy to insert a new row, then grab the last_insert_id and then translate this into an object by calling the getObjectById(id) method from within whichever persistence framework is in use. I find this is good practice because it will ensure that you are returning exactly what is stored in the database and any error will be picked up there and then, rather than next time you ask for the object.

The other way, since you have all the data required to build the object right in front of you, is to simply create the new object from the supplied data and simply set the objectId once the statement is verified as complete. I have always felt as though there are still some unknowns which can occur, and if there are any triggers in the database which transform the data in any way, then you will have a mismatch in state which is bad.

However, thinking purely about performance, I am obviously taking a hit by running multiple queries to create the object (insert plus select) which adds overhead and I would like to make the application both as fast and secure as possible.

My question is, what would be the most appropriate approach for performance, scalability, security and then for the trade-off between the 3?


问:
Programmatically syncing with remote servers
My application generates text files that need to be synced with remote servers, which may be windows or linux. Sync has to happen without user's intervention.

I tried with rsync but windows doesn't come with rsync by default. Also it is not possible to supply password in the command line for rsync.

Currently I'm going with ftp. But that seems like an inefficient way.

Is there a way to rsync without user intervention? What are the ways to sync with a remote server programmatically? App is on nodejs.

答:
I think you should accomplish two tasks:

watch source filesystem for change. This could be done by either cron job (task scheduler for windows) to check for changes, FTP watcher that checks changes in FTP server. I am sure there are other options too.

You have to copy source files to target servers. This you can achieve in many ways trough ftp or ssh or even upload files through http.

Your best setup depends on what is already installed there on servers or what is easier for you to set up. Also do you need to sync back if files have changes in remote servers.


答:
Assumed, you will travel only a certain subset of all possible routes ever.

In that case, you could use a mapping between  the routebits and a incremented numerical id. You will have to store that mapping somewhere, but this way every path used gets an unique id assigned, which can be used to refer to it later.

I'm not so sure if this is an efficient way to do it, but you didn't ask for that aspect.

Title: Unique ID algorithm


问:
Have objects delivered in terms of code reuse?
I have often heard it said that objects have not delivered in terms of code reuse. Do you agree? If you believe that they haven't, why not?</p>

答: Objects enable code re-sue but as such is not the most technique for that. I think code re-use is promoted through object related techniques such as inheritance, polymorphism, overloading, and templates.</p>

ContentLicense: CC BY-SA 2.5


问:
MVC: my controller seems useless half of the time. Is this a problem?
Often when I design a program with MVC, the controller is useless half of the time.

What I mean is this: something happens on the view (e.g. a button click). The view then notifies the controller. The controller then directly delegates to the model and does nothing else because it has nothing to do.

For example:

User presses button 'Color Blue' > view tells controller controller.colorBlue() > controller tells model model.colorBlue() > model colors something blue.

In this example, the controller seems useless. It adds nothing. The view might as well have talked straight to the model.

The other half of the time, however, the controller does do some kind of mediation between the view and model.

My question is this: how common is this in MVC structures? Is it reasonable that half the time my controller seems unnecessary? Or is this a problem? Is this common? How should I approach this?

If my question isn't clear enough, please say so.

答:
While coding you could think this way:

Will I be able to change view to something else (console, service) or you same controller for different view?

Will I be able to change model to handle different database or write to some external service?

In your case it seems you are putting domain logic into model and that would cause you problems if you want to change it: you will have to copy methods like "model.colorBlue" to new model.

And what would happen if definition of "blue" changes? You will have to change it 2 models. Also in controller you should not write directly into your database, but as Lie Ryan pointed you should use model.setColor.

Same with views. If you start putting logic or validation into view then if you want to change view you will have to copy all that functionality.


问:
How do languages with Maybe types instead of nulls handle edge conditions?
Eric Lippert made a very interesting point in his discussion of why C# uses a null rather than a Maybe<T> type:

Consistency of the type system is important; can we always know that a non-nullable reference is never under any circumstances observed to be invalid? What about in the constructor of an object with a non-nullable field of reference type? What about in the finalizer of such an object, where the object is finalized because the code that was supposed to fill in the reference threw an exception? A type system that lies to you about its guarantees is dangerous.

That was a bit of an eye-opener.  The concepts involved interest me, and I've done some playing around with compilers and type systems, but I never thought about that scenario.  How do languages that have a Maybe type instead of a null handle edge cases such as initialization and error recovery, in which a supposedly guaranteed non-null reference is not, in fact, in a valid state?

答:
I think your quote is a straw man argument.

Modern languages today (including C#), guarantee you that the constructor either fully completes or it does not.

If there is an exception in the constructor and the object is left partially uninitialized, having null or Maybe::none for uninitialized state makes no real difference in the destructor code.

You will just have to deal with it either way.
When there is external resources to manage, you must manage those explicitly any way.
Languages and libraries can help, but you will have to put some thought into this.

Btw: In C#, null value is pretty much equivalent to Maybe::none. You can assign null only to variables and object members that on a type level are declared as nullable:

```<code>String? nullableString = getOptionalString();
Nullable<String> maybe = nullableString; // This is equivalent
</code>```

This is in no way different than the following snippet:

```<code>Maybe<String> optionalString = getOptionalString();
</code>```

So in conclusion, I do not see how nullability is in any way opposite to Maybe types. I would even suggest that C# has sneaked in it's own Maybe type and called it Nullable<T>.

With extension methods, it is even easy to get the clean-up of the Nullable to follow the monadic pattern:

```<code>Resource? resource = initializationThatMayFail();
...
resource.ifExists( Resource r -> r.cleanup() );
</code>```

Body:
I think your quote is a straw man argument.

Modern languages today (including C#), guarantee you that the constructor either fully completes or it does not.

If there is an exception in the constructor and the object is left partially uninitialized, having null or Maybe::none for uninitialized state makes no real difference in the destructor code.

You will just have to deal with it either way.
When there is external resources to manage, you must manage those explicitly any way.
Languages and libraries can help, but you will have to put some thought into this.

Btw: In C#, null value is pretty much equivalent to Maybe::none. You can assign null only to variables and object members that on a type level are declared as nullable:

String? nullableString = getOptionalString();
Nullable<String> maybe = nullableString; // This is equivalent

This is in no way different than the following snippet:

Maybe<String> optionalString = getOptionalString();

So in conclusion, I do not see how nullability is in any way opposite to Maybe types. I would even suggest that C# has sneaked in it's own Maybe type and called it Nullable<T>.

With extension methods, it is even easy to get the clean-up of the Nullable to follow the monadic pattern:

Resource? resource = initializationThatMayFail();
...
resource.ifExists( Resource r -> r.cleanup() );


问:
Unit-based architecture
This is probably a damn fool question, for which I apologise, but I can't seem to get the google syntax right to find an answer.

Imagine a Property, like this:

```<code>private int _type
public int Type
{
    get { return _type; }
    set
    {
        _type = value;
        //raise an event in your chosen language or tech
        CallAFunction();
    }
}
</code>```

Now, imagine that CallAFunction does some sort of fairly serious heavy lifting in your application, interacting with the database via a repository.

It doesn't seem unreasonable to want a unit test for this, to make absolutely sure that Type gets set to whatever you put in and to check that doing so raises the expected event.

However, setting the property with a test will call CallAFunction() which means that you're no longer really testing a "unit" of code as such, and perhaps more importantly that a very simple test for this very simple property might well require more elaborate preparation, including repository mocking, which seems huge overkill.

In some cases you could split these apart by having CallAFunction raised via the event. But that's not always the case (I'm using WPF, and the events bubble up to non-testable XAML).

What's the best way to split these two interdependent things apart?

答:
There are two issues intermingled here.

"Is it OK to have hidden logic in a setter?" This is asked from time to time, and there is no accepted universal answer. It depends on whether the additional thing you do is really an intrinsic part of that property or not.

"How do I test a method with an expensive external dependency?"  Here the general opinion is that if your method does stuff via a collaborator, you should either mock that collaborator out, or use it normally while making sure that this does not make your unit test unacceptably slow.

Title: Unit-based architecture


问:
Why would Square inheriting from Rectangle be problematic if we override the SetWidth and SetHeight methods?
If a Square is a type of Rectangle, than why can't a Square inherit from a Rectangle? Or why is it a bad design?

I have heard people say:

If you made Square derive from Rectangle, then a Square should be
  usable anywhere you expect a rectangle

What is the problem here? And why would Square be usable anywhere you expect a rectangle? It would only be usable if we create the Square object, and if we override the SetWidth and SetHeight methods for Square than why would there be any issue?

If you had SetWidth and SetHeight methods on your Rectangle base class
  and if your Rectangle reference pointed to a Square, then SetWidth and
  SetHeight don't make sense because setting one would change the
  other to match it. In this case Square fails the Liskov Substitution
  Test with Rectangle and the abstraction of having Square inherit from
  Rectangle is a bad one.

Can someone explain the above arguments? Again, if we over-ride SetWidth and SetHeight methods in Square, wouldn't it resolve this issue?

I have also heard/read:

The real issue is that we are not modeling rectangles, but rather
  "reshapable rectangles" i.e., rectangles whose width or height can be
  modified after creation (and we still consider it to be the same
  object). If we look at the rectangle class in this way, it is clear
  that a square is not a "reshapable rectangle", because a square cannot
  be reshaped and still be a square (in general). Mathematically, we
  don't see the problem because mutability doesn't even make sense in a
  mathematical context

Here I believe "re-sizeable" is the correct term. Rectangles are "re-sizeable" and so are squares. Am I missing something in the above argument? A square can be re-sized like any rectangle.

答:
If a Square is a type of Rectangle than why cant a Square inherit from a Rectangle? Or why is it a bad design?

First things first, ask yourself why you think a square is a rectangle.

Of course most people learnt that in primary school, and it would seem obvious. A rectangle is a 4 sided shape with 90 degree angles, and a square fulfils all those properties. So isn't a square a rectangle?

The thing though is that it all depends on what is your initial criteria for grouping objects, what context are you looking at these objects. In geometry shapes are classified based on the properties of their points, lines and angels.

So before you even say "a square is a type of rectangle" you first have to ask yourself, is this based on criteria I care about.

In the vast majority of cases it isn't going to be what you care about at all. The majority of systems that model shapes, such as GUIs, graphics and video games, are not primarily concerned with the geometric grouping of an object but it is behaviour. Have you ever worked on a system that it mattered that a square was a type of rectangle in the geometric sense. What would that even give you, knowing that it has 4 sides and 90 degree angles?

You are not modelling a static system, you are modelling a dynamic system where things are going to happen (shapes are going to be created, destroyed, altered, drawn etc). In this context you care about shared behaviour between objects, because your primary concern is what you can do with a shape, what rules have to be maintained to still have a coherent system.

In this context a square is most definitely not a rectangle, because the rules that govern how the square can be altered are not the same as the rectangle. So they are not the same type of thing.

In which case don't model them as such. Why would you? It gains you nothing other than an unnecessary restriction.

It would only be usable if we create the Square object, and if we override the SetWidth and SetHeight methods for Square than why would there be any issue?

If you do that though you are practically stating in code that they are not the same thing. Your code would be saying a square behaves this way and a rectangle behaves that way but they are still the same.

They clearly aren't the same in the context that you care about because you just defined two different behaviours. So why pretend they are the same if they are only similar in a context you don't care about?

This highlights a significant problem when developers come to a domain that they wish to model. It is so important to clarify what context you are interested in before you start thinking about the objects in the domain. What aspect are you interested in. Thousands of years ago the Greeks cared about the shared properties of the lines and angels of shapes, and grouped them based on these. That doesn't mean you are forced to continue that grouping if it isn't what you care about (which in 99% of the time modelling in software you won't care about).

A lot of the answers to this question focus on sub-typing being about grouping behaviour 'cause them the rules.

But it is so important to understand that you aren't doing this just to follow the rules. You are doing this because in the vast majority of cases this is what you actually care about as well. You don't care if a square and rectangle share the same internal angels. You care about what they can do while still being squares and rectangles. You care about the behaviour of the objects because you are modelling a system that is focused on changing the system based on the rules of the behaviour of the objects.


问:
How to manage version control company wide?
Are there any industry standards or best practises on how to manage a rapidly changing code base?

The types of applications I am developing always have a custom aspect to them. So there will always be some code written which is client specific for every project.

The method we are using now is as follows:

Several 'CORE' projects exist in isolation from one another, each core project is a class library which is capable of running on its own, or with dependencies on other core modules.

All of these core modules are documented (Sandcastle) and NuGet packages created for them, which are served up via a private NuGet feed.

When a customer purchases the software we create a customer specific project which implements the bespoke code that they require, and pulls in the NuGet packages from the core libs as needed. The build of this project is what is provided to the customer, and each customer project has it's own Git repository.

This has worked fine for a year or so, but I feel that as we add features to the core libraries the number of nuget packages is growing quite quickly.

Is there a better method of organising code, whilst making sure there are not seperate version of the same code lying around?

I know in this stackoverflow post it states that:

Google manages to keep the source code of all its projects, over 2000, in a single code trunk containing hundreds of millions of code lines, with more than 5,000 developers accessing the same repository.

But this seems like it produce problems for us, due to having bespoke deployments.

Any ideas or comments on what I am doing wrong?

Edit

The problems I foresee going with the google way are mainly to do with release management and build issues. We use continuous integration, so that every commit a build will be triggered and test automatically run. If we use one all encompassing repo I am not sure what effect this will have on the build and test servers. Will it have to build every customers project?

Or would there be a branch per customer? In which case is this any better than a repo per customer?

答:
This is more a code management issue. At the heart of it, you need to make a distinction between common code and bespoke modifications. Once you can answer that, the SCM issue will fall into place easily.

For example, you could have all your application setup to use a lot of configuration. For all customer features, you add a config option and implement the feature in the common codebase. A customer then purchases a single application and a specially created config file (or DB or whatever).

Alternatively, you have a common codebase that you extend with inherited classes for each customer feature. The SCM would be used to checkout the common, unchanging codebase and then bring in the new files to add to the build for that customer.

Or you can try branching off a central trunk and editing the code as needed for each customer, with any fixes to the common trunk being merged into each and every customer branch. This last one is easiest for the devs, but a real pain for the build manager.

I'd say you're probably doing things right with a large set of common libraries, but maybe your common code is just too fine-grained. Try combining them into fewer libraries, it doesn't matter if the customer has extra that they never use in a single package. You might be able to get away with a single Nuget package that pulls in a single library with all common code in it, for example.


问:
Should POCO domain classes contain collections?
The question title is not good, but I couldn't think of a way to word it better.

I am used to develop using POCO classes in my projects, that is, domain objects contain absolutely no logic, only data.

I am wondering which is the best approach when dealing with class relationships - to put a collection inside the class or to request it later.

For example, consider we have an e-commerce application, that has Orders, and Items inside those Orders. So we could have (pseudo-code)

```<code>class Order
{
     int id;
     List<OrderItem> Items;
}

class OrderItem
{
     Product product;
     int quantity;
}
</code>```

And then use it (1)

```<code>var o = LoadOrder(id);
foreach (var i in o.Items) {
</code>```

...or we could do:

```<code>class Order
{
    int id;
}
</code>```

And use it this way: (2)

```<code>var odr = LoadOrder(id);
var itms = LoadItemsOfOrder(odr);
foreach (var i in itms) {
    .....
</code>```

The first way is more compact and more "OOP-ish", but the second way gives more control on how and when items are requested, e.g. what if now I need to request only the items that have quantity > 3 ? And what if I don't use the Items collection at all (e.g. to display only a list of orders) - I will be doing unnecessary queries to the database.

In my older, big projects I've gone with a hybrid approach - the domain classes are of the first flavor but there are various "load" methods, like "LoadOrder" and "LoadOrderWithItems" or "FillOrderObject".

Now I am working on a small, toy project, no customers and crazy deadlines and got time to think on these issues.

I tried searching the web but it is very hard to find a POCO answer not related to Entity Framework. (I am not working in .net this time, but would like to apply these concepts.)

Question: is there a method which is clearly better than the other, or both are valid and "it depends" on my project, if I am aiming for performance or for code clarity and maintainability?.

答:
I am used to develop using POCO classes in my projects, that is, domain objects contain absolutely no logic, only data.

First off, your objects should not be only data. Behavior is central to you domain, and thus your domain objects should contain behavior logic. If anything they should contain all your behavior logic.

Domain objects that are just data would be what Martin Fowler calls an anemic domain model

POCO simply means you don't create your objects in your domain model with dependencies to external libs or frameworks. You don't make your classes all children of FunkyORMLibrary7 or something. The objects should be plain old objects that can be run without any external modules being loaded, this reduces dependency and also makes them easy to test in isolation. But that doesn't mean no logic in them, quite the opposite.

I am wondering which is the best approach when dealing with class relationships - to put a collection inside the class or to request it later.

You should be restricting who has responsibility to send messages to Order Item objects based on responsibilities. Who is responsible for ensuring the integrity of the who order including all the items in an order. In both your examples you are pulling order items out of the Order that contains them and operating on the items independently. That, in most cases, is a bad idea.

Think of a real world example. If you worked in a company would you let anyone in the company alter the information on an order document? I would imagine not, you would end up with a situation where the janitor just turned an order for 5 iPhones into an order for 50 million iPhones.

Some where you will need domain logic that controls what is or isn't valid actions to take on an order item. Only the object that contains this logic should be allowed operated on order items.

It makes far more sense that Order Items are accessed only through the Order object that contains them, since this is probably where all that logic will be held. In this case neither of your examples works. The for loop that is in both examples should be in the Order object, not outside of it and nothing should be able to iterate over the order items other than the order object itself.

Unless you have a very very good reason for accessing an individual order item outside of the order that contains it the rest of your system shouldn't be able to access the order item outside of the order that contains it. That is the key notion of the principle of encapsulation in OO and of an aggregation root in DDD.

Again from Martin Fowler DDD Aggregate

A DDD aggregate is a cluster of domain objects that can be treated as a single unit. An example may be an order and its line-items, these will be separate objects, but it's useful to treat the order (together with its line items) as a single aggregate ... Any references from outside the aggregate should only go to the aggregate root. The root can thus ensure the integrity of the aggregate as a whole.


问:
Is Software Testing Really Needed?
I'm a student working on my B.E(CS) and my question is the following:

Is testing in the software field needed?

If we create a software with great care, then why should we test?

After testing can we be sure that we have achieved this goal (the product/software works as intended) because we have done the testing for it? Is it possible?

My question: Is testing of software needed?

答:
YES

Imagine your software is only a logical function AND(b1, b2) where b1 and b2 are only bits. With that you need 4 test cases to be sure that your software is error free, if your surrounding environment delivers exactly what they were specified for.

Now your system is made by a lot of functions whose simplest one is way more complicated than that logical function. How would you make sure it is error free ?

(to be continued)

Title: Is Software Testing Really Needed?


问:
Is it okay to not completely understand code functionality?
As I am currently struggling with learning WCF for a project at work, for the past several days I have been looking at online tutorials and examples on the best way to make a WCF client; and today, when I told my boss I was having a hard time finding good tutorials because some of them would not go into details with their examples (for instance showing a piece of code that works but not explaing why exactly, or making an example with just a few lines instead of at a larger scale), he told me that I should not try to understand them completely, because there are times where a code will just do what it does and I should leave it at that (he gave me the example that when doing calculus, for instance, we use formulas that we don't know how they were conceived or how they work, we just know that they do and we use them).

And this bothered me because I have always been told that it's really important to understand your code, and that just copying and pasting without knowing HOW it works is practically a sin; which is why I always take my time in understanding something before moving forward with it. And it's not like I'm trying to understand how a particular class works at an assembly language level, I just want to know why a set of instructions does the trick, and why another one doesn't, or why both do and under what circumstances. But my boss tells me that I will end up wasting time obsessing over these little details, and I should just skip it. So my question is, is he right? Is it okay to understand your code only to a certain extent and keep going, and have I only been obsessing over little things that don't matter?

答:
Not that I disagree with the other answers, but let me respond to what I read between the lines. If your boss is advising you that you don't need to understand how something works, it could be some feedback that you are taking too long to get something done. Some people easily get distracted by unimportant details and for them it is advisable to work on staying on track.

On the other hand, if programming is your chosen profession and you do have the intellectual curiosity to dig deeper into some technology that is important to what you do, then I would encourage you to take some extra time to follow your interests when possible. The insights that you gain, though not immediately rewarding, will pay dividends in the long run. It will help you make sense of the technology, put you in a position to extend it in many cases, and will prepare you for an even deeper understanding in the future. Over time, this is what differentiates an expert from a casual user.


问:
Understanding Cyclomatic Complexity
I've recently come across Cyclomatic Complexity and I'd like to try to understand it better.

What are some practical coding examples of the different factors that go into calculating the complexity? Specifically, for the Wikipedia equation of M = E − N + 2P, I want to better understand what each of the following terms means:

E = the number of edges of the graph

N = the number of nodes of the graph

P = the number of connected components

I suspect that either E or N may be the number of decision points (if, else if, for, foreach, etc) in a block of code, but I'm not quite sure which is which or what the other signifies. I'm also guessing that P refers to function calls and class instantiations, but there isn't a clear definition given that I can see. If someone could shed a little more light with some clear code examples of each, it would help.

As a follow-up, does the Cyclomatic Complexity directly correlate to the number of unit tests needed for 100% path coverage? As an example, does a method with a complexity of 4 indicate that 4 unit tests are needed to cover that method?

Finally, do regular expressions affect Cyclomatic Complexity, and if so, how?

答:
Some remarks on this that I idly write up...

Specifically, for the Wikipedia equation of M = E − N + 2P

That equation is very wrong.

For some reason, McCabe indeed uses it in his original paper ("A Complexity Measure", IEEE Transactions on Software Engineering, Vo.. SE-2, No.4, December 1976), but without justifying it and after actually citing the correct formula on the first page, which is

v(G) = e - v + p

(Here, the formula elements have been relabeled)

Specifically, McCabe references the book C.Berge, Graphs and Hypergraphs (abbreviated below to G&HG). Directly from that book:

Definition (page 27 bottom of G&HG):

The cyclomatic number v(G) of an (undirected) graph G (which may have
  several disconnected components) is defined as:

v(G) = e - v + p

where e = number of edges, v = number of vertices, p = number of
  connected components

Theorem (page 29 top of G&HG) (not used by McCabe):

The cyclomatic number v(G) of a graph G is equal to the maximum number
  of independent cycles

A cycle is a sequence of vertices starting and ending at the same vertex, with each two consecutive vertices in the sequence adjacent to each other in the graph.

Intuitively, a set of cycles is independent if none of the cycles can be constructed from the others by superimposing the walks.

Theorem (page 29 middle of G&HG) (as used by McCabe):

In a strongly connected graph G, the cyclomatic number is
  equal to the maximum number of linearly independent circuits.

A circuit is a cycle with no repetitions of vertices and edges allowed.

A directed graph is said to be strongly connected if every vertex is reachable from every other vertex by passing through the edges in their designated direction.

Note that here we passed from undirected graphs to strongly connected graphs (which are directed ... Berge doesn't make this entirely clear)

McCabe now applies the above theorem to derive a simple way to compute a “McCabe Cyclomatic Complexity Number” (CCN) thusly:

Given a directed graph representing the “jump topology” of a procedure (the instruction flow graph), with a designated vertex representing the unique entry point and a designated vertex representing the unique exit point (the exit point vertex may need to be “constructed” by adding it in case of multiple returns), create a strongly connected graph by adding a directed edge from the exit point vertex to the entry point vertex, thus making the entry point vertex reachable from any other vertex.

McCabe now posits (rather confusingly I might say) that the cyclomatic number of the modified instruction flow graph "conforms to our intuitive notion of 'minimum number of paths'", and so we shall use that number as complexity measure.

Cool, so:

The cyclomatic complexity number of the modified instruction flow graph can be determined by counting the "smallest" circuits in the undirected graph. This is not particularly hard to do by man or machine, but applying the above theorem gives us an even easier way to determine it:

v(G) = e - v + p

if one disregards the directionality of the edges.

In all cases, we just consider a single procedure, so there is only one connected component in the whole graph, and so:

v(G) = e - v + 1.

In case one considers the original graph without the added "exit-to-entry" edge, one obtains simply:

ṽ(G) = ẽ - v + 2

as ẽ = e - 1

Let's illustrate by using McCabe' example from his paper:

Here we have:

e = 10

v = 6

p = 1 (one component)

v(G) = 5 (we are clearly counting 5 cycles)

The formula for the cyclomatic number says:

v(G) = e - v + p

which yields 5 = 10 - 6 + 1 and so correct!

The "McCabe cyclomatic complexity number" as given in his paper is

5 = 9 - 6 + 2 (no further explanations are given in the paper as to how)

which happens to be correct (it yields v(G)) but for the wrong reasons, i.e. we use:

ṽ(G) = ẽ - v + 2

and thus ṽ(G) = v(G) ... phew!

But is this measure any good?

In two words: Not very

It is not entirely clear how to establish the "instruction flow graph" of a procedure, especially if exception handling and recursion enter the picture. Note that McCabe applied his idea to code written in FORTRAN 66, a language with no recursion, no exceptions and a straightforward execution structure.

The fact that a procedure with a decision and a procedure with a loop yield the same CCN is not a good sign.

Even less good is the fact that for loops and while loops are handled in the same way (note that in C, one can abuse the for to express a while in another way; here I am talking about the strict for (int i=0;i<const_val;i++) loop). We know from theoretical computer science that these two constructs yields totally different computational powers: primitive-recursive functions if you are only equipped with for, partial μ-recursive functions if you are equipped with while.

An experiment having experts judge the complexity of code shows that CCN does not capture the idea of "code complexity" as well as other measures, in particular Halstead's software science and Shao and Wangs' cognitive functional size (the latter being apparently the winner), see Applicability of three cognitive complexity metrics, 2012 International Conference on Advances in ICT for Emerging Regions, 12-15 Dec. 2012

Empiricial verification shows that (at least for mature code), CCN is strongly linearly correlated with LOC (lines of code), i.e. the CCN inreases naturally with the length of the procedure and you might as well use the LOC count to express complexity. A better measure than absolute CCN might be CCN/LOC. See in particular: Cyclomatic complexity metrics revisited - DSpace@MIT and The role of empiricism in improving the reliability of future software

Title: Understanding Cyclomatic Complexity

Body:
Some remarks on this that I idly write up...

Specifically, for the Wikipedia equation of M = E − N + 2P

That equation is very wrong.

For some reason, McCabe indeed uses it in his original paper ("A Complexity Measure", IEEE Transactions on Software Engineering, Vo.. SE-2, No.4, December 1976), but without justifying it and after actually citing the correct formula on the first page, which is

v(G) = e - v + p

(Here, the formula elements have been relabeled)

Specifically, McCabe references the book C.Berge, Graphs and Hypergraphs (abbreviated below to G&HG). <a href="http://books.google.lu/books?id=h5BjnaoKyOwC&lpg=PA29&ots=PXYTc6FnR7&dq=the%20fundamental%20numbers%20of%20the%20theory%20of%20graphs%20as%20before,%20starting%20with%20a%20graph%20consisting%20of%20the%20vertices%20of%20G%20isolated%20from%20one%20another&pg=PA29#v=onepage&q=the%20fundamental%20numbers%20of%20the%20theory%20of%20graphs%20as%20before,%20starting%20with%20a%20graph%20consisting%20of%20the%20vertices%20of%20G%20isolated%20from%20one%20another&f=false" rel="noreferrer">Directly from that book:

Definition (page 27 bottom of G&HG):

The cyclomatic number v(G) of an (undirected) graph G (which may have
  several disconnected components) is defined as:

v(G) = e - v + p

where e = number of edges, v = number of vertices, p = number of
  connected components

Theorem (page 29 top of G&HG) (not used by McCabe):

The cyclomatic number v(G) of a graph G is equal to the maximum number
  of independent cycles

A cycle is a sequence of vertices starting and ending at the same vertex, with each two consecutive vertices in the sequence adjacent to each other in the graph.

Intuitively, a set of cycles is independent if none of the cycles can be constructed from the others by superimposing the walks.

Theorem (page 29 middle of G&HG) (as used by McCabe):

In a strongly connected graph G, the cyclomatic number is
  equal to the maximum number of linearly independent circuits.

A circuit is a cycle with no repetitions of vertices and edges allowed.

A directed graph is said to be strongly connected if every vertex is reachable from every other vertex by passing through the edges in their designated direction.

Note that here we passed from undirected graphs to strongly connected graphs (which are directed ... Berge doesn't make this entirely clear)

McCabe now applies the above theorem to derive a simple way to compute a “McCabe Cyclomatic Complexity Number” (CCN) thusly:

Given a directed graph representing the “jump topology” of a procedure (the instruction flow graph), with a designated vertex representing the unique entry point and a designated vertex representing the unique exit point (the exit point vertex may need to be “constructed” by adding it in case of multiple returns), create a strongly connected graph by adding a directed edge from the exit point vertex to the entry point vertex, thus making the entry point vertex reachable from any other vertex.

McCabe now posits (rather confusingly I might say) that the cyclomatic number of the modified instruction flow graph "conforms to our intuitive notion of 'minimum number of paths'", and so we shall use that number as complexity measure.

Cool, so:

The cyclomatic complexity number of the modified instruction flow graph can be determined by counting the "smallest" circuits in the undirected graph. This is not particularly hard to do by man or machine, but applying the above theorem gives us an even easier way to determine it:

v(G) = e - v + p

if one disregards the directionality of the edges.

In all cases, we just consider a single procedure, so there is only one connected component in the whole graph, and so:

v(G) = e - v + 1.

In case one considers the original graph without the added "exit-to-entry" edge, one obtains simply:

ṽ(G) = ẽ - v + 2

as ẽ = e - 1

Let's illustrate by using McCabe' example from his paper:

Here we have:

e = 10

v = 6

p = 1 (one component)

v(G) = 5 (we are clearly counting 5 cycles)

The formula for the cyclomatic number says:

v(G) = e - v + p

which yields 5 = 10 - 6 + 1 and so correct!

The "McCabe cyclomatic complexity number" as given in his paper is

5 = 9 - 6 + 2 (no further explanations are given in the paper as to how)

which happens to be correct (it yields v(G)) but for the wrong reasons, i.e. we use:

ṽ(G) = ẽ - v + 2

and thus ṽ(G) = v(G) ... phew!

But is this measure any good?

In two words: Not very

It is not entirely clear how to establish the "instruction flow graph" of a procedure, especially if exception handling and recursion enter the picture. Note that McCabe applied his idea to code written in FORTRAN 66, a language with no recursion, no exceptions and a straightforward execution structure.

The fact that a procedure with a decision and a procedure with a loop yield the same CCN is not a good sign.

Even less good is the fact that for loops and while loops are handled in the same way (note that in C, one can abuse the for to express a while in another way; here I am talking about the strict for (int i=0;i<const_val;i++) loop). We know from theoretical computer science that these two constructs yields totally different computational powers: primitive-recursive functions if you are only equipped with for, partial μ-recursive functions if you are equipped with while.

An experiment having experts judge the complexity of code shows that CCN does not capture the idea of "code complexity" as well as other measures, in particular Halstead's software science and Shao and Wangs' cognitive functional size (the latter being apparently the winner), see Applicability of three cognitive complexity metrics, 2012 International Conference on Advances in ICT for Emerging Regions, 12-15 Dec. 2012

Empiricial verification shows that (at least for mature code), CCN is strongly linearly correlated with LOC (lines of code), i.e. the CCN inreases naturally with the length of the procedure and you might as well use the LOC count to express complexity. A better measure than absolute CCN might be CCN/LOC. See in particular: Cyclomatic complexity metrics revisited - DSpace@MIT and The role of empiricism in improving the reliability of future software


问:
How to extend Constructor Injection?
Suppose I have MyClass with a very simple dependency.  It uses constructor injection.

```<code>public class MyClass : IMyClass
{
    private IA A;

    public MyClass(IA a)
    {
        A = a;
    }
}
</code>```

This code get shipped and some other developers are using it.

At some point in the future I need to add in a second dependency, on IB.

How should I add this dependency on IB?

Some options, and why I disapprove:

Just add it to the constructor

Braking change.

Inheritance or the decorator pattern.

Extra classes and code bloat.

New class will have boilerplate code passing around the IA.

I have no guarantee that other developers will switch to using the new class.

Use a service locator to populate the new IB field.

I'm now using two different types of injection for extra confusion.

It seems to me that constructor injection is just not easily extensible.

答:
Create an implementation of IB that contains whatever behavior MyClass currently possesses that is being extracted, or if IB provides new functionality, then a sensible default implementation that preserves MyClass's current semantics.

Add IB dependency to MyClass via a new constructor.

Have the old constructor create an instance of the implementation of IB you made in step 1.

Old code still works, new code can provide alternate behavior as desired.

Title: How to extend Constructor Injection?


答:
If MyClass needs to have an IB to function, then there is not really a choice.
Any non-breaking change would just results in bugs because the others will keep using MyClass without providing the required IB object, so you can just as well prevent that and make the new dependency a required parameter of your constructor.

If the dependency on IB is optional, then you have a few options:

Derive a new MyClass_version2 from MyClass and provide all the new IB-related behavior from there. This will likely work best if there is little overlap between the existing behavior and the extensions.

Add the new IB dependency to MyClass, but ensure to set it to null in the existing constructor and ensure that all methods can handle a null IB. Then add an overload of the constructor MyClass(IA a, IB b).

Title: How to extend Constructor Injection?

Body:
Suppose I have MyClass with a very simple dependency.  It uses constructor injection.

```<code>public class MyClass : IMyClass
{
    private IA A;

    public MyClass(IA a)
    {
        A = a;
    }
}
</code>```

This code get shipped and some other developers are using it.

At some point in the future I need to add in a second dependency, on IB.

How should I add this dependency on IB?

Some options, and why I disapprove:

Just add it to the constructor

Braking change.

Inheritance or the decorator pattern.

Extra classes and code bloat.

New class will have boilerplate code passing around the IA.

I have no guarantee that other developers will switch to using the new class.

Use a service locator to populate the new IB field.

I'm now using two different types of injection for extra confusion.

It seems to me that constructor injection is just not easily extensible.


问:
Is inheritance that adds rules bad?
I got into a debate on this question which distilled to if it is a good idea for a specialization of a class to add business rules. Unfortunately this point got trampled in the comments so I'm asking it again as a separate question.

I believe two things:

An object is responsible for its internal consistency

A specialization/child class has more specific rules than the super class which can be seen as the general case.

The logical result of this is that a specialization might only accept some values of input for its method or might change some values in order to stay consistent. But isn't that OK, since guarding its internal consistency is what an object should do?

A point many people were making is that some code could break if it would make assumptions. For example that setting the width would not change the height of a square. However wouldn't that be bad code? Since you make assumptions on how the object does something instead of just telling it what to do and not worry about it?

If we would not write code like that almost all overloading would have problems. How often doesn't overloading add an extra fail condition or more internal logic that might be seen via other parts of the interface? Maybe the point an old professor of me once made is correct: "you should only ever use inheritance to overload the constructor". At the time that seemed a bit strict but now it seems like the only way to guarantee these kinds of problem never happening. To use the old square: rectangle analogy again:

```<code>public class Rectangle
{
    private int width, height;

    public Rectangle(int width, int height){this.width = width; this.height = height;}

    public void SetWidth... SetHeight...
}

public class Square : Rectangle
{
    public Square(int diameter) : base(diameter, diameter) {}

    public void SetDiameter...
}
</code>```

Note: I hope we can play this question a little bit less 'on the man' than the question that inspired it. I've been on Stack Exchange for more than three years but I was quite intimidated by the type of responses here.

答:
The trap a lot of people fall into is looking at inheritance as a means to codify any relationship or similarity between two classes.  That's not the case.  Inheritance is useful for certain limited kinds of relationships and is actually harmful when used outside those contexts.  Lack of substitutability is one reason why.

The crucial point a lot of people miss about the square-rectangle example is that it is perfectly substitutable if you reverse the relationship.  In object-oriented design, a rectangle is a specialized form of a square.  The reason that's hard to see is that people want to organize classes by the similarities between the classes themselves, perhaps following real-world taxonomies, when they should really be concerned with organizing classes by what methods the calling code will need to use on a mixed collection of those classes.  That's where the idea of substitutability comes in.

Think of it this way.  You have a bunch of code that sets the width of squares and you want to throw some rectangles into the mix.  You can set the width on either a square or rectangle all day without violating substitutability, but independently setting the height only applies to the rectangle, so it should not be a part of the base class.  You're adding to the specialized class, not changing the common behavior.

In other words, don't make it a false choice and say to yourself, "I have no choice but to violate substitutability."  If you can't do something without violating substitutability, then you either need to change your inheritance relationship, or not use inheritance at all.

Title: Is inheritance that adds rules bad?


答:
Take the classic example for inheritance - Dog : Animal where Dog is a class that inherits from Animal.  While Animal can eat, a dog can bark, jump, and swim.  So you add these methods to Dog.

It makes sense from a relation point of view.  Why should Animal be able to bark?  Why shouldn't Dog be able to bark?  In fact, nobody is claiming otherwise.  You see this type of relation often in code, however, whenever you need to use bark, you simultaneously need to know if it is a Dog.  Therefore any usage of bark automatically adds a direct dipendency on Dog any way you slice it.  Even if you take an Animal and check if it is a Dog, and then act accordingly, you're no longer acting on the general case of handling Animal.  There's nothing stopping you from diong this, though you've lost any advantage you had with inheritance.

In order to truly take advantage of inheritance, you must let inherited classes represent various implementations of the super class.  In this way, it isn't enough that a class "is a type of" another class.  It must also play the part of the super class with minor exceptions such as during its creation which is the only point in your program that should know the specific implementation being used.

So perhaps a better example wouldn't be Dog : Animal but rather Square : Drawable, where Drawable is an object that can be called to draw itself regardless of how.

Title: Is inheritance that adds rules bad?

Body:
I got into a debate on this question which distilled to if it is a good idea for a specialization of a class to add business rules. Unfortunately this point got trampled in the comments so I'm asking it again as a separate question.

I believe two things:

An object is responsible for its internal consistency

A specialization/child class has more specific rules than the super class which can be seen as the general case.

The logical result of this is that a specialization might only accept some values of input for its method or might change some values in order to stay consistent. But isn't that OK, since guarding its internal consistency is what an object should do?

A point many people were making is that some code could break if it would make assumptions. For example that setting the width would not change the height of a square. However wouldn't that be bad code? Since you make assumptions on how the object does something instead of just telling it what to do and not worry about it?

If we would not write code like that almost all overloading would have problems. How often doesn't overloading add an extra fail condition or more internal logic that might be seen via other parts of the interface? Maybe the point an old professor of me once made is correct: "you should only ever use inheritance to overload the constructor". At the time that seemed a bit strict but now it seems like the only way to guarantee these kinds of problem never happening. To use the old square: rectangle analogy again:

```<code>public class Rectangle
{
    private int width, height;

    public Rectangle(int width, int height){this.width = width; this.height = height;}

    public void SetWidth... SetHeight...
}

public class Square : Rectangle
{
    public Square(int diameter) : base(diameter, diameter) {}

    public void SetDiameter...
}
</code>```

Note: I hope we can play this question a little bit less 'on the man' than the question that inspired it. I've been on Stack Exchange for more than three years but I was quite intimidated by the type of responses here.


问:
MVC: Where should I store interchangeable algorithms used by the Model (whose names also need to be accessible to the View)?
Please consider a program, where the user chooses an algorithm from a list, and the Strategy pattern is utilized to set this algorithm as the model's operation.

For example, an image procession application. There are a number of algorithms that can be used to manipulate an image (darken, brighten, contrast, etc). They are all encapsulated in objects, and the controller sets the model to use an algorithm from this list. The algorithms also need to be presented by name on the UI.

This is how it will work:

The user can select an algorithm from a list on the GUI. When he/she does, the controller is notified, and sets the suitable algorithm in the model. Later on, when the model is called model.operate(), it will delegate the operation to it's current algorithm. Classic Strategy pattern.

Also, the view needs access to the names of the algorithms, in order to allow the user to choose one from a list.

My question is this:

Should I store the algorithms somewhere, where the controller will fetch them from when it needs to set an algorithm in the model? Or should the controller just instantiate a new algorithm whenever it needs to set an algorithm in the model?

If the answer is that it's good to store the algorithms somewhere - than where?

In the model? - makes sense because the model encapsulates the business logic and data of the app. But how will the view fetch the names of the algorithms?

In the controller? - makes sense because the controller is the one that sets the algorithms in the model. And also it can offer the view a method getAlgorithmNames(). But technically it shouldn't hold business logic objects, which is what the algorithms are.

In a different class, where anyone interested can fetch the algorithms or their names from?

I'm sure there have been a lot of applications where the user selects an operation, and the appropriate algorithm is set in the model. How do other applications do this?

答:
Just to avoid a possible misconception, in the MVC pattern, the Model part does not consist of a single class, but rather the Model encompasses all classes that are not interfacing with the user.

In simple terms:

View: The classes that show something to the user (they render output)

Controller: The classes that react to user actions

Model: Everything else.

Now to your question:

The algorithms and the list of their names belong in the Model part of your application.

The algorithms themselves are part of your business logic and belong in the model for that reason. And if the Model is maintaining a collection of algorithms, then it is only natural that the Model can also provide both Controller and View with a list of available algorithms.

Selection from the list can work in two ways:

The Model just provides a list of names. The View communicates the selected name to the Controller, which asks the Model for an instance of an algorithm with the specified name.

This is easy, but requires string compares in the Model and can wreak havoc with localization.

The Model provides a set of (key, value) pairs, where the key is an opaque ID that the Model can use to retrieve the specific instance of an algorithm and the value is the default name of the algorithm.

This takes a bit more work, but can be beneficial in localized applications (the View can show translated names without risk of breaking stuff) or in locally running applications (the Model could just use a pointer/reference to the actual algorithm object as key).


问:
Storing object-graphs with class-evolution in Java with transformation (long time archiving)

Abstract

A common problem is to store objects (with graph), and to load them back. This is easy as long the stored object representation matches the executing code. But as time goes by, requirements change and stored objects do not match any longer the code. The stored objects should not loose their data, and the code in the clients should work with the latest object-models.

So a transformation has to occur somehow between loading the data and returning a object to the client.

I know that there exist some libraries such as XStream, gson, protobuf and avro. They could load older objects, but afaik just ignore data that does not match any longer the fields in the class (maybe I missed something).

(When I'm talking about storing and serialization I do not mean Java's built in serialization mechanism.)

Question

So what is the question? I'm now researching for some time, and there seems no library that adresses this issue (class evolution) without data-loss. I hope to find another working solution or idea how to implement it by myself here.

I have some requirements:

File-based - I want to be able to store the serialized object on disk

Appendable - I want to append multiple objects to one file without loading the whole file in memory again and again

Support for multiple versions in one file - A file could contain objects with different version (only of the same type)

Transformation - Data should be accessible by using the same type, even when changed in between.

Generic - The mechanism itself has to be generic, so I could use it for different objects (different objects do not get mixed in one file, only different versions of one type).

It would be nice if the storing format is human-readable.

Already stored objects are not updateable (at least not without huge effort). Think of an long-term archive.

Example

I could give an example for better illustration. Let's suppose we have two Pojos that we want to serialize.

```<code>public class MyPojo {
    String text;
    Long number;
    Integer[] values;
    SubPojo pojo;
}

public class SubPojo {
    List<String> items;
}
</code>```

In the next version we might have renamed a field (text->content), changed a type (Integer[]->List), and have transformed a field to List (SubPojo->List) where the previous field now is the first element of the new list (not loosing data, just transforming to new representation).

```<code>public class MyPojo {
    String content;
    Long number;
    List<Integer> values;
    List<SubPojo> pojo;
}

public class SubPojo {
    List<String> items;
}
</code>```

Some pseudocode how the client might take use of this:

```<code>// Write
Serializer ser = new Serializer();
MyPojo pojo = new MyPojo();
pojo.xxx = ...; // set fields
ser.store(pojo, file, append);

// Read (a version later)
Serializer ser = new Serializer();
ser.registerTransformer(new TransformerV1ToV2());
List<MyPojo> pojos = ser.load(file);
</code>```

This approach has some drawbacks:

The transformer have to work on some kind of intermediate format (could be the backed stored format such as json or xml)

You don't know how the class format was at some point in time, since you're only transforming relative to the previous version and mapping to the final class, making search for errors hard

Performance (depending on how the transformation happens)

答:
I decided to use the transformation approach. JSON is used as intermediate-format, this way I can ensure the correctness using Json Schema between versions (optional).

Conceptional you can think in two ways if you like: As object-mapper, or as json-format that is expressed in java-objects.

I open-sourced my solution at http://github.com/galan/verjson

The documentation will be extended in the next time. I also added support for custom-serializer/deserializer and polymorph types.