问:
Elemental access in arrays
I was reading up on data structures from Code Complete. This is when I stumbled through this piece about arrays:

Think of arrays as sequential structures Some of the brightest people in computer science have suggested that arrays never be
  accessed randomly, but only sequentially (Mills and Linger 1986).
  Their argument is that random accesses in arrays are similar to random
  gotos in a program: Such accesses tend to be undisciplined, error
  prone, and hard to prove correct. Instead of arrays, they suggest
  using sets, stacks, and queues, whose elements are accessed
  sequentially.

Does this hold true for System.Array class in C#?

答:
It certainly does. Arrays in C# are very similar to arrays in other programming languages.

Some differences between dynamically allocated arrays in C and arrays in C#:

In C#, array always knows its length.

You can't use pointer arithmetic in C# (unless you use unsafe). This means that part of the array can't be represented as (pointer, length), it has be represented as something like (reference, start_index, length).

But none of these differences are relevant to the quote in question.

Also, C# makes it easy to treat array as a sequential structure: it implements IEnumerable<T> and can be used in a foreach (though neither of these allows you to modify the array). This means you can iterate though the array without using indexes. For example:

```<code>foreach (var item in array)
    Console.WriteLines(array);
</code>```

Or (using LINQ, which is based on IEnumerable<T>):

```<code>var unavailableProducts = products.Where(p => p.InStock == 0);
</code>```

Title: Elemental access in arrays

Body:
It certainly does. Arrays in C# are very similar to arrays in other programming languages.

Some differences between dynamically allocated arrays in C and arrays in C#:

In C#, array always knows its length.

You can't use pointer arithmetic in C# (unless you use unsafe). This means that part of the array can't be represented as (pointer, length), it has be represented as something like (reference, start_index, length).

But none of these differences are relevant to the quote in question.

Also, C# makes it easy to treat array as a sequential structure: it implements IEnumerable<T> and can be used in a foreach (though neither of these allows you to modify the array). This means you can iterate though the array without using indexes. For example:

foreach (var item in array)
    Console.WriteLines(array);

Or (using LINQ, which is based on IEnumerable<T>):

var unavailableProducts = products.Where(p => p.InStock == 0);


答:
The point is language-unspecific, so as far as it holds, it holds for C#. (The only exception would be if your language has arrays where random access is not O(1), but I can't think of one off-hand.)

But of course there are situations in programing where you definitely don't need to access all items in a collection, but only one particular item per request, and in such situations it can be useful to arrange the items in an array for fast access. I don't think anyone would argue that random access per se is undisciplined and should be avoided in any situation - but in those where looping does the trick, it is indeed easier to program and to verify.

ContentLicense: CC BY-SA 3.0

Title: Elemental access in arrays

Body:
I was reading up on data structures from Code Complete. This is when I stumbled through this piece about arrays:

Think of arrays as sequential structures Some of the brightest people in computer science have suggested that arrays never be
  accessed randomly, but only sequentially (Mills and Linger 1986).
  Their argument is that random accesses in arrays are similar to random
  gotos in a program: Such accesses tend to be undisciplined, error
  prone, and hard to prove correct. Instead of arrays, they suggest
  using sets, stacks, and queues, whose elements are accessed
  sequentially.

Does this hold true for System.Array class in C#?


问:
Self-referencing anonymous closures: is JavaScript incomplete?
Does the fact that anonymous self-referencing function closures are so prevelant in JavaScript suggest that JavaScript is an incomplete specification? We see so much of this:

```<code>(function () { /* do cool stuff */ })();
</code>```

and I suppose everything is a matter of taste, but does this not look like a kludge, when all you want is a private namespace? Couldn't JavaScript implement packages and proper classes?

Compare to ActionScript 3, also based on ECMAScript, where you get

```<code>package com.tomauger {
  import bar;
  class Foo {
     public function Foo(){
       // etc...
     }

     public function show(){
       // show stuff
     }

     public function hide(){
       // hide stuff
     }
     // etc...
  }
}
</code>```

Contrast to the convolutions we perform in JavaScript (this, from the jQuery plugin authoring documentation):

```<code>(function( $ ){

  var methods = {
    init : function( options ) { // THIS },
    show : function( ) { // IS   },
    hide : function( ) { // GOOD },
    update : function( content ) { // !!! }
  };

  $.fn.tooltip = function( method ) {

    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }

  };

})( jQuery );
</code>```

I appreciate that this question could easily degenerate into a rant about preferences and programming styles, but I'm actually very curious to hear how you seasoned programmers feel about this and whether it feels natural, like learning different idiosyncrasies of a new language, or kludgy, like a workaround to some basic programming language components that are just not implemented?

答:
First off, a couple things:

Another way of looking at JavaScript is the 1 million and 1 things you can do with the function as a construct. It's all there if you look for it. It's just never far from a function.

That jQuery plug-in authoring thing is awful. I have no idea why they're advocating that. $ extensions should be general-use stuff that $ already has pretty-well covered not build-me-a-complete-widget methods. It's a DOM-API normalization tool. It's use is best buried inside your own objects. I don't see the appeal of using it as a full-on UI library repository.

Packages on the Client Side Web are Pointless

What I don't personally like about packages on the client-side web is that we'd basically be pretending we're doing something that we're really not. In a post .NET webforms and gobs-of-horrifying-stuff-that-never-panned-out-from-our-Java-friends world, I'd rather think of a hunk of HTML with linked resources as what it really is and not try to appease learning-new-things-resistant OS app developers by pretending it's something else. In JS on the client-side web, nothing gets "imported" barring doing something awful with Ajax that operates in ignorance of browser-caching, which yes, many have tried to do. All that matters to the browser is that it was either loaded in and interpreted or it wasn't. We don't have more code stashed on the client somewhere available for use "just in case" for good reasons. #1 being that I just described a plug-in and browser plug-in dependencies for web apps as a phenomenon has not generally worked out too well. We want web now. Not after Adobe or Sun is done updating the third time this week.

The Language Has What it Needs for Structure

JS objects are highly mutable. We can have branching trees of namespaces to any degree that we find it useful to do so and it's very easy to do. But yes, for anything re-usable you do have to stick the root of any library at the global space. All dependencies are linked and loaded at the same time anyway, so what's the point of doing anything else? The point of avoiding the global namespace isn't that anything there is bad. It's that too much stuff there is bad because you run the risk of namespace collisions or accidentally overwriting core language features.

Just Because it's Popular Doesn't Mean We're Doing it Right

Now when you see this all over a client-side web app:

```<code>(function(){
//lots of functions defined and fired and statement code here
})()
</code>```

The problem isn't that we lack tools to structure an app around, the problem is that people aren't valuing structure. For 2-3 page one-off temporary throwaway sites at a design agency, I don't really  have a problem with that. Where it gets ugly is when you have to build something maintainable and legible and easy to modify.

But when you get to the place where it's time to just implement all of the re-usable objects and factories and maybe one or two new temporary vars might creep into that process, it's a convenience.

But There Are Implementations of JS With Packages/Modules

Keep in mind that in Node.js, where such things make a lot more sense, they do have modules. JS, assuming we can avoid uber-config-hell that plagues other languages, is the only thing in the equation and each executed file is its own isolated scope. But on a web page, linking a js-file is itself the import statement. Doing more imports on the fly is just a waste of time and resources since getting the resources requires a lot more effort than simply adding links to files as you need them knowing they'll be cached in a browser if another page needs them again. So is trying to split up the global space by doing anything other than create adapter object factories like jQuery or more traditional objects that cover a large subset of tasks in a given domain while occupying one spot in global. There's also efforts underway to actually write modules into future spec: http://wiki.ecmascript.org/doku.php?id=harmony:modules

So no, there's nothing wrong with auto-invokers used to avoid global namespace pollution when there's a good reason to use such things (more often than not there isn't). And we have persistent private-equivalent properties in our objects (just define a var in the constructor and don't expose it as a property).

The fact that we CAN do such things, however, is awesome. Heavy usage is a sign that JS developers are still maturing perhaps, but it's not a gaping hole in the language to anybody who's not trying to force a paradigm into the client-side web that just doesn't make sense here.

Body:
First off, a couple things:

Another way of looking at JavaScript is the 1 million and 1 things you can do with the function as a construct. It's all there if you look for it. It's just never far from a function.

That jQuery plug-in authoring thing is awful. I have no idea why they're advocating that. $ extensions should be general-use stuff that $ already has pretty-well covered not build-me-a-complete-widget methods. It's a DOM-API normalization tool. It's use is best buried inside your own objects. I don't see the appeal of using it as a full-on UI library repository.

Packages on the Client Side Web are Pointless

What I don't personally like about packages on the client-side web is that we'd basically be pretending we're doing something that we're really not. In a post .NET webforms and gobs-of-horrifying-stuff-that-never-panned-out-from-our-Java-friends world, I'd rather think of a hunk of HTML with linked resources as what it really is and not try to appease learning-new-things-resistant OS app developers by pretending it's something else. In JS on the client-side web, nothing gets "imported" barring doing something awful with Ajax that operates in ignorance of browser-caching, which yes, many have tried to do. All that matters to the browser is that it was either loaded in and interpreted or it wasn't. We don't have more code stashed on the client somewhere available for use "just in case" for good reasons. #1 being that I just described a plug-in and browser plug-in dependencies for web apps as a phenomenon has not generally worked out too well. We want web now. Not after Adobe or Sun is done updating the third time this week.

The Language Has What it Needs for Structure

JS objects are highly mutable. We can have branching trees of namespaces to any degree that we find it useful to do so and it's very easy to do. But yes, for anything re-usable you do have to stick the root of any library at the global space. All dependencies are linked and loaded at the same time anyway, so what's the point of doing anything else? The point of avoiding the global namespace isn't that anything there is bad. It's that too much stuff there is bad because you run the risk of namespace collisions or accidentally overwriting core language features.

Just Because it's Popular Doesn't Mean We're Doing it Right

Now when you see this all over a client-side web app:

(function(){
//lots of functions defined and fired and statement code here
})()

The problem isn't that we lack tools to structure an app around, the problem is that people aren't valuing structure. For 2-3 page one-off temporary throwaway sites at a design agency, I don't really  have a problem with that. Where it gets ugly is when you have to build something maintainable and legible and easy to modify.

But when you get to the place where it's time to just implement all of the re-usable objects and factories and maybe one or two new temporary vars might creep into that process, it's a convenience.

But There Are Implementations of JS With Packages/Modules

Keep in mind that in Node.js, where such things make a lot more sense, they do have modules. JS, assuming we can avoid uber-config-hell that plagues other languages, is the only thing in the equation and each executed file is its own isolated scope. But on a web page, linking a js-file is itself the import statement. Doing more imports on the fly is just a waste of time and resources since getting the resources requires a lot more effort than simply adding links to files as you need them knowing they'll be cached in a browser if another page needs them again. So is trying to split up the global space by doing anything other than create adapter object factories like jQuery or more traditional objects that cover a large subset of tasks in a given domain while occupying one spot in global. There's also efforts underway to actually write modules into future spec: http://wiki.ecmascript.org/doku.php?id=harmony:modules

So no, there's nothing wrong with auto-invokers used to avoid global namespace pollution when there's a good reason to use such things (more often than not there isn't). And we have persistent private-equivalent properties in our objects (just define a var in the constructor and don't expose it as a property).

The fact that we CAN do such things, however, is awesome. Heavy usage is a sign that JS developers are still maturing perhaps, but it's not a gaping hole in the language to anybody who's not trying to force a paradigm into the client-side web that just doesn't make sense here.


问:
A question regarding linked list vs vector insert/remove results comparison
I was reading this blog post: http://kjellkod.wordpress.com/2012/02/25/why-you-should-never-ever-ever-use-linked-list-in-your-code-again/

and I found there a code to run: http://ideone.com/62Emz

I've compiled it using gcc 4.7.2 with g++ -std=c++11 on my old laptop with T5450 cpu with two cores with 32 Kbytes L1 cache each and 2 Megabytes of (common?) L2 cache and I have got this results:

```<code>********** Times in microseconds**********
Elements ADD (List, Vector)     ERASE(List, Vector)
100,     , 0, 0,                0, 0
200,     , 0, 0,                15625, 0
500,     , 0, 0,                0, 0
1000,    , 15625, 0,            0, 15625
4000,    , 109375, 140625,              46875, 31250
10000,   , 750000, 875000,              312500, 187500
20000,   , 2968750, 3468750,            1296875, 781250
40000,   , 12000000, 13843750,          5359375, 3156250
Exiting test,. the whole measuring took 45375 milliseconds (45seconds or 0 minut
es)
</code>```

Which actually says an opposite, at least for ADD operation comparing to what author of that blog post says. List is faster for ADD than Vector. What conclusions should I make from my results? Does it proof anything? What should I think or understand?

答:
First of all, congratulations for doing the right thing and measuring rather than believing advice about efficiency! With modern computer architecture, it is harder than ever to predict how precisely a small change in data structures will affect runtimes, because of the many levels of the memory hierarchy, out-of-order execution, aggressive code optimizers etc. If your use case is indeed what you have measured, then yes, you will be better off with a list.

That said, that program doesn't do a lot; in practice you will almost certainly access elements more often than you add or delete them, and probably in non-successive ways. I suspect that if you rerun benchmarks with a lot of random accesses, the results might turn around, but... remember what I just said? Never assume. Always measure. Happy profiling!


问:
Detecting misusage of delete[] vs. delete at compile time
I'd like to know if it's possible to detect the delete error commented below at compile time? Especially, I'd like to hear about g++ compiler.

ClassTypeA *abc_ptr = new ClassTypeA[100];
abc_ptr[10].data_ = 1;
delete abc_ptr; // error, should be delete []
```

答:
You can use the appropriate RAII classes to delete. This is the only safe way of doing it, and this error is only one of the very, very many you will encounter calling delete yourself.

Always use classes to manage dynamic lifetime resources, and the type system will enforce correct resource destruction.

Edit: "What if you're auditing the code and can't change it?" You're fucked.


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答:
In a company that sold software...giving salespeople full commission on all custom mods sold, so that selling something that already existed and we could just profit on was not nearly as profitable for them as selling one-offs.  This was combined with moving the sales staff halfway across the country from the technical staff.

This also meant that we in Development couldn't possibly meet the sales deadlines, making customers unhappy, and had a great deal of difficulty in getting any core work done that would make the product better for everybody.  The increased pressure caused code quality to decrease and hurt morale, particularly when we heard stories about the sales office (which I never confirmed).

Lots of us resented Sales, but in fact it wasn't their fault.  They were going out and selling as much as they could, doing what they were rewarded for in accordance with the limits that had been placed on them.  It was bad management that caused all these problems.

ContentLicense: CC BY-SA 2.5


问:
More comfortable working on the backend, often referred for role on the front end
I have applied and have been approached for different roles in web development recently. The one thing that keeps coming up is that I am more suited to front end development than back end development.  This makes sense given my background starting out as a designer.

The problem is that while I have worked on a large app using ExtJS, I found designing and developing in ExtJS really frustrating. Oddly enough, it was working on this project that landed me in web development because my coding skills were recognized by some senior developers. I highlight that in my CV but I wonder if this might be a mistake.

I also use JavaScript quite a bit outside of web development. Specifically in Photoscript and InDesign to create batch operations.  It's often assumed that I have expert knowledge in JavaScript, whereas I'm only just getting to grips with the OOP style of JavaScript.  I use a lot of procedural code or I just use libraries like jQuery and Google Maps. I have created some experimental apps in Node and Knockout which I fortunately have enjoyed although Node is back end. I used to avoid JavaScript and jQuery in certain web projects since I was focusing on SEO and would only use Javascript if I really needed it.

During the interviews, I'm asked questions about JavaScript and front-end development.  But I really wanted to talk about PHP and the server side development, so I guess my background shows. How do I address this when I am either contacted for a role or I applying directly without selling my short?

答:
Beside @Karl Bielefeldt excelent answer that your interviewer need someone for the part where you are not so much interested in there may be more.

```<code>> During the interviews, I'm asked questions about JavaScript and
> front-end development. But I really wanted to talk about PHP and the
> server side development
</code>```

[Speculation]

May be your interviewer is already shure that you know enough for the job with php and server side development. He wants to find out where you limits in other fields are.

May be the server side development is not with php but with java/c# or something else.

[/Speculation]

But without asking the interviewer we can only speculate about the interviewers behavior.
I have made good experience in having a more active role in the interview situation and asking many (detail) questions in the topics i was interested in.

Remember you are applying for a job but also they (the stuff where the interviewer belongs to) are also applying to become your contractor.

OwnerDisplayName: anon

Body:
Beside @Karl Bielefeldt excelent answer that your interviewer need someone for the part where you are not so much interested in there may be more.

> During the interviews, I'm asked questions about JavaScript and
> front-end development. But I really wanted to talk about PHP and the
> server side development

[Speculation]

May be your interviewer is already shure that you know enough for the job with php and server side development. He wants to find out where you limits in other fields are.

May be the server side development is not with php but with java/c# or something else.

[/Speculation]

But without asking the interviewer we can only speculate about the interviewers behavior.
I have made good experience in having a more active role in the interview situation and asking many (detail) questions in the topics i was interested in.

Remember you are applying for a job but also they (the stuff where the interviewer belongs to) are also applying to become your contractor.


答:
This particular error - yes. This kind of error generally: unfortunately, no! That would involve predicting the flow of execution without actually executing it, and that isn't possible for arbitrary programs. (That's why most compilers don't even try to detect simple cases like your example.)

Therefore DeadMG's answer is the appropriate one: don't try to get it right by paying attention - human attention is fallible. Use the language-provided means and let the computer pay attention.

Title: Detecting misusage of delete[] vs. delete at compile time

Body:
I'd like to know if it's possible to detect the delete error commented below at compile time? Especially, I'd like to hear about g++ compiler.

ClassTypeA *abc_ptr = new ClassTypeA[100];
abc_ptr[10].data_ = 1;
delete abc_ptr; // error, should be delete []
```


问:
Which asp.net technology fits this situation best?
I think I can count WebAPI out, but WebForms, WebPages, and MVC are all possibilities.

I want to create an asp.net web site that is primarily static content and links to other sites. The only "fancy" bit will be a Bing map with pushpins that I add - but even these are static. And there will be a photo gallery. Oh, and ads, too.

And, finally, it needs to work well on phones and tablets as well as desktop browsers.

Which asp.net technology "flavor" is most suited for this type of web site?

UPDATE

In VS 2012, Web Pages projects are not available beneath Templates | Visual C# | Web.

What is there:

```<code>ASP.NET Empy Web Application
ASP.NET Web Forms Application
ASP.NET MVC 3 Web Application
ASP.NET MVC 4 WebApplication
ASP.NET Dyanmic Data Entities Web Application
</code>```

Does this mean that Web Pages are passe, or that Web Pages and Web Forms are the same thing?

答:
It's easy to discard WebForms because you're not accepting user data, no MVC because, well, your model isn't going to be substantial. That leaves WebPages.

But let's look at this from another perspective: what happens when the requirements change? Are you looking forward to doing much of what you've already done over again because your site needs added functionality, because suddenly there IS supposed to be heavy user interaction, data being pushed back to the server, a model that will influence your view?

Don't be too quick to choose the easy way out because more often than not, that means closing the door on flexibility and scalability. More often than not, at some point, sailor-like swearing will ensue.

Go with MVC. We don't live in an era of a static web anymore.

As far as multi-device goes: that's mainly a CSS-related endeavor, should have very little to do with ASP.NET in itself. If you design it well from the start, that is.


答: Maybe consider something like Nancy, it's lightweight and aims to get out of your way as much as possible. As @Wim Ombelets says you really don't need the overhead of WebForms and both the Model and Controllers are probably also more than you'll require which means you probably wont need the MVC framework either.

Title: Which asp.net technology fits this situation best?

Body:
I think I can count WebAPI out, but WebForms, WebPages, and MVC are all possibilities.

I want to create an asp.net web site that is primarily static content and links to other sites. The only "fancy" bit will be a Bing map with pushpins that I add - but even these are static. And there will be a photo gallery. Oh, and ads, too.

And, finally, it needs to work well on phones and tablets as well as desktop browsers.

Which asp.net technology "flavor" is most suited for this type of web site?

UPDATE

In VS 2012, Web Pages projects are not available beneath Templates | Visual C# | Web.

What is there:

```<code>ASP.NET Empy Web Application
ASP.NET Web Forms Application
ASP.NET MVC 3 Web Application
ASP.NET MVC 4 WebApplication
ASP.NET Dyanmic Data Entities Web Application
</code>```

Does this mean that Web Pages are passe, or that Web Pages and Web Forms are the same thing?


答:
The title of that article is intentionally disingenuous.  The author is making three points:  that linked list traversals and searches are slow, which is true, that most people don't realize how much slower they are than even linear array searches due to cache misses, which is probably true, and that most people don't take search time into account when selecting a linked list, which is probably false.

His benchmark program includes the search time together with adds and deletes, which is the disingenuous part.  When I select a linked list, the very first thing I ask myself is if the poor search time can either be worked around or if it is an acceptable trade off.  I think that is true of most people.

For example, the last time I used a linked list was when I needed to keep some items sorted by how recently they were last accessed.  The most common operation by far was moving an item from the middle of the list to the front, an O(1) operation for a linked list.  However, there's that pesky search time.  It turned out to be convenient to store a pointer to the linked list node in another data structure I needed anyway, so the searches would be O(1) as well.

However, in other circumstances, I have just kept the O(n) searches because the semantics of a linked list simplified the code, and the performance hit was negligible.  Your own test shows the difference measured in hundredths of a second for adding or deleting 4000 nodes.  For most applications that's completely unnoticeable.

The fact that you got different results than the author on his own benchmark is also very interesting, and illustrates well why you should do your own measuring.  Your compiler, operating system, and standard library implementation, and even the other processes running on your system can all make a significant difference in things like how many cache misses your code will generate.

Title: A question regarding linked list vs vector insert/remove results comparison

Body:
I was reading this blog post: http://kjellkod.wordpress.com/2012/02/25/why-you-should-never-ever-ever-use-linked-list-in-your-code-again/

and I found there a code to run: http://ideone.com/62Emz

I've compiled it using gcc 4.7.2 with g++ -std=c++11 on my old laptop with T5450 cpu with two cores with 32 Kbytes L1 cache each and 2 Megabytes of (common?) L2 cache and I have got this results:

```<code>********** Times in microseconds**********
Elements ADD (List, Vector)     ERASE(List, Vector)
100,     , 0, 0,                0, 0
200,     , 0, 0,                15625, 0
500,     , 0, 0,                0, 0
1000,    , 15625, 0,            0, 15625
4000,    , 109375, 140625,              46875, 31250
10000,   , 750000, 875000,              312500, 187500
20000,   , 2968750, 3468750,            1296875, 781250
40000,   , 12000000, 13843750,          5359375, 3156250
Exiting test,. the whole measuring took 45375 milliseconds (45seconds or 0 minut
es)
</code>```

Which actually says an opposite, at least for ADD operation comparing to what author of that blog post says. List is faster for ADD than Vector. What conclusions should I make from my results? Does it proof anything? What should I think or understand?


问:
Mutual exclusion over network - pattern?
I want to do the following:

I have a number of computers. On each computer a programm will run. There is no centralized server.

The program can choose by defined criteria to give another computer specified data. While doing so, the other computer should not do the same. (A sort of 2 way synchronize)

Let's make an example. (C1 .. Cn are the programs running on different computers)

C1 sends C2 updated data. While processing is active, C2 should not ask C1 for update something else.

The idea was:

C1 sends a message to C2: PauseExecution()
C1 sends to C2 items to be processed (updates some data on C2)
C1 sends a message to C2: ResumeExecution().
C2 sends a message to C1: PauseExecution()
C2 sends to C1 items to be processed (updates some data on C1)
C2 sends a message to C1: ResumeExecution().
But now the biggest problem arises.

If C1 sends a message to C2 to Pause, and C22 sends at the same tiem a message to C1 to Pause, both would block.

There is no centralized server / shared memory for keeping a semaphore.

Is there another pattern which can be used, so that n computers will not block?

So this question is about algorithmic exclusion.

Or is there another workaround for this problem, if no semaphore or mutex can be used?

答: There are a number of well-known algorithms for this.  Ricart-Agrawala appears to have the fewest issues.  Basically, instead of commanding another system to pause execution, you pause your own execution, send a request, and wait for a reply before unpausing.  Then you send another message when you're done executing the critical section.  The different algorithms have different ways of avoiding deadlock.</p>


答:
In general, the compiler can't detect such errors. Example: Suppose the constructor for some class allocates some data member using new TypeName[], but the destructor erroneously uses delete instead of delete[]. If the constructor and destructor are defined in separate compilation units, how is the compiler to know when compiling the file that defines the destructor that the usage is inconsistent with that in the separately compiled file that defines the constructor?

With regard to the GNU compilers, it doesn't. As noted above, it can't do so in the general case. A compiler doesn't have to detect such mismatched new/delete errors because this is undefined behavior. UB is the compiler vendor's "get out of jail free" card.

Tools such as valgrind can and do detect these kinds of new/delete mismatches, but do so at runtime. There might be a static analysis tool that looks at all of the source files that will eventually be compiled to form an executable, but I don't of any such static analysis tool that detect this kind of error.


问:
Algorithm for picking reasonable min/max vals given a single value
I am making a simplistic in-browser IDE for some very domain-specific coding. Because I like Bret Victor's thoughts on Learnable Programming so much I thought I'd throw in some draggable numbers ala Tangle.js (click here to see what I'm talking about).

My implementation is a much simpler slider input control but the idea is the same. One issue comes up however. The dragging slider needs values for min, max, and step. Since the values are user-entered I cannot hard code them. Currently I do {min: currentValue/10, max: currentValue*5} but this is so simplistic that it fails to make sense in a large class of cases.

What I would like is an algorithm (which I imagine would be just a simple calculation) that given a value for a number would make good guesses on min, max, and step values. (Or any 2 of those since getting the third would be trivial).

eg.

```<code>   fn(15) -> {min: 0, max: 35, step: 1}
   fn(1.478) -> {min: -2, max: 5, step: .2}
   fn(-7034) -> {min: -35000, max: -500, step: 100}
</code>```

Obviously it need not and cannot be perfect but I'm wondering if anyone has an idea for an algorithm or something mathy that makes sense here.

答:
I might try something like:

stepSize = abs(currentValue/numSteps);

offset = numSteps * stepSize / 2;

minValue = currentValue - offset;

maxValue = currentValue + offset;

Where you get to pick how many steps (your precision) that you want for the increment size of your progress bar.


答:
The trivial case which you show can be detected at compile time, because the instantiation and destruction of the object are in the same scope. In general, the deletion is no in the same scope, or even the same source file, as the instantiation.
And a C++ pointer's type does not carry information about whether it references a single object of its type or an array, let alone the allocation scheme. So it is not possible to diagnose this at compile time in general.

Why not diagnose the special cases that are possible?

In C++ there are already tools for dealing with leakage of dynamic resources that are tied to scopes, namely smart pointers and higher level arrays (std::vector).

Even if you use the correct delete flavor, your code is still not exception safe. If the code between the new[] and delete[] terminates by a dynamic exit, the deletion never executes.

As far as run-time detection goes, the Valgrind tool does a good job of detecting this at run-time. Watch:

```<code>==26781== Command: ./a.out
==26781==
==26781== Mismatched free() / delete / delete []
==26781==    at 0x402ACFC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==26781==    by 0x8048498: main (in /home/kaz/test/a.out)
==26781==  Address 0x4324028 is 0 bytes inside a block of size 80 alloc'd
==26781==    at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==26781==    by 0x8048488: main (in /home/kaz/test/a.out)
</code>```

Of course, Valgrind doesn't run on all platforms, and it's not always practical or possible to reproduce all run-time situations under the tool.

Body:
The trivial case which you show can be detected at compile time, because the instantiation and destruction of the object are in the same scope. In general, the deletion is no in the same scope, or even the same source file, as the instantiation.
And a C++ pointer's type does not carry information about whether it references a single object of its type or an array, let alone the allocation scheme. So it is not possible to diagnose this at compile time in general.

Why not diagnose the special cases that are possible?

In C++ there are already tools for dealing with leakage of dynamic resources that are tied to scopes, namely smart pointers and higher level arrays (std::vector).

Even if you use the correct delete flavor, your code is still not exception safe. If the code between the new[] and delete[] terminates by a dynamic exit, the deletion never executes.

As far as run-time detection goes, the Valgrind tool does a good job of detecting this at run-time. Watch:

==26781== Command: ./a.out
==26781==
==26781== Mismatched free() / delete / delete []
==26781==    at 0x402ACFC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==26781==    by 0x8048498: main (in /home/kaz/test/a.out)
==26781==  Address 0x4324028 is 0 bytes inside a block of size 80 alloc'd
==26781==    at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==26781==    by 0x8048488: main (in /home/kaz/test/a.out)

Of course, Valgrind doesn't run on all platforms, and it's not always practical or possible to reproduce all run-time situations under the tool.


答:
The keyword here is distributed transaction. Hit google with that and you'll find plenty of possible ways, but as Karl already said a two-phased commit is the traditional solution.

Given that there is no central authority, it makes sense to assume nothing about the other systems until you get an acknowledgment from them that they agree to your plans (first phase). Only when all the involved systems agree do they perform the transaction / data sending / whatever (second phase).

Depending on the amount of transfers you have and the number of systems involved, you have to take a closer look at possible cases of starvation though. Let's say that systems A and B continually want to send data to system C and more or less bombard it with first-phase commits, i.e. they ask system C if it is willing to accept a file from them. If you now want a system D to send a file to C, it might never get an acknowledgment depending on the specific implementation details' fairness.

Title: Mutual exclusion over network - pattern?

Body:
I want to do the following:

I have a number of computers. On each computer a programm will run. There is no centralized server.

The program can choose by defined criteria to give another computer specified data. While doing so, the other computer should not do the same. (A sort of 2 way synchronize)

Let's make an example. (C1 .. Cn are the programs running on different computers)

C1 sends C2 updated data. While processing is active, C2 should not ask C1 for update something else.

The idea was:

C1 sends a message to C2: PauseExecution()
C1 sends to C2 items to be processed (updates some data on C2)
C1 sends a message to C2: ResumeExecution().
C2 sends a message to C1: PauseExecution()
C2 sends to C1 items to be processed (updates some data on C1)
C2 sends a message to C1: ResumeExecution().
But now the biggest problem arises.

If C1 sends a message to C2 to Pause, and C22 sends at the same tiem a message to C1 to Pause, both would block.

There is no centralized server / shared memory for keeping a semaphore.

Is there another pattern which can be used, so that n computers will not block?

So this question is about algorithmic exclusion.

Or is there another workaround for this problem, if no semaphore or mutex can be used?


问:
Unable to convince on data hiding
I am working on a Selenium + java project where all Web Element in a class are declared as -

```<code>public class CheckoutPaymentConfirmpage extends WebPage{

public final Button btnPrintorder = new Button("//input[@id='but_Print']");
public final TextField txtpassword = new TextField("password", "//input[@id='pass']");

    // Some more elements here
    // Some page object methods here
}
</code>```

Now when ever test need to access these elements they are directly invoked over the object of CheckoutPaymentConfirmpage class
What ever little java (or OOPS) I know, has taught me that members should be as hidden as possible. Hence I would have had btnPrintorder and txtpassword declared private and would access them using getters or would have created methods in page object class to be used by tests.

But when I convey this to others they don't see much value in it as state of instance variable (i.e. btnPrintorder etc) would not be changed from one object to another for page object class (i.e. CheckoutPaymentConfirmpage etc)

Hence in this situation, is it ok to leave instance variable as public?

答:
You misunderstand implementation hiding if you think that making members private, but providing getters and setters, is information hiding.

If I'm using your class, and I have a way of directly accessing a member via a getter, or overwriting that member with a setter, then it isn't information hiding. Your class is acting as a dumb container for members that I can manipulate quite directly.

Yes, the getter and setter can do some neat things, like trigger certain actions. Maybe the getters and setters can be rewritten to be remote procedure calls to a server in Russia. But those neat things are not information hiding. They don't hide how the class is implemented, only some details about how that specific member is implemented.

In any case, in decent programming languages, if you need that kind of abstraction for member access, you can just start out by leaving an ordinary member accessible, and then later add getter and setter methods which hook into the ordinary access syntax. That is to say, an assignment like obj.memb = foo actually triggers a setter, and evaluation of obj.memb triggers a getter. Getters-setters versus direct evaluation and assignment syntax is therefore only an issue of syntax, whereas implementation hiding has to do with semantics, and revolves around providing no access to members whatsoever. An object which hides its implementation can only be manipulated by methods on that object, none of which provide direct access to any members.

Title: Unable to convince on data hiding


问:
Implementing cache system in Java Web Application
I worked with JPA (Eclipselink implementation) and Hibernate. As I understand these two have great caching systems.

I am interested in caching in a Web application and in order to better understand the process I'm trying to implement something on my own.

Sadly, I cannot find any in depth documentation about this subject. I'm interested in things like high scalability, sharing memory on different machines and other important theoretical matters. Is there any tutorial or open project I could check out?

Thank you!

*LE: * I want to cache DB information in POJOs just like JPA or Eclipselink

答:
Ehcache is a widely used open-source caching provider for Java with lots of features including replication, and works very well as a second-level cache for Hibernate.

Reading their doc and browsing their source should give you a good start.


答:
I can think of a few things you could try. You're going to have to experiment though - what works best in most situations is going to largely be based on how it feels to use:

Use your current formula, but tweak those constants.

Base the step size on the number of digits in the current/previous value, rather than the actual value. I imagine this might be a little more intuitive for users.

If you aren't already, you might want to try dynamically updating your min/max/step values based on the current value, rather than the previous value.

If your step size doesn't have to be constant, try increasing it based on the difference between the current value and the previous value.

You might be able to get some use out of Benford's Law: use a smaller step size if the first digit of the current/previous value lower. Basically you could try using a smaller range & step size if the first digit is lower. This might be confusing for users though!

...Where by current value I mean the currently-selected value. By previous value I mean the value as it was when the user started manipulating it (i.e. clicked on it in the Tangle.js example).

Title: Algorithm for picking reasonable min/max vals given a single value

Body:
I am making a simplistic in-browser IDE for some very domain-specific coding. Because I like Bret Victor's thoughts on Learnable Programming so much I thought I'd throw in some draggable numbers ala Tangle.js (click here to see what I'm talking about).

My implementation is a much simpler slider input control but the idea is the same. One issue comes up however. The dragging slider needs values for min, max, and step. Since the values are user-entered I cannot hard code them. Currently I do {min: currentValue/10, max: currentValue*5} but this is so simplistic that it fails to make sense in a large class of cases.

What I would like is an algorithm (which I imagine would be just a simple calculation) that given a value for a number would make good guesses on min, max, and step values. (Or any 2 of those since getting the third would be trivial).

eg.

```<code>   fn(15) -> {min: 0, max: 35, step: 1}
   fn(1.478) -> {min: -2, max: 5, step: .2}
   fn(-7034) -> {min: -35000, max: -500, step: 100}
</code>```

Obviously it need not and cannot be perfect but I'm wondering if anyone has an idea for an algorithm or something mathy that makes sense here.


问:
Microsoft Public License vs MIT?
I'm working with a new plugin (flexbox), and I ran into the MS-PL license, which I had not run into before.

In the past, I've used mainly MIT and Apache licensed projects, so I have no idea what the main differences are with this one.

Here's a link to it: http://opensource.org/licenses/MS-PL

Can anyone help explain the differences to me? I'm usually wary of Microsoft, so the fact that this product comes with this makes me nervous.

答:
There's a pretty good answer on Stack Overflow: https://web.archive.org/web/20150901065118/https://stackoverflow.com/questions/1424307/how-does-ms-pl-license-work

There's also a decent article on CMS Wire: http://www.cmswire.com/cms/web-development/taking-a-closer-look-at-microsofts-mspl-open-source-license-004248.php

The short version of those is essentially that code under this license can be used or modified freely by anybody. If you choose to use or modify code released under this license, it must be provided under the same license. So if you use a library in a project, the rest of the project doesn't need to be distributed under that license, but the library does. And if you make modifications to the code under MS-PL, those modifications must also follow that license.

OwnerDisplayName: streetlight

Title: Microsoft Public License vs MIT?

ContentLicense: CC BY-SA 4.0


问:
What should junior developer expect from their senior team lead
Disclaimer: Opinions expressed are solely my own and do not express the views or opinions of my employer.

I work for a small company, in which few people are  developers, others are QA/Test and 1 is a Manager. I joined this company 1.5 years ago. 3 senior developers have 8+ years of experience.

These are the observations which I made about the team lead. (considering me as a fresher with less experience compared to them in all aspects )

They never discuss 1:1 or they never consider the junior suggestion (I agree that it's up to them, whether they accept it or not, at least they should consider an opinion).

As senior team leader they can try to refactor the codebase with new technologies ( including the factor of rolling out new technologies is possible and other developer and infrastructure also ready), but these team leader feel less in-secure to work with new technologies, as they are not up to date. (reason I am telling, they don't know what current programming trend, *(such as popular open source projects like modernizr, bootstrap and many others).

In our codebase more than 10000+ lines are repeated, so I told them  about DRY: Don't Repeat yourself.  Their reply was : "It is a fascinating article, but never works in practice".  I just told them if we do not make it 100% DRY, we can at least use interfaces, but that also was not considered. *(interfaces can be added for new features, not touching the previous codebase, if they are not ready to refactor)

All senior developers do maintenance and hot fixing of patches. The rest of the time they just spend on entertainment sites. They are just happy to finish the task.

Introducing new technology is bad? *(including factor of feasibility can be done).

Manager also least concerned about the things which I am talking about.

Junior expects they can learn many things from team lead. *(not by asking help or senior coding for them).

My questions are:

Am I too aggressive about the changes which I am proposing?

What should I expect from senior dev leads who have 8+ years experience?

Am I wrong to expect to learn and gain experience from a company?

Update :

Why they feel DRY is impractical: because they don't want get involved with OOP concepts. They are happy with repeating tasks.

New technologies I am proposing:

Usage of Minification of CSS, JS, SPrite images

Usage of Interfaces and .net framework 4, generics and many others.

Client side libraries such as modernizr, knockout js, bootstrap for responsive,

答:
Do you work at my company?

No but seriously, this seems to be a pretty common thread in many large companies. Change is hard, and EXPENSIVE. Sometimes you don't really know how much until your in the middle of it and its too late to go back.

For instance my company is still migrating from cobol based mainframe screens to java. It is hard to sell someone on Spring or JSF when they are still trying to get their tech up to date with standards from ten years ago. So, I will tell you what I have done that has had some limited success (I'm a jr dev too). Be the example. It's not good enough that you know your more cutting edge, you have to prove it. When everyone else is goofing off bring in a book to read if you have down time. And make it about one of these techs your interested in implementing. If they see you reading it while they are watching youtube (honestly surpised your operations unit doesn't catch that and people get fired) they will be more inclined to not only believe you know what your talking about, but may even ask you what your reading.

As an example I'll tell you about my experience with my senior architect. Smart guy, but generally not interested in new tech. I went and asked him about how to do something in CVS (our version control) and mentioned "Oh ok, I'm used to using subversion, and they do it this way. thanks for your help." This lead to several conversations about CVS and Ant
vs. SVN and Maven, leading up to him borrowing a couple of books out of my library to check it out. End Result: we're going to move to the new systems sometime this year. The key is to be open and helpful without conveying that they are doing it wrong. Because after all there may be plenty of better ways to do it but if it is working correctly then they are not doing it the wrong way. Any type of disrespect will land you in hot water in most cases so watch out for that.

If they just aren't receptive, keep in mind that your in a great field that is in high demand. If your inquisitive and a quick learner you WILL find another job, probably one you will enjoy a whole lot more. Which is as important as the money to me. Be sure to mention in any interview, "Oh you guys use xxx technology? That's awesome, I've always wanted to use that and tried at my old company." Poeple love when you have enthusiasm for what they are doing.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: That commenting code is unnecessary, or that "good code doesn't need comments". Sometimes you need to explain what a complex bit of code is doing. Furthermore, commenting sections of code helps you skim read much more effectively.</p>


问:
How do you unit test an encoder?
I have something like this:

```<code>public byte[] EncodeMyObject(MyObject obj)
</code>```

I've been unit testing like this:

```<code>byte[] expectedResults = new byte[3]{ 0x01, 0x02, 0xFF };
Assert.IsEqual(expectedResults, EncodeMyObject(myObject));
</code>```

EDIT: The two ways I've seen proposed are:

1) Using hardcoded expected values, like the above example.

2) Using a decoder to decode the encoded byte array and comparing the input/output objects.

The problem I see with method 1 is that it is very brittle and requires a lot of hard coded values.

The problem with method 2 is that testing the encoder depends on the decoder working correctly. If the encoder/decoder are broken equally (in the same place), then the tests could produce false positives.

These may very well be the only ways to test this type of method. If that's the case then fine. I'm asking the question to see if there are any better strategies for this type of testing. I can not reveal the internals of the particular encoder I am working on. I am asking in general how you would solve this type of problem, and I don't feel the internals are important. Assume that a given input object will always produce the same output byte array.

答:
Depends. If the encoding is something completely fixed, where every implementation is supposed to create exactly the same output, it doesn't make sense to check anything other than verify that example inputs map to exactly the expected outputs. That is the most obvious test, and probably also the easiest to write.

If there is wiggle room with alternative outputs, as in the MPEG standard (e.g. there are certain operators you can apply to the input, but you are free to trade off encoding effort versus output quality or storage space), then it's better to apply the defined decoding strategy to the output and verify that it's the same as the input - or, if the encoding is lossy, that it's reasonably close to the original input. That is harder to program, but protects you against any future improvements that may be made  to your encoder.

Title: How do you unit test an encoder?


问:
Use Cases with respect to downstream systems
Use cases are primarily meant for interaction between user and a system. It could be used for interaction between system and another system. The actors are primarily roles.

It is easy to document the use cases for a front end application like a portal where in all the activities and role performing the activity could be defined. However if the system is an order management or provisioning system which a downstream system how could the use cases be documented?

Example: An order management application may responsible for processing orders for type new install , change of service , cancel , reschedule , suspend , restart etc.These transactions could be triggered by from different sources by different means (service call , entry placed in db which OM application polls , order placed in jms queue - however I assume these have no relation to use case). Once an order is received Order Management application might have to interact with different applications (credit check , shipping , provisioning , activation , billing etc) depending on the order type.

I have an application that receives data from an upstream application. My application consumes webservices exposed by multiple other applications in order to fulfill a task. The data flows through multiple applications before reaching the upstream system which sends messages to my application. The activities that my application does are install, disconnect , suspend, restore etc using multiple services that it consumes.

When I read posts on having system as actors, the primary aim seems to be demarcating and defining the interfaces properly. In the scenario above assuming the upstream system is A, my application is B and the applications that my application consumes are C, D, and E.

My aplication performs install , disconnect , restrat and suspend. Are these the activities?

Will the primary actor be the system sending messages to my application? I can't think of this as a role and also there no interaction between the upstream application and my application after the point when my application recieves a message.

How can I define the external applications that my application consumes? as actor or activity? or i need not care about these in use case diagram?

When you take an interaction between user and a system for shopping a product - you will list the series of interations between you and the software. However what software does internally is not specified.

Here in my case , since it is a downstream system , the upstream system sends only one message and there is no series of interaction. Hence I am in a quandry as to how I should define the scenarios.

答:
For a use case the Actor can easily be a:

User

System (self-reference)

System (external reference)

... (I'm sure there's others I'm not thinking of right now)

The problem that you're running into is that you are assuming that an Actor can only be a User.  In reality, the Actor is just the agent that triggers some sequence of events.  System to System use cases are quite common, and are the solution to your challenge.


问:
Design Pattern For Util Classes and General Static Variables
I am developing a Mojo(think it as just a usual class) for my custom Maven Plugin. There is an Abstract Mojo at top. I have some other custom Mojos in example which makes server side includes. I have some static variables and some util methods in example get operating system name, fix file separator in order to used operating system etc. I have created an abstract Base Mojo that extends Abstract Mojo and put every common things inside it. When I create a Mojo (i.e. server side includer) I extend it from my Base Mojo. However should I think that I should separate variables and util methods or not and what kind of pattern I should follow.

To make it clear there is:

AbstractMojo at top by default (I can not change it)

BaseMojo an abstract class that extends AbstractMojo that has util methods and static system variables

CustomMojo extends BaseMojo and does its responsibility.

Any ideas how to implement a design for my needs?

答:
I'm wondering, why this was migrated. But anyway:

You shouldn't put everything in a base mojo. That practically makes reusing that code impossible. Just think of the mojo growing and you need to split that mojo up into separate classes. You can't do that if that code has a dependency on the base class of the mojo.

You should create services that provide the functionality you currently have in your base mojo. They are reusable and therefore accessible from other places.

As a general rule of thumb:

YAGNI - You aint gonna need a member declaration in a class that is only intendend to be used by deriving classes. How do you know that it is really used?

OwnerDisplayName: kamaci


问:
Question on System Requirement
I have a scenario where a specific webservice must be consumed based on the state to setup user info. For instance if the state is NY or NJ call service A , if state is WA call service B etc. But specifying what service must be called is I guess is "HOW" to setup a user info and not a "WHAT".

So should I just have single requirement stating system must have the capbality to setup up user info based on state?

EDIT: I would also like to add that the services implemented for different states might want different info to be provided in addition to basic details such as first name and last name. Should the services , input to the services , output from the service , what the program needs to do with the output etc be part of system requirements? I guess all these deal with "HOW" more than "WHAT" - hence is it in the requirements realm?

答:
Correct, you'll want to start with a single requirement like:

System must have the capability to register user information based upon geographical state

As that phrasing avoids the particulars about how the information is supposed to be registered.

It also allows the generation of a main service InitialRegistration() that pulls common information for all the cases along with the geographic state.  From there, InitialRegistration() can call StateSpecificRegistration() without the client application or end user having to worry about what to do.

Title: Question on System Requirement


答:
Depending on the testing framework and paradigm you're using, you can still use the Arrange Act Assert pattern for this like you've said.

```<code>[TestMethod]
public void EncodeMyObject_ForValidInputs_Encodes()
{
    //Arrange object under test
    MyEncoder encoderUnderTest = new MyEncoder();
    MyObject validObject = new MyOjbect();
    //arrange object for condition under test

    //Act
    byte[] actual = encoderUnderTest.EncodeMyObject(myObject);

    //Assert
    byte[] expected = new byte[3]{ 0x01, 0x02, 0xFF };
    Assert.IsEqual(expected, actual);
}
</code>```

You should know requirements for EncodeMyObject() and can use this pattern to test against each of them for valid and invalid criteria, by arranging each of them and hardcoding the expected result for expected, similarly for the decoder.

Since the expected are hard coded, these will be fragile if you've got a massive change.

You may be able to automate with something parameter driven (have a look at Pex) or if you're doing DDD or BDD have a look at gerkin/cucumber.

Title: How do you unit test an encoder?

Body:
I have something like this:

```<code>public byte[] EncodeMyObject(MyObject obj)
</code>```

I've been unit testing like this:

```<code>byte[] expectedResults = new byte[3]{ 0x01, 0x02, 0xFF };
Assert.IsEqual(expectedResults, EncodeMyObject(myObject));
</code>```

EDIT: The two ways I've seen proposed are:

1) Using hardcoded expected values, like the above example.

2) Using a decoder to decode the encoded byte array and comparing the input/output objects.

The problem I see with method 1 is that it is very brittle and requires a lot of hard coded values.

The problem with method 2 is that testing the encoder depends on the decoder working correctly. If the encoder/decoder are broken equally (in the same place), then the tests could produce false positives.

These may very well be the only ways to test this type of method. If that's the case then fine. I'm asking the question to see if there are any better strategies for this type of testing. I can not reveal the internals of the particular encoder I am working on. I am asking in general how you would solve this type of problem, and I don't feel the internals are important. Assume that a given input object will always produce the same output byte array.

Body:
Depending on the testing framework and paradigm you're using, you can still use the Arrange Act Assert pattern for this like you've said.

[TestMethod]
public void EncodeMyObject_ForValidInputs_Encodes()
{
    //Arrange object under test
    MyEncoder encoderUnderTest = new MyEncoder();
    MyObject validObject = new MyOjbect();
    //arrange object for condition under test

    //Act
    byte[] actual = encoderUnderTest.EncodeMyObject(myObject);

    //Assert
    byte[] expected = new byte[3]{ 0x01, 0x02, 0xFF };
    Assert.IsEqual(expected, actual);
}

You should know requirements for EncodeMyObject() and can use this pattern to test against each of them for valid and invalid criteria, by arranging each of them and hardcoding the expected result for expected, similarly for the decoder.

Since the expected are hard coded, these will be fragile if you've got a massive change.

You may be able to automate with something parameter driven (have a look at Pex) or if you're doing DDD or BDD have a look at gerkin/cucumber.


问:
Trailing slash in RESTful API
I have been having a debate about what to do with a trailing slash in a RESTful API.

Lets say I have a resource called dogs and subordinate resources for individual dogs. We can therefore do the following:

```<code>GET/PUT/POST/DELETE http://example.com/dogs
GET/PUT/POST/DELETE http://example.com/dogs/{id}
</code>```

But what do we do with the following special case:

```<code>GET/PUT/POST/DELETE http://example.com/dogs/
</code>```

My personal view is that this is saying send a request to an individual dog resource with id = null. I think the API should return a 404 for this case.

Others say the request is accessing the dogs resource i.e. the trailing slash is ignored.

Does anyone know the definitive answer?

答:
None of this is authoritative (as REST has no exact meaning). But from the original paper on REST a full (not ending in /) URL names a resource, while one ending in a slash
'/' is a resource group (probably not worded like that).

A GET of a URL with a slash on the end is supposed to list the resources available.

```<code>GET http://example.com/dogs/          /* List all the dogs resources */
</code>```

A PUT on a URL with a slash is supposed to replace all the resources.

```<code>PUT http://example.com/dogs/          /* Replace all the dogs resources */
</code>```

A DELETE on a URL with a slash is supposed to delete all the resources

```<code>DELETE http://example.com/dogs/       /* Deletes all the dogs resources */
</code>```

A POST on a URL with a slash is supposed to create a new resource can then be subsequently accessed. To be conformant the new resource should be in this directory (though lots of RESTful architectures cheat here).

```<code>POST http://example.com/dogs/        /* Creates a new dogs resource (notice singular) */
</code>```

etc.

The Wikipedia page on the subject seems to explain it well:
https://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services.

Title: Trailing slash in RESTful API

Body:
None of this is authoritative (as REST has no exact meaning). But from the original paper on REST a full (not ending in /) URL names a resource, while one ending in a slash
'/' is a resource group (probably not worded like that).

A GET of a URL with a slash on the end is supposed to list the resources available.

GET http://example.com/dogs/          /* List all the dogs resources */

A PUT on a URL with a slash is supposed to replace all the resources.

PUT http://example.com/dogs/          /* Replace all the dogs resources */

A DELETE on a URL with a slash is supposed to delete all the resources

DELETE http://example.com/dogs/       /* Deletes all the dogs resources */

A POST on a URL with a slash is supposed to create a new resource can then be subsequently accessed. To be conformant the new resource should be in this directory (though lots of RESTful architectures cheat here).

POST http://example.com/dogs/        /* Creates a new dogs resource (notice singular) */

etc.

The Wikipedia page on the subject seems to explain it well:
https://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services.


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答:
The Annotated Turing

Just picturing someone designing such complex methods & algorithms almost a century ago gets me motivated.


问:
Is it possible to avoid enormously big switch in that case?
I'm writing a simple chess-related code with intention to write it clearly (performance doesn't matter at all). And this method I have doesn't look clean to me at all:

```<code> public static Piece GetClosestPiece(Square squareFrom, Direction direction)
    {
        //TODO: rework this mess
        switch (direction)
        {
            case Direction.Top:
                return
                    _pieces.Where(p => p.Square.OnVerticalWith(squareFrom))
                           .OrderBy(p => p.Square.Y)
                           .First(p => p.Square.Y > squareFrom.Y);
            case Direction.Bottom:
                return
                    _pieces.Where(p => p.Square.OnVerticalWith(squareFrom))
                           .OrderByDescending(p => p.Square.Y)
                           .First(p => p.Square.Y < squareFrom.Y);
            case Direction.Right:
            <...>
            case Direction.TopLeft:
                return
                    _pieces.Where(p => p.Square.OnBackslashWith(squareFrom))
                           .OrderByDescending(p => p.Square.X)
                           .First(p => p.Square.X < squareFrom.X);
            default:
                throw new InvalidEnumArgumentException();
        }
    }
</code>```

I store the pieces as list, so, here I'm using LINQ to find the piece closest to a given square on a given direction.

Do switch/if statements of this size (8 cases total here) always present a code smell?

Is there any way to refactor this part only, or should I consider reviewing the design of the whole solution?

答:
1. Do switch/if statements of this size (8 cases total here) always present a code smell?

The size of the switch doesn't particularly matter, the number of times you have the switch does. If you are repeating yourself with this switch, it could or should indicate you need a better design perhaps using polymorphism. If your switch lives here and only here, then you might just live with it.

2. Is there any way to refactor this part only, or should I consider reviewing the design of the whole solution?

See point #1 about when to certainly consider a different approach. As for more immediate refactorings, at least consider extracting the bodies of the "case" code to delegate elsewhere.

```<code>case Direction.Top:
     return GetFromTop(_pieces);
case Direction.Bottom:
     return ...
</code>```

Keep your one method concerned only with the switch, have other methods concerned with the appropriate filtering and ordering.

Body:
1. Do switch/if statements of this size (8 cases total here) always present a code smell?

The size of the switch doesn't particularly matter, the number of times you have the switch does. If you are repeating yourself with this switch, it could or should indicate you need a better design perhaps using polymorphism. If your switch lives here and only here, then you might just live with it.

2. Is there any way to refactor this part only, or should I consider reviewing the design of the whole solution?

See point #1 about when to certainly consider a different approach. As for more immediate refactorings, at least consider extracting the bodies of the "case" code to delegate elsewhere.

case Direction.Top:
     return GetFromTop(_pieces);
case Direction.Bottom:
     return ...

Keep your one method concerned only with the switch, have other methods concerned with the appropriate filtering and ordering.


答:
Have a look at the typesafe enum pattern and the command pattern. Don't use a C# enum in that case, but an interface.

```<code>interface Direction {

    // implements a single case in your switch
    public Piece Closest(Collection<Piece> pieces);

}
</code>```

So you just need to do:

```<code>Directions.ValueOf(someDirectionLiteral).Closest(_pieces)
</code>```

The Directions.ValueOf call maps a literal (a string or whatever) to an instance of the Direction interface.

The code may not be valid C#, but you should get.

Title: Is it possible to avoid enormously big switch in that case?

Body:
I'm writing a simple chess-related code with intention to write it clearly (performance doesn't matter at all). And this method I have doesn't look clean to me at all:

```<code> public static Piece GetClosestPiece(Square squareFrom, Direction direction)
    {
        //TODO: rework this mess
        switch (direction)
        {
            case Direction.Top:
                return
                    _pieces.Where(p => p.Square.OnVerticalWith(squareFrom))
                           .OrderBy(p => p.Square.Y)
                           .First(p => p.Square.Y > squareFrom.Y);
            case Direction.Bottom:
                return
                    _pieces.Where(p => p.Square.OnVerticalWith(squareFrom))
                           .OrderByDescending(p => p.Square.Y)
                           .First(p => p.Square.Y < squareFrom.Y);
            case Direction.Right:
            <...>
            case Direction.TopLeft:
                return
                    _pieces.Where(p => p.Square.OnBackslashWith(squareFrom))
                           .OrderByDescending(p => p.Square.X)
                           .First(p => p.Square.X < squareFrom.X);
            default:
                throw new InvalidEnumArgumentException();
        }
    }
</code>```

I store the pieces as list, so, here I'm using LINQ to find the piece closest to a given square on a given direction.

Do switch/if statements of this size (8 cases total here) always present a code smell?

Is there any way to refactor this part only, or should I consider reviewing the design of the whole solution?

Body:
Have a look at the typesafe enum pattern and the command pattern. Don't use a C# enum in that case, but an interface.

interface Direction {

    // implements a single case in your switch
    public Piece Closest(Collection<Piece> pieces);

}

So you just need to do:

Directions.ValueOf(someDirectionLiteral).Closest(_pieces)

The Directions.ValueOf call maps a literal (a string or whatever) to an instance of the Direction interface.

The code may not be valid C#, but you should get.


问:
Java Generics - how to strike a balance between expressiveness and simplicity
I'm developing some code that utilizes generics, and one of my guiding principles was to make it usable for future scenarios, and not just today's. However, several coworkers have expressed that I may have traded off readability for the sake of extensibility. I wanted to gather some feedback about possible ways to resolve this.

To be specific, here is an interface that defines a transform - you start with a source collection of items, and you apply the transform to each element, storing the results in a destination collection. Additionally, I want to be able to return the destination collection to the caller, and rather than forcing them to use a Collection reference, I want them to be able to use whatever collection type they actually provided for the destination collection.

Finally, I make it possible for the type of items in the destination collection to be different from the type of items in the source collection, because maybe that's what the transform does. In my code, for instance, several source items make up one destination item after the transform.

This yields the following interface:

```<code>interface Transform<Src, Dst> {
    <DstColl extends Collection<? super Dst>> DstColl transform(
                Collection<? extends Src> sourceCollection,
                DstColl                   destinationCollection);
}
</code>```

I tried to be all nice and apply Josh Bloch's PECS principle (producer extends, consumer super) to make sure the interface is usable with super- and sub-types where appropriate. The end result is somewhat of a monstrosity.

Now, it would have been nice if I could extend this interface and specialize it somehow. For example, if I don't really care about playing nice with subtypes of the source items and supertypes of the destination items, I could have:

```<code>interface SimpleTransform<Src, Dst> {
    <DstColl extends Collection<Dst>> DstColl transform(
                  Collection<Src> sourceCollection,
                  DstColl         destinationCollection);
}
</code>```

But there is no way to do that in Java. I want to make implementations of this interface something that others would actually consider doing, as opposed to running in fear. I've considered several options:

Don't return the destination collection. Seems weird given that you do a transform but get nothing back.

Have an abstract class that implements this interface, but then translates the parameters to something easier to use and calls another method "translateImpl()" which has the simpler signature and thus presents less of a cognitive burden for implementers. But then it's weird to have to write an abstract class just to make an interface user-friendly.

Forgo extensibility and just have the simpler interface. Possibly couple that with not returning the destination collection. But then that limits my options in the future.

What do you think? Am I missing an approach I could use?

答:
I personally do not see much problem with the way you've defined your interface, however I am used to toying with Generics and I can understand that your coworkers would find your code to be a bit of a mouthful if that is not their case.

If I were you, I would go with the third solution you state: make things simpler at the expense of potentially having to go back to it later. Because after all, maybe you won't have to in the end; or you would end up being able to use it fully at some point, but not enough to make up for the effort you've put into making this interface so generic, as well as the effort your coworkers may have made to wrap their heads around it.

Another thing to consider is how often you use this interface, and at which level of complexity. Also, how useful this interface proves to be in your project(s). If it allows for high reusability of some components (and not just potential, but actual), it is a good thing. If a much simpler interface works as well 90% of the time, you could ask yourself whether for the remaining 10% a complex interface would prove useful or not.

I do not think it would be a very good idea to not use super and extend, though if you can do without them for the moment, I am sure your colleagues won't mind seeing them disappear. However, do you really have so many situations where you need to change the type of Collection as well?

Some already given advices are really good, and I agree with Frank about following the YAGNI principle unless you have very good reasons not to. You can still change the code when the need for more complexity will arise, but it is not of much use to develop things you are not pretty sure will be used soon. Also, Martijn's advice of using Guava is one to consider seriously. I haven't had the opportunity to use it yet, but I have heard a lot of good about it, including in a presentation where the Transformer pattern got discussed (you can watch it online on InfoQ if you are interested).

As an aside, wouldn't it be better in your current interface to have destinationCollectionbe of type Class<DstColl>?


问:
Wrote an application for a friend. Who is the owner of the software?
Friend asked me to develop a software application for him. I did and he paid me.
There was no written contract. I live in UK and he resides in Canada.

My question is: who is the owner of the software now?
Can my friend make and sell copies without my permission? Can I do the same?

I'm asking this because another person also wants to buy it, but friend insists on receiving some kind of sale commission, because the software was originally written at his request.

答:
Without a contract in place, most common law says that the program and copyright to the code belong to your friend.  Essentially, he employed you for a task and paid for your labor so you were his employee*.

And that implies that you aren't allowed to sell a copy to a second friend since you don't own that application.  Your first friend owns it.

However, it also depends upon the verbal (IM'd, or email'd) terms that you guys agreed to when specifying the project.  Verbal contracts are a pain to sort out because it's a you-said vs. he-said argument.  But if your first friend agrees that you also still "own" the software then you could sell it to your second friend.

In my opinion, the right thing to do would be to give your first friend a cut of the sale.  Ideally, he's not asking for all of the sale, but he could be entitled to make the claim.  You should also discuss what limits there will be for any additional sales that might occur.  Hopefully, you'll come to an amicable agreement.

Legally, there's probably not much that can occur.  You're in completely separate jurisdictions, and I'm willing to be that the sums involved are not enough to justify an international lawsuit.  Worst case is that you'll have lost a friend, and perhaps with some hard feelings.

Talk it over with your first friend and find an amicable agreement.  He does have a basis for his claims.

Update:

There is a huge distinction to be made between an application that was created under terms of employment and an application that was commissioned.

If the work was created under terms of employment, an implied contract in this case, then the copyright would belong with your first friend who paid you to write the program.  US law recognizes the term "work-for-hire" as an employment term.  Canadian law regrettably acknowledges the US term due to the number of Canadian | US contracts, but it's not a preferred term within Canadian contract law.

On the other hand, if the work was created under terms of a commission then full copyright remains with you, the creator of the work.

And there's one more slightly crazy exception to all that.  If your friend was requesting the work on behalf of the Canadian Crown then all copyright would belong to the Crown.

The nuances between creation under employment versus creation from a commission are ones that an attorney would have to settle for you.  That sort of determination is well outside the scope of what Programmers can offer.

Also off-topic, but slightly interesting, is that photographs and illustrations have a whole gamut of exceptions to the copyright provisions of commissioned work.

For some not-so-casual reading, here are some additional references.

The link to the UK's IPO on this subject

Hat tip to Bart van Ingen Schenau for the reference

A UK & Ireland specific article regarding Copyright for custom code

An article from the NZ Ministry of Economic Development discussing the effects of copyright and commissioned work

A site from the U of Saskatchewan confirming copyright belonging to first author for commissioned works

A link to the CA Association of Professional Image Creators discussing some of the nuances of commissioned photographs and illustrations


问:
How to manage single software product to multiple customers?
We have developed one product for payroll processing. We have 10+ customers who are using this software product.

Our existing and new customers are giving us customization changes w.r.t. their needs, and now we are facing the problem of product management. Please give some guidelines to us.

How to manage single software product to multiple customers?

Software developement details :

Front End Tools : Visual Studio 2008 (ASP.net web application)

Source Code Mangement : Visual Source Safe (VSS)

Back End : Sql Server 2005

Team Size: 12

答:
This is one of those times where you want to look at configurable options.  I know this is an anti-pattern for some cases, but not in this case.

What you need to identify is the areas that clients are looking for customization.  Make those the points where you break out configuration files or put values into a configuration db.

Don't go overboard, try to keep the sales team in check with what you can and cannot customize.  I have seen this too and it gets very messy very fast.

If these types of configurations are not possible, look at creating interfaces to services or libraries that contain the common code between all clients and the code that is unique.  Again the sales team needs to know where these lines are and how expensive it is going to be to create each customization.


答:
I have found a podcast that talks about these issues.  Maybe this will be useful for you to listen to.

In this episode Michael interviews one of our regular listeners: Petri Ahonen. Petri introduces Software Configuration Management by defining key terms and describing relevant concepts

Body:
We have developed one product for payroll processing. We have 10+ customers who are using this software product.

Our existing and new customers are giving us customization changes w.r.t. their needs, and now we are facing the problem of product management. Please give some guidelines to us.

How to manage single software product to multiple customers?

Software developement details :

Front End Tools : Visual Studio 2008 (ASP.net web application)

Source Code Mangement : Visual Source Safe (VSS)

Back End : Sql Server 2005

Team Size: 12


问:
Implementing chat in 2013
I played a bit with WebSockets and started to implement a tiny chat. Last time I did something like this was when there was no such thing as threads and computers had single core. I started to think how to implement it with todays programming patterns but I didn't come to any final conclusion.

How you implement chat's main functionality in today's technics in higher level?

I now have context Server, Socket and User. User has states Undefined, Connected, InChat, ToBeDisconnected, Disconnected, My main problem is the user maintenance:

If user hasn't said "hello" in 5 seconds after connection was opened -> disconnect

User is not replied to "ping" with "pong" at all or at least 2 minutes -> disconnect

User has been connected over 12 hours -> disconnect

User haven't been assigned profile (nickname and/or other details) after 5 minutes of connect -> disconnect

Some other program specific flag that kicks out user is triggered -> disconnect

My current implementation is like how it was done in olden days. ie. I have

```<code>while(serverRunning)
{
  foreach(socket in allSockets)
  {
    user = allUsers.findUserBySocket(socket);
    doMaintenance(user);
  }
}
</code>```

Now this runs far too many times and locks and blocks allUsers and allSockets way too much.

How this is implemented today? Like this for example?

Socket connects

Add to allSockets

Add to allUsers

Start per-user thread that runs every x seconds and runs user.doMaintenance()?

Or there's per-user queue that gets injected with actions like doPongCheckAction, doProfileTimeoutCheckAction, etc every x seconds (also needs per-user thread which constantly empties user's queue)?

Or there's Maintenance thread that runs every x second after last run and iterates through allUsers (a bit like current implementation)?

Or there's thread that injects actions to all users queues when there's been too long when same kind of action were ran and other thread that iterates through all users and empties user's queue?

Or something else or which is not even based on queues? :)

答: I would do it with one or more timers per user that fire off an event.  For example, you could set a pingMissed(user) function to be called every two minutes, which disconnects the user.  Every time you receive a ping response from that user, you reset the timer for another two minutes.  Timers are supported by the operating system, and use very few resources while waiting.

Title: Implementing chat in 2013


答:
Check out architectural patterns like PubSub or Enterprise Service Bus. Chat rooms can easily be modeled along those lines. A client would connect to the broker and register itself, subscribing to published updates. Also, consider using an established protocol to manage these connections, subscriptions and registrations, something like PubSubHubbub or XMPP are established enough to have thought of issues and edge-cases you haven't yet, but open enough to let you write your own server, using them as a medium only.

To remain scalable, I would avoid any architecture that is dependent on the number of connections. Spinning up a thread for each user doesn't scale once the user count goes up and the threads start getting in each-other's way.

Title: Implementing chat in 2013

Body:
I played a bit with WebSockets and started to implement a tiny chat. Last time I did something like this was when there was no such thing as threads and computers had single core. I started to think how to implement it with todays programming patterns but I didn't come to any final conclusion.

How you implement chat's main functionality in today's technics in higher level?

I now have context Server, Socket and User. User has states Undefined, Connected, InChat, ToBeDisconnected, Disconnected, My main problem is the user maintenance:

If user hasn't said "hello" in 5 seconds after connection was opened -> disconnect

User is not replied to "ping" with "pong" at all or at least 2 minutes -> disconnect

User has been connected over 12 hours -> disconnect

User haven't been assigned profile (nickname and/or other details) after 5 minutes of connect -> disconnect

Some other program specific flag that kicks out user is triggered -> disconnect

My current implementation is like how it was done in olden days. ie. I have

```<code>while(serverRunning)
{
  foreach(socket in allSockets)
  {
    user = allUsers.findUserBySocket(socket);
    doMaintenance(user);
  }
}
</code>```

Now this runs far too many times and locks and blocks allUsers and allSockets way too much.

How this is implemented today? Like this for example?

Socket connects

Add to allSockets

Add to allUsers

Start per-user thread that runs every x seconds and runs user.doMaintenance()?

Or there's per-user queue that gets injected with actions like doPongCheckAction, doProfileTimeoutCheckAction, etc every x seconds (also needs per-user thread which constantly empties user's queue)?

Or there's Maintenance thread that runs every x second after last run and iterates through allUsers (a bit like current implementation)?

Or there's thread that injects actions to all users queues when there's been too long when same kind of action were ran and other thread that iterates through all users and empties user's queue?

Or something else or which is not even based on queues? :)


问:
How to get better at debugging?
How can one become better at debugging in general? I do not mean specific tools or tactics that apply to a certain programming language or stack, but simply how to make your mind better at it, hopefully something beyond "just more exercise".

I am fairly good at "blank sheet" type programming problems: I can easily code something from scratch, even starting from the lowest level and coding the framework in the process than maybe extracting the framework and using it in another project or doing a fancy rearchitecture of a complex piece of software. But compared to most people I've worked with, I am extremely bad at detail oriented debugging, and by this I mean finding that little misinterpreted error code, those parameters passed in the wrong order that gave birth to a wrong sql query n-levels deep, or that little configuration bug that made the testing server behave totally different from the production one or other "micro" bugs.

I sometimes feel that my mind is not made for this. Even in other areas with a high-level vs. low-level separation I get something similar, like when I write something, regardless of the language, despite my decent knowledge of spelling and grammar, I'm spell-checking dependent - when I focus on what I write, my mind becomes blind and I make horrendous spelling and grammar errors. And almost everything I happen to be doing, my mind drifts away to the higher level views and concepts (my mind is somehow "made for" architecting stuff and viewing high level patterns) and I become mostly blind to low level stuff and I'm very bad at debugging the errors at these levels. I get this detail blindness even when the lowest level code is written by me.

So again, what do you do and know it works to get over this detail blindness and debugging induced mind-block and become better at the task of debugging yours or others code? (I'm looking for as much facts and as little subjective opinions as possible for this question...)

Note: I mostly work in Python, Javascript and unfortunately PHP and rarely delve into C and I'm currently learning Haskell FTR, but I'm not looking for a language or tech specific solution - its more a "how do I reprogram my mind to become better at this" problem.

答:
Well, to do debugging like you described, messed up sql queries and config and other misterious things, you have to know the system inside out. Especially for cases where the app runs seemingly ok but gives out wrong data. The outright crashes are relatively easy compared to logical errors.

But to fix those, you really have to know what that part of the application needs to be doing, and how it's doing it, and then you need a good understanding of how what it is doing now is wrong. Something like "it's just wrong data" is not enough. Look for patterns in the errors, because programs are not random. Spotting patterns can get you to that light-bulb moment when you realize, oh it must be something with the query, and then you track it down.
This is something that is not easy if you are not familiar with the system, or have experience with similar systems, so I'm willing to bet that you're no worse at it than anyone else who's been given an app to maintain but not enough time to get to know it.

Also, learn to really read the errors that the language gives you. Get to know its codes/messages whatever. I see a bunch of people giving up when they get a cryptic exception. They don't know what it's saying and they start blindly poking around, which leads to frustration. Knowing exactly what can trigger that particular exception with that message can get you going in the right direction.

On a side note, I really hope you're using something like XDebug when working with PHP and not just throwing echo/var_dump/print_r statements around.

Title: How to get better at debugging?


答:
David Agans wrote a pretty good book on the subject, breaking it down into 9 fairly objective rules:

Understand the system

Make it fail

Quit thinking and look

Divide and conquer

Change one thing at a time

Keep an audit trail

Check the plug

Get a fresh view

If you didn't fix it, it ain't fixed

I've always considered myself a fairly intuitive debugger, and saw it as more art than science, until I read that book, which verbalized a lot of the habits I picked up, making them concrete and objective.

The basic idea is to be methodical about it, instead of haphazard.  If you get blinded by details, and distracted by the high-level view, write things down.  Put temporary comments in the code to track your place, or keep track of what you've already tried on a whiteboard.  Use a debugger, so you know exactly what arguments are being passed at the lowest levels of the call stack.  Then once you're sure the lowest layer is good, work your way up, but write it down so you don't revisit the same thing over and over.

Title: How to get better at debugging?

Body:
How can one become better at debugging in general? I do not mean specific tools or tactics that apply to a certain programming language or stack, but simply how to make your mind better at it, hopefully something beyond "just more exercise".

I am fairly good at "blank sheet" type programming problems: I can easily code something from scratch, even starting from the lowest level and coding the framework in the process than maybe extracting the framework and using it in another project or doing a fancy rearchitecture of a complex piece of software. But compared to most people I've worked with, I am extremely bad at detail oriented debugging, and by this I mean finding that little misinterpreted error code, those parameters passed in the wrong order that gave birth to a wrong sql query n-levels deep, or that little configuration bug that made the testing server behave totally different from the production one or other "micro" bugs.

I sometimes feel that my mind is not made for this. Even in other areas with a high-level vs. low-level separation I get something similar, like when I write something, regardless of the language, despite my decent knowledge of spelling and grammar, I'm spell-checking dependent - when I focus on what I write, my mind becomes blind and I make horrendous spelling and grammar errors. And almost everything I happen to be doing, my mind drifts away to the higher level views and concepts (my mind is somehow "made for" architecting stuff and viewing high level patterns) and I become mostly blind to low level stuff and I'm very bad at debugging the errors at these levels. I get this detail blindness even when the lowest level code is written by me.

So again, what do you do and know it works to get over this detail blindness and debugging induced mind-block and become better at the task of debugging yours or others code? (I'm looking for as much facts and as little subjective opinions as possible for this question...)

Note: I mostly work in Python, Javascript and unfortunately PHP and rarely delve into C and I'm currently learning Haskell FTR, but I'm not looking for a language or tech specific solution - its more a "how do I reprogram my mind to become better at this" problem.


答:
Test that encode(decode(coded_value)) == coded_value and decode(encode(value)) == value.  You can give a random input to the tests if you want.

It's still possible that both the encoder and decoder are broken in complimentary ways, but that seems pretty unlikely unless you have a conceptual misunderstanding of the encoding standard.  Doing hardcoded tests of the encoder and decoder (like you're doing already) should guard against that.

If you have access to another implementation of this that's known to work, you can at least use it to get confidence that your implementation is good even if using it in the unit tests would be impossible.

Title: How do you unit test an encoder?