问:
Should I test inherited methods?
Suppose I have a class Manager derived from a base class Employee, and that Employee has a method getEmail() that is inherited by Manager.  Should I test that the behaviour of a manager's getEmail() method is in fact the same as an employee's?

At the time these tests are written the behaviour will be the same, but of
course at some point in the future someone might override this method, change its behaviour, and therefore break my application.  However it seems a bit strange to essentially test for the absence of meddling code.

(Note that testing Manager::getEmail() method does not improve code coverage (or indeed any other code quality metrics (?)) until Manager::getEmail() is created/overridden.)

(If the answer is "Yes", some information about how to go about managing tests that are shared between base and derived classes would be useful.)

An equivalent formulation of the question:

If a derived class inherits a method from a base class, how do you express (test) whether you're expecting the inherited method to:

Behave in exactly the same way as the base does right now (if the behaviour of the base changes, the behaviour of the derived method doesn't);

Behave exactly the same way as the base for all time (if the behaviour of the base class changes, the behaviour of the derived class changes as well); or

Behave however it wants to (you don't care about the behaviour of this method because you never call it).

答:
No, you do not need to test inherited methods. Classes and their test cases which rely on this method will break anyway if the behaviour changed in Manager.

Think of the following scenario: The email address is assembled as Firstname.Lastname@example.com:

```<code>class Employee{
    String firstname, lastname;
    String getEmail() {
        return firstname + "." + lastname + "@example.com";
    }
}
</code>```

You have unit tested this and it works fine for your Employee. You also have created a class Manager:

```<code>class Manager extends Employee { /* nothing different in email generation */ }
</code>```

Now you have a class ManagerSort which sorts managers in a list based on their email address. Of yourse you suppose that the email generation is the same as in the Employee:

```<code>class ManagerSort {
    void sortManagers(Manager[] managerArrayToBeSorted)
        // sort based on email address omitted
    }
}
</code>```

You write a test for your ManagerSort:

```<code>void testManagerSort() {
    Manager[] managers = ... // build random manager list
    ManagerSort.sortManagers(managers);

    Manager[] expected = ... // expected result
    assertEquals(expected, managers); // check the result
}
</code>```

Everything works fine. Now someone comes and overrides the getEmail() method:

```<code>class Manager extends Employee {
    String getEmail(){
        // managers should have their lastname and firstname order changed
        return lastname + "." + firstname + "@example.com";
    }
}
</code>```

Now, what happens? Your testManagerSort() will fail because the getEmail() of Manager was overridden. You will investigate in this issue and will find the cause. And all without writing a seperate testcase for the inherited method.

Therefore, you do not need to test inherited methods.

Otherwise, e.g. in Java, you would have to test all methods inherited from Object like toString(), equals() etc. in every class.

Title: Should I test inherited methods?

Body:
No, you do not need to test inherited methods. Classes and their test cases which rely on this method will break anyway if the behaviour changed in Manager.

Think of the following scenario: The email address is assembled as Firstname.Lastname@example.com:

class Employee{
    String firstname, lastname;
    String getEmail() {
        return firstname + "." + lastname + "@example.com";
    }
}

You have unit tested this and it works fine for your Employee. You also have created a class Manager:

class Manager extends Employee { /* nothing different in email generation */ }

Now you have a class ManagerSort which sorts managers in a list based on their email address. Of yourse you suppose that the email generation is the same as in the Employee:

class ManagerSort {
    void sortManagers(Manager[] managerArrayToBeSorted)
        // sort based on email address omitted
    }
}

You write a test for your ManagerSort:

void testManagerSort() {
    Manager[] managers = ... // build random manager list
    ManagerSort.sortManagers(managers);

    Manager[] expected = ... // expected result
    assertEquals(expected, managers); // check the result
}

Everything works fine. Now someone comes and overrides the getEmail() method:

class Manager extends Employee {
    String getEmail(){
        // managers should have their lastname and firstname order changed
        return lastname + "." + firstname + "@example.com";
    }
}

Now, what happens? Your testManagerSort() will fail because the getEmail() of Manager was overridden. You will investigate in this issue and will find the cause. And all without writing a seperate testcase for the inherited method.

Therefore, you do not need to test inherited methods.

Otherwise, e.g. in Java, you would have to test all methods inherited from Object like toString(), equals() etc. in every class.


问:
How to avoid a singleton in this example?
I have a class Image and another one ImageStore. The Image it's just a value object containing the package name and the image name. The ImageStore does all the actual work: calculates the real path of the image (based on the package and image name) and loads it from the server.

Now I have a quite big (and deep) hierarchy of nodes (this is a render engine for a game) so for example now I am in a group and I want to insert a new Image. I do:

```<code>var image = new Image("packageName", "imageName");
</code>```

At this moment the Image doesn't have any size yet, as I don't want to hard code the image size (in this case this can be a tile, which is not always 64*32 for example) in my game view.

when the Image is added to the Group (I suppose the group is already attached to the Renderer) then the Group will be invalidated

the Renderer will request a new frame render.

it will parse the hierarchy tree of node and when it finds the Image I've added before

it will ask the ImageStore (or TileImageStore, this one not only stores the width and height but also the bottom center point of the tile. This only when the bottom center of the tile doesn't match the bottom center point of the real image.) for the ImageData;

the ImageStore now loads the package, which also has the info about the width and height;

it will apply the new width and height to the image and will set a flag as loaded.

I would like to have somehow the ImageStore detached from the render. To be able to use only the Image and ImageStore without the need of the renderer.

Edit:
I want to do this because I would like to know the size of a image even when the image is not rendered. In order to get the image it has to ask the ImageStore for the size, anchor and imageData. The packages are like this:

```<code>package = {image01: {base64: "very very long string", width: 10, height: 20, anchorX: 1, anchorY: 10}}
</code>```

Only after the ImageStore loads this big file is able to know the image width/height;

答: You just make an ImageStore and pass it into a Renderer you make. There is no reason for singletons here.

OwnerDisplayName: Totty

ContentLicense: CC BY-SA 3.0


答:
Without really knowing any further details:

Suggest you rename your existing Image struct, to ImageInfo
And create a new object called SelfLoadingImage, which has an 'Image' interface that the Renderer can use to get actual pixel data or whatever.

Then under the hood, how this pixel data is retrieved is a different problem that the Renderer doesn't care about. You can now, for instance, have a HardcodedImage for testing purposes.

In the case of a SelfLoadingImage, it has a constructor that takes an ImageInfo, and an ImageStore and uses these when needed. But these instances of SelfLoadingImage get added as 'Image' objects to your rendering system.

Title: How to avoid a singleton in this example?

Body:
I have a class Image and another one ImageStore. The Image it's just a value object containing the package name and the image name. The ImageStore does all the actual work: calculates the real path of the image (based on the package and image name) and loads it from the server.

Now I have a quite big (and deep) hierarchy of nodes (this is a render engine for a game) so for example now I am in a group and I want to insert a new Image. I do:

```<code>var image = new Image("packageName", "imageName");
</code>```

At this moment the Image doesn't have any size yet, as I don't want to hard code the image size (in this case this can be a tile, which is not always 64*32 for example) in my game view.

when the Image is added to the Group (I suppose the group is already attached to the Renderer) then the Group will be invalidated

the Renderer will request a new frame render.

it will parse the hierarchy tree of node and when it finds the Image I've added before

it will ask the ImageStore (or TileImageStore, this one not only stores the width and height but also the bottom center point of the tile. This only when the bottom center of the tile doesn't match the bottom center point of the real image.) for the ImageData;

the ImageStore now loads the package, which also has the info about the width and height;

it will apply the new width and height to the image and will set a flag as loaded.

I would like to have somehow the ImageStore detached from the render. To be able to use only the Image and ImageStore without the need of the renderer.

Edit:
I want to do this because I would like to know the size of a image even when the image is not rendered. In order to get the image it has to ask the ImageStore for the size, anchor and imageData. The packages are like this:

```<code>package = {image01: {base64: "very very long string", width: 10, height: 20, anchorX: 1, anchorY: 10}}
</code>```

Only after the ImageStore loads this big file is able to know the image width/height;


问:
How can robots beat CAPTCHAs?
I have a website e-mail form. I use a custom CAPTCHA to prevent spam from robots. Despite this, I still get spam.

Why? How do robots beat the CAPTCHA? Do they use some kind of advanced OCR or just get the solution from where it is stored?

How can I prevent this? Should I change to another type of CAPTCHA?

I am sure the e-mails are coming from the form, because it is sent from my email-sender that serves the form messages. Also the letter style is the same.

 For the record, I am using PHP + MySQL, but I'm not searching for a solution to this problem. I was interested in the general situation how the robots beat these technologies. I just told this situation as an example, so you can understand better what I'm asking about.

答:
It is possible that your site is being targeted by an exploited ultra-cheap labour force and that a human being is manually entering your CAPTCHA phrases.

If the solution you are using is not overly sophisticated, it is possible that your attacker is doing image recognition.

It is also a possibility that you have a bug somewhere in your code that is allowing the CAPTCHA to be bypassed.

Don't make the assumption that a robot is beating your CAPTCHA. Think of your system holistically and see if it has been compromised.

Title: How can robots beat CAPTCHAs?


答:
Two easiest ways to get through CAPTCHA:

Use human farms, i.e. ask for people to fill CAPTCHAs for money, just like ProTypers does.

Use an OCR.

There may also be a bug either in the CAPTCHA mechanism itself or the surrounding application, allowing someone to bypass the CAPTCHA.

By the way, the W3C article Inaccessibility of CAPTCHA : Alternatives to Visual Turing Tests on the Web explains as well how CAPTCHAs could be compromised:

[...] One of the first documented attacks on the system was by a Carnegie Mellon student, who associated CAPTCHA images with access to an adult Web site, thus gaining free human labor to crack the authentication. [...]

External projects [...] have shown methodologies and results indicating that many of the systems can be defeated by computers with between 88% and 100% accuracy, using optical character recognition.

So how can you prevent those attacks?

If you have your custom implemented CAPTCHA, you may try to move to a popular one, like reCAPTCHA.

This will help if either your own CAPTCHA was too easy to OCR, or if there was a bug which was successfully exploited.

If you use a popular CAPTCHA mechanism, moving to a custom-made one or to another popular one might prevent OCR.

Technically, nothing would prevent human farms: you may create animated GIFs where several frames display different text very quickly, and only one frame is actually visible by the user, you may distort or bend text in all directions or find new, alternative ways to prevent OCRs from recognizing text, still humans paid for solving CAPTCHAs will successfully solve them.

You may want to move from visual CAPTCHA to sound (if you're not using both already, and you should), but this means that users with hearing impairment would be unable to use your application.

FrustratedWithFormsDesigner and GalacticCowboy mentioned in the comments domain-specific CAPTCHAs. I tried to find some material about how effective those are, but without success, so here is just my personal opinion:

Domain-specific CAPTCHAs can be hugely annoying when actual users have no idea about the answer.

Example: I'm visiting a page on a movies-oriented website. I notice a mistake in an article and want to comment on it to notify the author about the mistake. The comments form asks me, as a CAPTCHAs mechanism, to provide the name of the actress displayed on a photo. I have no idea who is this actress, so the only thing I can do is to leave the website (or spend the next two minutes using Google Images).

Another example: a website asks to give a synonym of "mysterious". Easy as it sounds for a non-impaired person who speaks English fluently, it would be impossible to solve without external help for people who don't speak English well or people with some developmental disabilities, not counting the fact that finding synonyms or antonyms is always tricky.

Most of those domain-specific problems can be solved programmatically. Both examples I gave are easily solved using external resources (Google Images and Synonyms dictionary). The one about transistors given as an example by FrustratedWithFormsDesigner is better, but still may be probably solved with a custom-made bot.

None resist human farms.

Either they generate data, just like ordinary text CAPTCHAs draw distorted characters, in which case the generation algorithm can be itself exploited to tune the bots, or they find data somewhere, just like reCAPTCHA takes text from scanned books, in which case the bot can use this data against it (for example, if you take words from a dictionary, asking the user to provide synonyms, the bot can use the very same dictionary to have a 100% success).

Title: How can robots beat CAPTCHAs?

Body:
I have a website e-mail form. I use a custom CAPTCHA to prevent spam from robots. Despite this, I still get spam.

Why? How do robots beat the CAPTCHA? Do they use some kind of advanced OCR or just get the solution from where it is stored?

How can I prevent this? Should I change to another type of CAPTCHA?

I am sure the e-mails are coming from the form, because it is sent from my email-sender that serves the form messages. Also the letter style is the same.

 For the record, I am using PHP + MySQL, but I'm not searching for a solution to this problem. I was interested in the general situation how the robots beat these technologies. I just told this situation as an example, so you can understand better what I'm asking about.


问:
.Net developer trying to learn ruby on rails
I am a .NET developer and I just had the chance to play with Ruby on Rails this weekend.

In .NET we separate layers of the application by creating separate class library projects. From the design pattern standpoint, do we have to do that in Rails too or is it just one whole project with everything in it?

答:
You'll find that Rails apps start as single repos. The more successful ones (Twitter, Square, many others) split into multiple codebases as they grow into that requirement.  Those additional codebases can be daemons, services, gems, Rails Engines, or something else.

This refactoring into multiple projects isn't done until it proves necessary, because YAGNI.  Bifurcating your project on day 1 slows prototyping time, and prototyping speed is a key strength of Ruby and of Rails.  You'll want to keep in mind that creating or a class in Ruby costs almost nothing, as does breaking apart a well-desined class.  Your pure Ruby code will live mostly under /app/ (app/models, app/views app/controllers, app/helpers) and /lib/.  Your static assets, layered JS/Coffee includes, and CSS/Sass/etc includes are going to be in /app/assets.

Understanding why breaking apart a Ruby class is so easy requires a bit of reading on duck typing and the understanding that Ruby's interfaces aren't as ironclad as you might
be used to in a less dynamic environment.

Here are a few links that might interest you:

Brief description of duck typing (Yehuda Katz blogpost)

The inestimable Sandi Metz on how and why to design OO programs that are simple to read, to understand, and to change (2 hour Ruby Rogues podcast) (Her fantastic book)

Rails creator David Heinemeier Hansson on the asset pipeline and the code layout problems it ameliorates (RailsConf keynote video)

Making your own gem (Rubygems.org HOWTO)

Good luck with your projects!


问:
How to avoid repetitively logging in to web site?
While developing web sites it can be annoying that I have to login to the site.
Every time the session runs out I have to go through a flow like...

Open logon page -> enter username/password -> click link to navigate to my page.

I sometimes use Selenium to record this flow, and then automate it.
But Selenium doesn't work in all browsers, and it still takes
too long to load etc.

I would like to be able to just refresh the page, exactly like I would if the
site didn't have a login page.

Does anyone use any strategies to achieve this?
Any way to disable login during development?
Or other tools which can help improve the situation?

答: A session has a time limit associated with it.  This is set when the session is created.  You can set the time limit to a long time for debugging purposes.</p>


问:
Java vs PHP Memory / CPU Consumption
I work in a PHP based company. There is a project where we want to create a backend service. Senior members here are going for PHP, even though it is slower than Java. Their only point of contention, that Java is heavier than PHP in both memory and cpu load standpoint.

Jvm is more like a container environment, if u bring in more baggage it will consume that much, but service we are talking here will be of medium complexity. So chances are that it won't be much demanding (or will it?)

I understand this question leans heavily towards vagueness, however my point of ponder is, that is it always the same case? That java is more hardware demanding? I would just like to know opinions of all you experienced folks about how the actual scenario looks like.

答:
If you're worried about speed, write the back-end in a compiled, fast-as-you-like language such a C or C++. There are plenty of webservice tooling to create simple C/C++ web services that you can consume from your PHP clients.

However, if you want to code it quickly and performance isn't so bad, then write it in PHP. You also have the benefit of already having the skills necessary to do this, so that's a double bonus.

Java isn't massively bloated compared to PHP, it might be a 'step up', but you'll have to learn all the niggles and tricks that you need with any new system, and I doubt the benefit will be worth it compared to just writing it in PHP straight away. In most cases, if you have the skills to do it in PHP already, that should be the first choice, choosing to do it in a different language away from your main area of expertise should be very carefully considered and only chosen if there is definite benefits over your primary system (which I don't think there will be in this case)

Title: Java vs PHP Memory / CPU Consumption


答:
A sessionlogouttimer resets when a new page is loaded, set your browser to autoreload the page and your session should not run out.

You can use a meta tag in your page :

```<code>(meta http-equiv="refresh" content="3")
</code>```

or use a plugin for your browser.

Don't forget to remove the meta tag when you set it live though.

Title: How to avoid repetitively logging in to web site?

Body:
While developing web sites it can be annoying that I have to login to the site.
Every time the session runs out I have to go through a flow like...

Open logon page -> enter username/password -> click link to navigate to my page.

I sometimes use Selenium to record this flow, and then automate it.
But Selenium doesn't work in all browsers, and it still takes
too long to load etc.

I would like to be able to just refresh the page, exactly like I would if the
site didn't have a login page.

Does anyone use any strategies to achieve this?
Any way to disable login during development?
Or other tools which can help improve the situation?

Body:
A sessionlogouttimer resets when a new page is loaded, set your browser to autoreload the page and your session should not run out.

You can use a meta tag in your page :

(meta http-equiv="refresh" content="3")

or use a plugin for your browser.

Don't forget to remove the meta tag when you set it live though.


答:
Why sessions are expiring? Is it because:

They were inactive for a certain delay?

In this case, just increase the delay.

Or because recompiling the web application threw out application cache and current sessions?

In this case, store sessions on a less volatile support, like the database. This would also give you the advantage to be able to run the web application on multiple servers for redundancy or higher scalability.

In both cases, unless you're working on a web application of a bank, give to your users the ability to remember credentials on logon through cookies and use it yourself.

While technically, it's not the same as staying logged in (since the web app will be forced to authenticate the user according to the values in cookies), from the users' perspective, there is no big difference, since they don't have to see the login form again for weeks or months.


问:
Is there a way to support different coding styles in a development team
The Problem: Two developers => three opinions on indention, braces on new line or not etc.

We usually work with three or four people on our projects and each of those has it's own code style. I know, the common solution is to agree on a code style, everybody has to use, but I don't want to force creative programmers in a suit that does not fit them.

So the question is: Is there a way to let each programmer live his/her own style, but having a common code base inside the repository? I think of some git/svn/whatever plugin, which changes between personal and common style on checkout and commit. It appears to me, that the tricky part in this approach is to support correct diffs between the versions of a file

答:
absolutely you can. Its all about not sweating the small stuff.

The only standard that matters is "keep your changes the same style as the existing code". As long as you can fit yourself to a coding style that isn't your preferred one, then you can work with any coding style.

So what's the big deal about working in 3 different styles within the same company. Your developers need to understand this, that writing code in the way they like is find for their code but once they make changes to a different file that uses a different style, they have to maintain that style (or it'll really look bad). No reformatting is allowed (or they'll just reformat continually and the scm diffs will be useless)(and if you do this, then a auto formatted should be employed).

Chances are, once they get going with this, they'll come to some consensus about which style to use or they style will drift together for the most part. If they're going to be childish about it and will reformat each others code all the time, then it'll be time to download a standard from the internet and demand they use it. You might want to do this anyway, just to wave it in their faces as an "play nice or else" card.


问:
Feature vs. Function
Often I hear PMs (Project Managers) talk about feature and function. And I'm just so puzzled to differentiate them. Sometimes I think of a feature to be equivalent to a user story. Something like "As a user, Bob should be able to see a list of his payments", and they call it a feature. Sometimes it gets as big as a subsystem, something like "the ability to send SMS via web application". Function on the other hand sometimes gets as small as a task, "implementing digit grouping for number inputs", while there are cases when it gets as big as a whole CRUD operation.

My question is, how can we differentiate feature from function?

答: It is important to remember the distinction between product functions and product features.  Functions are the “product’s answer to the set of user tasks”; features are the “user tools” inherent in the product used to perform the functions .  Placing a telephone call is a function; the dial tone and the touch-tone keypad are features used to accomplish the function. </p>

Title: Feature vs. Function


答:
Adding to MainMa's answer...

Spammers trick others into doing the CAPTCHA for them

Basically, spammers set up a warez site or a porn site that appears to have a CAPTCHA on it, but it's not a real CAPTCHA. A bot pulls the CAPTCHA from the site they want to spam (or otherwise exploit), and then displays it on the warez site or a porn site where someone completes it for them. Then the CAPTCHA value is passed back to their bot...

A bit more on Spammers

I use reCAPTCHA, and I've found that it's basically worthless. I also use a custom spam filter that catches the spam that got past reCAPTCHA, and I need to review it every few days for false positives.

My forum is also all custom-written and it gets very little traffic. I don't believe anyone coded a specific attack to my site. Still, my spam filter catches 2k spam messages a day! None are ever displayed on the site. Spammers get no benefit from spamming me, yet they still do.

I can see patterns in the spamming attempts because I log it all. I can tell you this: putting aside how they get past the CAPTCHA, spammers are clearly using a brute force technique varying the fields that are filled out and the kind of data and word mixes that populate those fields. Apparently they do this so cheaply (including bypassing the CAPTCHA) that it doesn't even pay to do an analysis of the individual sites to see of if what they are doing is or isn't working.

Year after year, they continue targeting my site with thousands of spam messages a day only to get one through every month, and that one gets manually deleted a day later. It's that cheap to spam!

This is going to be a battle for years to come. Particularly for small one-man moderator sites like mine.

EDIT 6/22/2017 :
I want to add that since this post google has completely revamped reCAPTCHA and as of this writing it has been working flawlessly. Though I suspect there is a bit of false positives or its a pain for users as post have dropped a bit since I implemented it. The 2 big changes are

1) They are using Images instead of text (So no more OCR)

2) They are combining it with the users activity across all site that use reCAPTCHA. So if you get past the reCAPTCHA on site A, then go to Site B it may not even prompt you to prove you are human! Also (I think) if you are hitting too many reCAPTCHAs across too many sites it will flag you as well. I am sure it is using other sorts of AI based on the users activity as well.

I'm sure its just a matter of time until spammers beat this as well...

Title: How can robots beat CAPTCHAs?


问:
How do I learn linking compiling, makefile quickly? Any book recommendations?
I'm very good at programming in C++ but when it gets to linking and the other important stuffs I feel very ignorant. I want to learn allegro without wasting time. So please suggest a book or a resource to learn the concepts mentioned above. Thanks a lot in advance.</p>

答:
I wouldn't spend time on any book. There's really not much knowledge here.

Use Wikipedia, Google, and unix man to

Understand what make is (file stamp driven dependency aware synthesizer of whatever). Use GNU Make manual as a reference as you go. The important flags of GNU Make to be aware of are '-p', '-n', and '-d'

Read about gcc/g++ flags for compiling/linking shared/static debug/optimized 32/64-bit modes. Read what LD_LIBRARY_PATH, LD_PRELOAD, position independent code, and rpath are.

Learn what nm, c++filt, strings, and ldd are. You will need to use them to debug build problems.

This is more or less it.

ContentLicense: CC BY-SA 2.5


问:
Switching from ActionScript to JavaScript, tips for writing code?
I am quite comfortable with using actionscript3 and flash. I also have some experience with Java. But recently, I started learning JavaScript and node.js. I ultimately want to make a 3d game in threejs, but for now I simply want to make a chat application.

I want to get into the habit of using JavaScript. Unfortunately, I am finding it very difficult to start using JavaScript. The difficulties I am facing are

No suggestions for different methods and properties pop up, like they do in the Eclipse IDE and Flash Builder IDE. Like when you press dot after object, it shows all the methods and properties relating to that object and it becomes really easy to see what the parameters are and needed to be passed and stuff.

How to organize code? In ActionScript3, I could simply make different classes in different packages. I could then import and use those classes in one main file. How does it work in JavaScript?

Functions. I have seen people use anonymous functions in javascript. But I am compelled to write external functions as I am in the habit of it. What is better in JavaScript workflow? What do you advice?

How is code executed within a HTML file? So if I have several  tags and I declare a variable in one of them, can the tags below it and above it access that variable?

答:
Autocompletion

Javascript is a dynamic language and it's impossible to get anywhere near to what you have in Actionscript or Java. Just accept what your IDE (WebStorm for instance) might suggest for you. This goes for any interpreted language really.

How to organize code?

Have a look at requirejs or node.js's own module require function.

Anonymous functions.

Yes, get use to them. Javascript is very much function-based so you'd just have to accept that part. Here is a great starting point.

Several  tags and I declare a variable in one of them,
  can the tags below it and above it access that variable?

Nope, only tags below it. Try this:

```<code><body>
   <script> console.log(x); </script>
   <script> var x = 1; </script>
</body>
</code>```

Console prints "x is undefined".

Body:
Autocompletion

Javascript is a dynamic language and it's impossible to get anywhere near to what you have in Actionscript or Java. Just accept what your IDE (WebStorm for instance) might suggest for you. This goes for any interpreted language really.

How to organize code?

Have a look at requirejs or node.js's own module require function.

Anonymous functions.

Yes, get use to them. Javascript is very much function-based so you'd just have to accept that part. Here is a great starting point.

Several  tags and I declare a variable in one of them,
  can the tags below it and above it access that variable?

Nope, only tags below it. Try this:

<body>
   <script> console.log(x); </script>
   <script> var x = 1; </script>
</body>

Console prints "x is undefined".


问:
Do not declare interfaces for immutable objects
Do not declare interfaces for immutable objects

[EDIT] Where the objects in question represent Data Transfer Objects (DTOs) or Plain Old Data (PODs)

Is that a reasonable guideline?

Up to now, I've often created interfaces for sealed classes that are immutable (data cannot be changed). I've tried to be careful myself to not use the interface anywhere where I care about immutability.

Unfortunately, the interface begins to pervade the code (and it's not just my code I'm worried about). You wind up being passed an interface, and then wanting to pass it to some code that really wants to assume that the thing being passed to it is immutable.

Because of this problem, I'm considering never declaring interfaces for immutable objects.

This might have ramifications with respect to Unit Testing, but other than that, does this seem a reasonable guideline?

Or is there another pattern I should be using to avoid the "spreading-interface" problem I'm seeing?

(I'm using these immutable objects for several reasons: Mainly for thread safety since I write a lot of multi-threaded code; but also because it means I can avoid making defensive copies of objects passed to methods. Code becomes a lot simpler in many cases when you know something is immutable - which you don't if you've been handed an interface. In fact, often you can't even make a defensive copy of an object referenced via an interface if it doesn't provide a clone operation or any way of serialising it...)

[EDIT]

To provide a lot more context for my reasons for wanting to make objects immutable, see this blog post from Eric Lippert:

Link

I should also point out that I'm working with some lower-level concepts here, such as items that are being manipulated/passed around in multi-threaded job queues. These are essentially DTOs.

Also Joshua Bloch recommends the use of immutable objects in his book Effective Java.

Follow Up

Thanks for the feedback, all. I've decided to go ahead and use this guideline for DTOs and their ilk. It's working well so far, but it's only been a week... Still, it's looking good.

There are some other issues relating to this that I want to ask about; notably something I'm calling "Deep or Shallow Immutability" (nomenclature I stole from Deep and Shallow cloning) - but that's a question for another time.

答:
In my opinion, your rule is a good one (or at least it's not a bad one), but only because of the situation you are describing.  I wouldn't say that I agree with it in all situations, so, from the standpoint of my inner pedant, I'd have to say your rule is technically too broad.

Typically you wouldn't define immutable objects unless they are essentially being used as data transfer objects (DTO), which means that they contain data properties but very little logic and no dependencies.  If that is the case, as it seems it is here, I'd say you are safe to use the concrete types directly rather than interfaces.

I'm sure there will be some unit-testing purists who will disagree, but in my opinion, DTO classes can be safely excluded from unit-testing and dependency-injection requirements.  There is no need to use a factory to create a DTO, since it has no dependencies.  If everything creates the DTOs directly as needed, then there's really no way to inject a different type anyway, so there's no need for an interface.  And since they contain no logic, there's nothing to unit-test.  Even if they do contain some logic, as long as they have no dependencies, then it should be trivial to unit-test the logic, if necessary.

As such, I think that making a rule that all DTO classes shall not implement an interface, while potentially unnecessary, is not going to hurt your software design.  Since you have this requirement that the data needs to be immutable, and you cannot enforce that via an interface, then I would say it's totally legitimate to establish that rule as a coding standard.

The larger issue, though, is the need to strictly enforce a clean DTO layer.  As long as your interface-less immutable classes only exist in the DTO layer, and your DTO layer remains free of logic and dependencies, then you will be safe.  If you start mixing your layers, though, and you have interface-less classes that double as business layer classes, then I think you will start to run into much trouble.

OwnerDisplayName: Matthew Watson

ContentLicense: CC BY-SA 4.0

OwnerDisplayName: Steven Doggart


答:
Code becomes a lot simpler in many cases when you know something is immutable - which you don't if you've been handed an interface.

I don't think that's a concern that the accessor implementer has to worry about. If interface X is meant to be immutable, then isn't it the responsibility of the interface implementer to insure that they implement the interface in an immutable fashion?

However, in my mind, there's no such thing as an immutable interface - the code contract specified by an interface applies only to the exposed methods of an object, and nothing about the internals of an object.

It's much more common to see immutability implemented as a decorator rather than an interface, but the feasibility of that solution really depends on the structure of your object and the complexity of your implementation.

Body:
Do not declare interfaces for immutable objects

[EDIT] Where the objects in question represent Data Transfer Objects (DTOs) or Plain Old Data (PODs)

Is that a reasonable guideline?

Up to now, I've often created interfaces for sealed classes that are immutable (data cannot be changed). I've tried to be careful myself to not use the interface anywhere where I care about immutability.

Unfortunately, the interface begins to pervade the code (and it's not just my code I'm worried about). You wind up being passed an interface, and then wanting to pass it to some code that really wants to assume that the thing being passed to it is immutable.

Because of this problem, I'm considering never declaring interfaces for immutable objects.

This might have ramifications with respect to Unit Testing, but other than that, does this seem a reasonable guideline?

Or is there another pattern I should be using to avoid the "spreading-interface" problem I'm seeing?

(I'm using these immutable objects for several reasons: Mainly for thread safety since I write a lot of multi-threaded code; but also because it means I can avoid making defensive copies of objects passed to methods. Code becomes a lot simpler in many cases when you know something is immutable - which you don't if you've been handed an interface. In fact, often you can't even make a defensive copy of an object referenced via an interface if it doesn't provide a clone operation or any way of serialising it...)

[EDIT]

To provide a lot more context for my reasons for wanting to make objects immutable, see this blog post from Eric Lippert:

Link

I should also point out that I'm working with some lower-level concepts here, such as items that are being manipulated/passed around in multi-threaded job queues. These are essentially DTOs.

Also Joshua Bloch recommends the use of immutable objects in his book Effective Java.

Follow Up

Thanks for the feedback, all. I've decided to go ahead and use this guideline for DTOs and their ilk. It's working well so far, but it's only been a week... Still, it's looking good.

There are some other issues relating to this that I want to ask about; notably something I'm calling "Deep or Shallow Immutability" (nomenclature I stole from Deep and Shallow cloning) - but that's a question for another time.


答:
It seems like an okay guideline, but for odd reasons. I've had a number of places where an interface (or abstract base class) provides uniform access to a series of immutable objects. Strategies tend to fall here. State objects tend to fall here. I don't think it's too unreasonable to shape an interface to seem immutable and document it as such in your API.

That said, people do tend to over-interface Plain Old Data (hereafter, POD) objects, and even simple (often immutable) structures. If your code has no sane alternatives to some fundamental structure, it doesn't need an interface. No, unit testing is not sufficient reason to change your design (mocking database access isn't the reason you're providing an interface to that, it is flexibility for future change) - it isn't the end of the world if your tests use that basic fundamental structure as-is.

Title: Do not declare interfaces for immutable objects


问:
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 book programmers at work : http://www.amazon.com/Programmers-Work-Interviews-Computer-Industry/dp/1556152116

A great book which feature interviews of world class programmers of the 80's


问:
Implementing the Visitor Pattern for an Abstract Syntax Tree
I'm in the process of creating my own programming language, which I do for learning purposes. I already wrote the lexer and a recursive descent parser for a subset of my language (I currently support mathematical expressions, such as + - * / and parenthesis). The parser hands me back an Abstract Syntax Tree, on which I call the Evaluate method to get the result of the expression. Everything works fine. Here is approximately my current situation (Code examples in C#, although this is pretty much language-agnostic):

```<code>public abstract class Node
{
    public abstract Double Evaluate();
}

public class OperationNode : Node
{
    public Node Left { get; set; }
    private String Operator { get; set; }
    private Node Right { get; set; }

    public Double Evaluate()
    {
        if (Operator == "+")
            return Left.Evaluate() + Right.Evaluate();

        //Same logic for the other operators
    }
}

public class NumberNode : Node
{
    public Double Value { get; set; }

    public Double Evaluate()
    {
        return Value;
    }
}
</code>```

However, I would like to decouple the algorithm from the tree nodes because I want to apply Open/Closed Principle so I don't have to reopen every node class when I want to implement code generation for example. I read that the Visitor Pattern is good for that. I have a good understanding of how the pattern works and that using double dispatch is the way to go. But due to the recursive nature of the tree, I'm not sure how I should approach it. Here is what my Visitor would look like:

```<code>public class AstEvaluationVisitor
{
    public void VisitOperation(OperationNode node)
    {
        // Here is where I operate on the operation node.
        // How do I implement this method?
        // OperationNode has two child nodes, which may have other children
        // How do I work the Visitor Pattern around a recursive structure?

        // Should I access children nodes here and call their Accept method so they get visited?
        // Or should their Accept method be called from their parent's Accept?
    }

    // Other Visit implementation by Node type
}
</code>```

So this is my problem. I want to tackle it immediately while my language does not support a lot of functionnality to avoid having a bigger problem later.

I did not post this to StackOverflow because I don't want you to provide an implementation. I only want you to share ideas and concepts that I might have missed, and how I should approach this.

答:
You work the visitor pattern around a recursive structure the same way you would do anything else with your recursive structure: by visiting the nodes in your structure recursively. </p>

```<code>public class OperationNode
{
    public int SomeProperty { get; set; }
    public List<OperationNode> Children { get; set; }
}

public static void VisitNode(OperationNode node)
{
    ... Visit this node

    foreach(var node in Children)
    {
         VisitNode(node);
    }
}

public static void VisitAllNodes()
{
    VisitNode(rootNode);
}
</code>```

Body:
You work the visitor pattern around a recursive structure the same way you would do anything else with your recursive structure: by visiting the nodes in your structure recursively.

public class OperationNode
{
    public int SomeProperty { get; set; }
    public List<OperationNode> Children { get; set; }
}

public static void VisitNode(OperationNode node)
{
    ... Visit this node

    foreach(var node in Children)
    {
         VisitNode(node);
    }
}

public static void VisitAllNodes()
{
    VisitNode(rootNode);
}


答:
I have implemented the visitor pattern on a recursive tree before.

My particular recursive data structure was extremely simple - just three node types: the generic node, an internal node that has children, and a leaf node that has data.  This is much simpler than I expect your AST to be, but perhaps the ideas can scale.

In my case I deliberately did not let the Accept of a node with children call Accept on its children, or to call visitor.Visit(child) from within the Accept. It is the responsibility of the correct "Visit" member implementation of the visitor to delegate Accepts to children of the node being visited.  I chose this way because I wanted to allow different Visitor implementations to be able to decide the order of visitation independently of the tree representation.

A secondary benefit is that there are almost no artifacts of the Visitor pattern inside my tree nodes - each "Accept" just calls "Visit" on the visitor with the correct concrete type.  This makes it easier to locate and understand the visiting logic, it's all inside the visitor implementation.

For clarity I've added some C++-ish pseudocode.  First the nodes:

class INode {
  public:
    virtual void Accept(IVisitor& i_visitor) = 0;
};

class NodeWithChildren : public INode {
  public:
     virtual void Accept(IVisitor& i_visitor) override {
        i_visitor.Visit(*this);
     }
     // Plus interface for getting the children, exercise for the reader ;-)
 };

 class LeafNode : public INode {
   public:
     virtual void Accept(IVisitor& i_visitor) override {
       i_visitor.Visit(*this);
     }
 };
```

<p>And the visitor:</p>

<pre class="lang-java prettyprint-override"><code>class IVisitor {
  public:
     virtual void Visit(NodeWithChildren& i_node) = 0;
     virtual void Visit(LeafNode& i_node) = 0;
};

class ConcreteVisitor : public IVisitor
  public:
     virtual void Visit(NodeWithChildren& i_node) override {
       // Do something useful, then...
       for(Node * p_child : i_node) {
         child->Accept(*this);
       }
     }

     virtual void Visit(LeafNode& i_node) override {
        // Just do something useful, there are no children.
     }

};
</code>```

Title: Implementing the Visitor Pattern for an Abstract Syntax Tree

Body:
I'm in the process of creating my own programming language, which I do for learning purposes. I already wrote the lexer and a recursive descent parser for a subset of my language (I currently support mathematical expressions, such as + - * / and parenthesis). The parser hands me back an Abstract Syntax Tree, on which I call the Evaluate method to get the result of the expression. Everything works fine. Here is approximately my current situation (Code examples in C#, although this is pretty much language-agnostic):

```<code>public abstract class Node
{
    public abstract Double Evaluate();
}

public class OperationNode : Node
{
    public Node Left { get; set; }
    private String Operator { get; set; }
    private Node Right { get; set; }

    public Double Evaluate()
    {
        if (Operator == "+")
            return Left.Evaluate() + Right.Evaluate();

        //Same logic for the other operators
    }
}

public class NumberNode : Node
{
    public Double Value { get; set; }

    public Double Evaluate()
    {
        return Value;
    }
}
</code>```

However, I would like to decouple the algorithm from the tree nodes because I want to apply Open/Closed Principle so I don't have to reopen every node class when I want to implement code generation for example. I read that the Visitor Pattern is good for that. I have a good understanding of how the pattern works and that using double dispatch is the way to go. But due to the recursive nature of the tree, I'm not sure how I should approach it. Here is what my Visitor would look like:

```<code>public class AstEvaluationVisitor
{
    public void VisitOperation(OperationNode node)
    {
        // Here is where I operate on the operation node.
        // How do I implement this method?
        // OperationNode has two child nodes, which may have other children
        // How do I work the Visitor Pattern around a recursive structure?

        // Should I access children nodes here and call their Accept method so they get visited?
        // Or should their Accept method be called from their parent's Accept?
    }

    // Other Visit implementation by Node type
}
</code>```

So this is my problem. I want to tackle it immediately while my language does not support a lot of functionnality to avoid having a bigger problem later.

I did not post this to StackOverflow because I don't want you to provide an implementation. I only want you to share ideas and concepts that I might have missed, and how I should approach this.

Body:
I have implemented the visitor pattern on a recursive tree before.

My particular recursive data structure was extremely simple - just three node types: the generic node, an internal node that has children, and a leaf node that has data.  This is much simpler than I expect your AST to be, but perhaps the ideas can scale.

In my case I deliberately did not let the Accept of a node with children call Accept on its children, or to call visitor.Visit(child) from within the Accept. It is the responsibility of the correct "Visit" member implementation of the visitor to delegate Accepts to children of the node being visited.  I chose this way because I wanted to allow different Visitor implementations to be able to decide the order of visitation independently of the tree representation.

A secondary benefit is that there are almost no artifacts of the Visitor pattern inside my tree nodes - each "Accept" just calls "Visit" on the visitor with the correct concrete type.  This makes it easier to locate and understand the visiting logic, it's all inside the visitor implementation.

For clarity I've added some C++-ish pseudocode.  First the nodes:

class INode {
  public:
    virtual void Accept(IVisitor& i_visitor) = 0;
};

class NodeWithChildren : public INode {
  public:
     virtual void Accept(IVisitor& i_visitor) override {
        i_visitor.Visit(*this);
     }
     // Plus interface for getting the children, exercise for the reader ;-)
 };

 class LeafNode : public INode {
   public:
     virtual void Accept(IVisitor& i_visitor) override {
       i_visitor.Visit(*this);
     }
 };

And the visitor:

class IVisitor {
  public:
     virtual void Visit(NodeWithChildren& i_node) = 0;
     virtual void Visit(LeafNode& i_node) = 0;
};

class ConcreteVisitor : public IVisitor
  public:
     virtual void Visit(NodeWithChildren& i_node) override {
       // Do something useful, then...
       for(Node * p_child : i_node) {
         child->Accept(*this);
       }
     }

     virtual void Visit(LeafNode& i_node) override {
        // Just do something useful, there are no children.
     }

};


问:
Why there are no compound assignment operators for logical operators (such as ||, && etc)?
According to ECMA-262, part 11.13, following is the exhaustive list of compound assignment operators: *= /= %= += -= <<= >>= >>>= &= ^= |=.

According to the part 11.11, var c = a || b will put a value into c if ToBoolean(a) is true and will put b value into c otherwise. As such, the logical OR is often used as the coalesce operator, e.g.

```<code>function (options) {
    options = options || {};
}
</code>```

Frequently enough, coalesce is used to specify the default value for the variable, as was shown above: a = a || b.

It seems that compound assignment operator ||= would be really useful, allowing to write the code above in a shorter and cleaner fashion: a ||= b. However, it is not there (although *=, += and other compound assignment operators are).

The question is, why?

答:
The general answer to all questions about "why was this language feature not implemented" is that the team who designed the language decided that the benefit didn't outweigh the cost.

Cost can take many forms.  It takes time and effort to implement a language feature, but there is also the intrinsic cost of complexity: does the feature make the language more complex or ambiguous, out of proportion to its potential benefit?

The hypothetical ||= operator does something fundamentally different from the other compound assignment operators.  While the other operators are purely mathematical in nature, this one is different: it substitutes one value for another (in the context you described).

Given this ambiguity (the operator performs two different functions, depending on context), it's not difficult to see why it was not included in the language.  Although you state that changing

```<code>function (options) {
    options = options || {};
}
</code>```

to

```<code>function (options) {
    options ||= {};
}
</code>```

to perform null coalescing is a valuable feature, the benefit is far less clear to me.  If value substitution is to occur, it seems logical (and clearer) to have both values on the right side of the equals sign, to provide a visual indication that such substitution may occur.

C# took a different path, and uses a specific operator for null coalescing.

OwnerDisplayName: penartur

Body:
The general answer to all questions about "why was this language feature not implemented" is that the team who designed the language decided that the benefit didn't outweigh the cost.

Cost can take many forms.  It takes time and effort to implement a language feature, but there is also the intrinsic cost of complexity: does the feature make the language more complex or ambiguous, out of proportion to its potential benefit?

The hypothetical ||= operator does something fundamentally different from the other compound assignment operators.  While the other operators are purely mathematical in nature, this one is different: it substitutes one value for another (in the context you described).

Given this ambiguity (the operator performs two different functions, depending on context), it's not difficult to see why it was not included in the language.  Although you state that changing

function (options) {
    options = options || {};
}

to

function (options) {
    options ||= {};
}

to perform null coalescing is a valuable feature, the benefit is far less clear to me.  If value substitution is to occur, it seems logical (and clearer) to have both values on the right side of the equals sign, to provide a visual indication that such substitution may occur.

C# took a different path, and uses a specific operator for null coalescing.


问:
How many different configurations are used for software tests?
This article shows that for Android apps, software developers use between 30 and 50 different devices for compatibility tests.

I tried to find information about tests of applications on "classic" computers, for example PC games or graphics-oriented business applications: how many different hardware configurations are typically tested in this area?

答:
We had various Java and Flash-based apps that we tested (so more simple than a game or fully installed app), and we had ~15 testing machines with (iirc) ~20-30 VMs on each for testing.

When you get to that point, you're really testing for regressions - it becomes unfeasible to run every manual test against every hardware/software configuration.


答:
It is up to the visitor implementation to decide whether to visit child nodes and in which order. That's the whole point of the visitor pattern.

In order to adapt the visitor for more situations it is helpful (and quite common) to use generics like this (it's Java):

public interface ExpressionNodeVisitor<R, P> {
    R visitNumber(NumberNode number, P p);
    R visitBinary(BinaryNode expression, P p);
    // ...
}
```

<p>And an <code>accept</code> method would look like this:</p>

<pre class="lang-java prettyprint-override"><code>public interface ExpressionNode extends Node {
    <R, P> R accept(ExpressionNodeVisitor<R, P> visitor, P p);
    // ...
}
</code>```

This allows to pass additional parameters to visitor and retrieve a result from it. So, the expression evaluation can be implemented like this:

public class EvaluatingVisitor
    implements ExpressionNodeVisitor<Double, Void> {
    public Double visitNumber(NumberNode number, Void p) {
        // Parse the number and return it.
        return Double.valueOf(number.getText());
    }
    public Double visitBinary(BinaryNode binary, Void p) {
        switch (binary.getOperator()) {
        case '+':
            return binary.getLeftOperand().accept(this, p)
                + binary.getRightOperand().accept(this, p);
        // More cases for other operators here.
        }
    }
}
```

The accept method parameter isn't used in the above example, but just believe me: it is quite useful to have one. For example, it can be a Logger instance to report errors to.

Body:
It is up to the visitor implementation to decide whether to visit child nodes and in which order. That's the whole point of the visitor pattern.

In order to adapt the visitor for more situations it is helpful (and quite common) to use generics like this (it's Java):

public interface ExpressionNodeVisitor<R, P> {
    R visitNumber(NumberNode number, P p);
    R visitBinary(BinaryNode expression, P p);
    // ...
}

And an accept method would look like this:

public interface ExpressionNode extends Node {
    <R, P> R accept(ExpressionNodeVisitor<R, P> visitor, P p);
    // ...
}

This allows to pass additional parameters to visitor and retrieve a result from it. So, the expression evaluation can be implemented like this:

public class EvaluatingVisitor
    implements ExpressionNodeVisitor<Double, Void> {
    public Double visitNumber(NumberNode number, Void p) {
        // Parse the number and return it.
        return Double.valueOf(number.getText());
    }
    public Double visitBinary(BinaryNode binary, Void p) {
        switch (binary.getOperator()) {
        case '+':
            return binary.getLeftOperand().accept(this, p)
                + binary.getRightOperand().accept(this, p);
        // More cases for other operators here.
        }
    }
}

The accept method parameter isn't used in the above example, but just believe me: it is quite useful to have one. For example, it can be a Logger instance to report errors to.


问:
Barter vs. Cash for a Retailer's eCommerce Site
I am putting together a proposal for a local store with both a brick-n-mortar and web presence. It's an upscale shop that also happens to be one of my wife's favorites. I am considering offering the option of barter for part of the payment. I have two questions in this regard:

What would be a reasonable “exchange rate” for such a transaction? That is, in lieu of $1000 cash money, I should ask for about how much in store credit?

In your own experience, has using barter introduced any complications into the client relationship? Are there particular pitfalls to be concerned about?

答:
Factors to consider:

1) Store mark ups are considerable - generally at least 50%, sometimes 100%.  Essentially paying in store credit could represent a discount of 50% for him.

2) Store credit is only worth something to you if there are things in that store you would genuinely spend money on.

3) The deal has to be good for both of you.

Generally I'd be looking for 3:2 IF the store sold things I wanted / needed. If it didn't then it would be cash only.


答:
Enough to gain sufficient confidence that your software will work on the desired platforms.

You don't test every device, of course; you decide how much coverage of your target audience you want, and then structure your tests around the devices you think the vast majority of your audience has.

Unless your software requires exotic hardware (CUDA, perhaps, or multi-channel sound cards), it's easier to test software on PC platforms.  Your concerns have more to do with "system requirements" (things like processor speed, RAM and hard disk space) than they do with differences between computers, and software frameworks such as .NET are designed to run on almost any device that is PC compatible.

Title: How many different configurations are used for software tests?

Body:
This article shows that for Android apps, software developers use between 30 and 50 different devices for compatibility tests.

I tried to find information about tests of applications on "classic" computers, for example PC games or graphics-oriented business applications: how many different hardware configurations are typically tested in this area?


答:
We make a .Net obfuscation product. Because we are quite conservative and strive for compatibility, we must test on a lot of different platforms.

Some platforms:

Windows XP 32bit

Windows Vista 32 and 64bit

Windows 7 32 and 64bit

Windows 8 32 and 64 bit

And then we also have to test for different versions of .Net

.Net 3.5

.Net 3.5 SP1

.Net 4.0

.Net 4.5

and then we have to test that the outputted programs must work on an even more broad set of versions.

However, I'd say you should do general QA testing (like after each feature is implemented) on a few different "popular" set of systems and then before a release do much more broad(but not as deep) testing across all platforms you plan to support. Virtual Machines, a server to run them on, and an MSDN subscription is your friend :)


答: One possible reason is that the logical operators && and || have "short-circuiting" behavior.  The right-hand operand of && and || is not evaluated unless necessary.  Perhaps for this reason the language designers decided that the meaning of an expression like a ||= f() was not obvious, and so such operators were better left out.

Title: Why there are no compound assignment operators for logical operators (such as ||, && etc)?

Body:
According to ECMA-262, part 11.13, following is the exhaustive list of compound assignment operators: *= /= %= += -= <<= >>= >>>= &= ^= |=.

According to the part 11.11, var c = a || b will put a value into c if ToBoolean(a) is true and will put b value into c otherwise. As such, the logical OR is often used as the coalesce operator, e.g.

```<code>function (options) {
    options = options || {};
}
</code>```

Frequently enough, coalesce is used to specify the default value for the variable, as was shown above: a = a || b.

It seems that compound assignment operator ||= would be really useful, allowing to write the code above in a shorter and cleaner fashion: a ||= b. However, it is not there (although *=, += and other compound assignment operators are).

The question is, why?


问:
Why is test driven development missing from Joel's Test?
I was reading this blog by Joel Spolsky about 12 steps to better code. The absence of Test Driven Development really surprised me. So I want to throw the question to the Gurus. Is TDD not really worth the effort?

答:
Joel Spolsky himself answered this question back in 2009:

Joel: There's a debate over Test Driven Development... should you have
  unit tests for everything, that kind of stuff... a lot of people write
  to me, after reading The Joel Test, to say, "You should have a 13th
  thing on here: Unit Testing, 100% unit tests of all your code."

And that strikes me as being just a little bit too doctrinaire about
  something that you may not need. Like, the whole idea of agile
  programming is not to do things before you need them, but to
  page-fault them in as needed. I feel like automated testing of
  everything, a lot of times, is just not going to help you. In other
  words, you're going to write an awful lot of unit tests to insure that
  code that, really, is going to work, and you're definitely going to
  find out if it doesn't work [if you don't write the tests] does,
  actually still work, ... I don't know, I'm going to get such flame
  mail for this because I'm not expressing it that well. But, I feel
  like if a team really did have 100% code coverage of their unit tests,
  there'd be a couple of problems. One, they would have spent an awful
  lot of time writing unit tests, and they wouldn't necessarily be able
  to pay for that time in improved quality. I mean, they'd have some
  improved quality, and they'd have the ability to change things in
  their code with the confidence that they don't break anything, but
  that's it.

But the real problem with unit tests as I've discovered is that the
  type of changes that you tend to make as code evolves tend to break a
  constant percentage of your unit tests. Sometimes you will make a
  change to your code that, somehow, breaks 10% of your unit tests.
  Intentionally. Because you've changed the design of something...
  you've moved a menu, and now everything that relied on that menu being
  there... the menu is now elsewhere. And so all those tests now break.
  And you have to be able to go in and recreate those tests to reflect
  the new reality of the code.

So the end result is that, as your project gets bigger and bigger, if
  you really have a lot of unit tests, the amount of investment you'll
  have to make in maintaining those unit tests, keeping them up-to-date
  and keeping them passing, starts to become disproportional to the
  amount of benefit that you get out of them.


问:
Storing in-text metadata in a discrete data structure
I am developing an application which will need to store inline, intext metadata. What I mean by that is the following: let's say we have a long text, and we want to store some metadata connected with a specific word, or sentence of the text.

What would be the best way to store this information?

My first thought was to include in the text some kind of Markdown syntax that would then be parsed on retrieving. Something looking like this:

```<code>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam __nonummy nibh__[@note this sounds really funny latin]
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
</code>```

This would introduce two problems I can think of:

A relatively small one, is that if said syntax happen to be fortuitously on the said text, it can mess with the parsing.

The most important one is that this doesn't maintain this metadata separate from the text itself.

I would like to have a discrete data structure to hold this data, such a different DB Table in which these metadatas are stored, so that I could use them in discrete ways: querying, statistics, sorting, and so on.

EDIT: Since the answerer deleted his answer, I think it might be good to add his suggestion here, since it was a workable suggestion that expanded on this first concept. The poster suggested to use a similar syntax, but to link the metadata to the PRIMARY KEY of the metadata database table.

Something that would look like this:

```<code>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam __nonummy nibh__[15432]
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
</code>```

Where 15432 would be the ID of a table row containing the necessary, queriable information, as per example below.

My second thought was to store information of this kind in a DB Table looking like this:

```<code>TABLE: metadata

ID    TEXT_ID    TYPE    OFFSET_START    OFFSET_END    CONTENT
1     lipsum     note    68              79            this sounds really funny latin
</code>```

In this way the metadata would have a unique id, a text_id as a foreign key connected to table storing the texts and it would connect the data with the text itself by using a simple character offset range.

This would do the trick of keeping the data separated from the metadata, but a problem that I can immediately see with this approach is that the text would be fundamentally not editable. Or, if I wanted to implement the editing of the text after the assignation of metadata, I would basically have to calculate characters additions, or removal compared to the previous version, and check whether each of this modifications adds or remove characters before or after each of the associated metadata.

Which, to me, sounds like a really unelegant approach.

Do you have any pointers or suggestions for how I could approach the problem?

Edit 2: some XML problems

Adding another case which would make quite necessary for this separation of data and metadata to happen.

Let's say I want to make it possible for different users to have different metadata sets of the same text, with or without the possibility of each user actually displaying the other user metadata.

Any solution of the markdown kind (or HTML, or XML) would be difficult to implement at this point. The only solution in this case that I could think about would be to have yet another DB Table which would contain the single user version of the original text, connecting to the original text table by the use of a FOREIGN KEY.

Not sure if this is very elegant either.

XML has a hierarchical data model: any element which happens to be within the borders of another element is considered as its child, which is most often not the case in the data model I'm looking for; in XML any children element must be closed before the parent tag can be closed, allowing for no overlapping of elements.

Example:

<note content="the beginning of the famous placeholder"> Lorem ipsum
  dolor sit <comment content="I like the sound of amet/elit"> amet </note>,
  consectetuer adipiscing elit </comment> , <note content="adversative?"> sed
  diam <note content="funny latin"> nonummy </note> nibh </note> euismod
  tincidunt ut laoreet dolore magna aliquam erat volutpat.

Here we have two different problems:

Different elements overlapping: The first comment starts within the first note, but ends after the end of the first note, i.e. it's not its child.

Same elements overlapping: The last note and the boldfaced note overlap; however, since they are the same kind of element, the parser would close the lastly opened element at the first closure, and the first opened element at the last closure, which, in this circumstance, is not what is intended.

答:
I'd go for a mix of your solutions, but instead, I'd use a standard : XML. You'd have a syntax like this one

```<code>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam <note content="It sound really funny in latin">nonummy nibh</note>
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
</code>```

Why XML

If you think about it, it's exactly how the whole web is structured : content (actual text) that carries semantic - what you're calling metadata - through html tags.

This way you have a really cool world that opens :

Free parser

Battle tested way to add metadata to content

Ease of use (depending on which users you are targeting)

You can easily extract the raw text, without the metadata, as it's a standard features on XML parsers. That is very useful to have an indexable version of your content, so Lorem <note>ipsum</note> is raised when you are searching for lorem ips* for example.

Why XML over Markdown

A website like stackexchange uses markdown as the semantics its content convey is rather basic : emphasis, links/urls, image, header etc. It seems the semantic you're adding to your content is

More complex

Subject to change or must be extensible

Thus I sense Markdown wouldn't be a really good idea. Also Markdown isn't really standardized, and parsing/dumping it might be a pain in the ass, even more a markdownish syntax see Jeff Atwood's post about the WTF he met on parsing Markdown.

On separation between data and metadata

Per se, such separation isn't mandatory. I assume you are looking for the advantage it brings:

Possibility to have the raw content without the metadata

Separation of concerns: I don't want to have side-effect/complexity overhead when manipulating metadata because of the data, and otherwise.

All these concerns are cleared by the use of XML. From the XML, you can easily dump any tag-stripped content, and data/metadata are separated, just like attribute and actual text is separated in XML.

Also I don't think you can really have your metadata totally not bound to your data. From what you describe, your metadata are a composition of your data, ie deleting the data leads to metadata deletion. This is where you metadata diverge from the usual HTML/CSS. CSS doesn't disapear when an html element is removed, because it can be applied to other elements. I don't feel this is the case in your metadata.

Having metadata close to the data, as in XML or Markdown, allow an easy understanding (and maybe debugging) of the datas. Also, the example you give on your second thought add some complexity, because for each data I'm reading, I need to query the metadata table to get these. If the relation between your data and your metadata is 1:1 or 1:N, then it's IMO clearly useless, and only brings complexity (a good case of YAGNI).

Body:
I'd go for a mix of your solutions, but instead, I'd use a standard : XML. You'd have a syntax like this one

Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam <note content="It sound really funny in latin">nonummy nibh</note>
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Why XML

If you think about it, it's exactly how the whole web is structured : content (actual text) that carries semantic - what you're calling metadata - through html tags.

This way you have a really cool world that opens :

Free parser

Battle tested way to add metadata to content

Ease of use (depending on which users you are targeting)

You can easily extract the raw text, without the metadata, as it's a standard features on XML parsers. That is very useful to have an indexable version of your content, so Lorem <note>ipsum</note> is raised when you are searching for lorem ips* for example.

Why XML over Markdown

A website like stackexchange uses markdown as the semantics its content convey is rather basic : emphasis, links/urls, image, header etc. It seems the semantic you're adding to your content is

More complex

Subject to change or must be extensible

Thus I sense Markdown wouldn't be a really good idea. Also Markdown isn't really standardized, and parsing/dumping it might be a pain in the ass, even more a markdownish syntax see Jeff Atwood's post about the WTF he met on parsing Markdown.

On separation between data and metadata

Per se, such separation isn't mandatory. I assume you are looking for the advantage it brings:

Possibility to have the raw content without the metadata

Separation of concerns: I don't want to have side-effect/complexity overhead when manipulating metadata because of the data, and otherwise.

All these concerns are cleared by the use of XML. From the XML, you can easily dump any tag-stripped content, and data/metadata are separated, just like attribute and actual text is separated in XML.

Also I don't think you can really have your metadata totally not bound to your data. From what you describe, your metadata are a composition of your data, ie deleting the data leads to metadata deletion. This is where you metadata diverge from the usual HTML/CSS. CSS doesn't disapear when an html element is removed, because it can be applied to other elements. I don't feel this is the case in your metadata.

Having metadata close to the data, as in XML or Markdown, allow an easy understanding (and maybe debugging) of the datas. Also, the example you give on your second thought add some complexity, because for each data I'm reading, I need to query the metadata table to get these. If the relation between your data and your metadata is 1:1 or 1:N, then it's IMO clearly useless, and only brings complexity (a good case of YAGNI).


问:
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.

答:
If you're not typing, you're not working.

I believe zombie blank stares and coffee walks are essential to programmers organising things in their heads.


问:
Prevent developers from using constants
I have one one software system which allows developers to specify an ID or name to create NodeReferences. Both work fine, but ID's are not guaranteed to be the same across different environments. I've tried in documentation and in conversations to stress that ID's should not be hard coded (since they will break when deployed to a different environments), but some developers are still using them.

This works only in dev environment:

```<code>var level = LevelReference.ById(20);
var node = NodeReference.ByName(level, _patientGuid.ToString());
</code>```

This works in all environments:

```<code>var app = ApplicationReference.ByName("Reporting");
var area = AreaReference.ByName(app, "Default");
var level = LevelReference.ByName(area, "Patient");
var node = NodeReference.ByName(level, _patientGuid.ToString());
</code>```

I think the appeal is just that it produces fewer lines of code. The use of ID's is not by itself bad (since there are valid use cases like caching the ID returned from the server and using it later for faster look-up), but hard-coded ID's are bad. Most of the time the first code will throw an exception, but it's possible that it could be a valid ID for a different object than the developer intended, and this could result in very bad problems.

What's the best way to discourage the use of such constants in code? Ideally I'd like throw some kind of compiler error when I see code like the first example, or at least throw an exception before the call gets down to the database.

答:
If I understand correctly, those IDs are the primary keys (identity column) in the database. In this case, a workaround would be not to forbid or track the constants in code, but simply randomize those keys in the deployment script.

Since IDs are not guaranteed to stay the same in the test data, the only solution for the developers would be to move to something more reliable - in your case, names.

Title: Prevent developers from using constants


答:
Hide the int ids in opaque objects/structs;

```<code>var id = level.id;
</code>```

Here id is such a struct.

This way you can remove the ById(int) method and replace it with ById(Id) and it still lets you keep the cashed Ids for future use.

You can also create unique ID types for each reference type to ensure type safety (so you can't do NodeReference.ById(level.id)).

Title: Prevent developers from using constants

Body:
I have one one software system which allows developers to specify an ID or name to create NodeReferences. Both work fine, but ID's are not guaranteed to be the same across different environments. I've tried in documentation and in conversations to stress that ID's should not be hard coded (since they will break when deployed to a different environments), but some developers are still using them.

This works only in dev environment:

```<code>var level = LevelReference.ById(20);
var node = NodeReference.ByName(level, _patientGuid.ToString());
</code>```

This works in all environments:

```<code>var app = ApplicationReference.ByName("Reporting");
var area = AreaReference.ByName(app, "Default");
var level = LevelReference.ByName(area, "Patient");
var node = NodeReference.ByName(level, _patientGuid.ToString());
</code>```

I think the appeal is just that it produces fewer lines of code. The use of ID's is not by itself bad (since there are valid use cases like caching the ID returned from the server and using it later for faster look-up), but hard-coded ID's are bad. Most of the time the first code will throw an exception, but it's possible that it could be a valid ID for a different object than the developer intended, and this could result in very bad problems.

What's the best way to discourage the use of such constants in code? Ideally I'd like throw some kind of compiler error when I see code like the first example, or at least throw an exception before the call gets down to the database.

Body:
Hide the int ids in opaque objects/structs;

var id = level.id;

Here id is such a struct.

This way you can remove the ById(int) method and replace it with ById(Id) and it still lets you keep the cashed Ids for future use.

You can also create unique ID types for each reference type to ensure type safety (so you can't do NodeReference.ById(level.id)).


答:
Smack their hand in code review.

That said, is there a real difference between LevelReference.ById() and LevelReference.ByName()? In your example you are using hard coded values in both.

In one code base I've worked on we handled a similar situation by predefining the "hard coded" values that are set up with our database setup script and have an enumeration that maps an enumerated value to the database value.

Title: Prevent developers from using constants


问:
Using a public username as a login username
It has just dawned on me, that a system I am developing exposes a users username in the URI. This is a problem, since some of the users pages are public. Therefore people will know their username.

I thought that this would be a security issue, but then realised that big names like twitter do the same thing. Pretty much every single twitter user has their username on full display.

If a big name like twitter see it as safe, should I also assume the same?

答:
Pretty much every website I know does the same.

Account security relies on password, not the user name. This password should be kept secret and secure.

If it is, it doesn't matter who knows the user names.

If it doesn't, deal with it, because it's the primary issue: hiding user names won't help.

Note that relying on the fact that the web application doesn't display the user name is problematic for a few more reasons:

If the database is hacked, the hacker has the names of every user. While you can (and should) avoid storing users' passwords anywhere on the servers, you may not be able to do the same with user names. For example, storing only the hash of the e-mail makes it impossible to contact the person later by e-mail.

With a bit of social engineering, it's easy to determine what is the user name or the e-mail address which is used to access the web application. Let's take an example. You want to know what do I use to log in to Stack Exchange. From my profile, you get my real name. A quick Google search for it reveals my Google+ profile with my personal e-mail address, as well as my full profile on the website of my company as the first search result, this second profile containing my business e-mail address. This gives you two potential addresses.

From Gravatar, you learn that the MD5 hash of my e-mail address is

```<code>0f379b115b9090a1df9319f17574fa8b
</code>```

Surprisingly, two e-mail addresses you've previously found have different hashes:

```<code>97ec33bbad0a2e26f7fcc1feea6447fc
60597478d2736c4eeb915327474e8fab
</code>```

Let's see what additional information we can get. We can:

Either explore my profile on my company's website in order to find a screenshot of Password Manager, an app I developed. This screenshot displays two e-mail addresses: my personal one, already found through Google+, and a new one. A quick MD5 test reveals that it matches.

Or look at Google results for my first and last name and notice that they mention lakaidreams.com. A whois search shows not only that I'm the owner of the domain, but also reveals the very same e-mail address.

As you see, if Stack Exchange was relying on the secrecy of my e-mail address to prevent unauthorized access to my account, you couldn't be sure if the person who is typing this answer is really me.

Body:
Pretty much every website I know does the same.

Account security relies on password, not the user name. This password should be kept secret and secure.

If it is, it doesn't matter who knows the user names.

If it doesn't, deal with it, because it's the primary issue: hiding user names won't help.

Note that relying on the fact that the web application doesn't display the user name is problematic for a few more reasons:

If the database is hacked, the hacker has the names of every user. While you can (and should) avoid storing users' passwords anywhere on the servers, you may not be able to do the same with user names. For example, storing only the hash of the e-mail makes it impossible to contact the person later by e-mail.

With a bit of social engineering, it's easy to determine what is the user name or the e-mail address which is used to access the web application. Let's take an example. You want to know what do I use to log in to Stack Exchange. From my profile, you get my real name. A quick Google search for it reveals my Google+ profile with my personal e-mail address, as well as my full profile on the website of my company as the first search result, this second profile containing my business e-mail address. This gives you two potential addresses.

From Gravatar, you learn that the MD5 hash of my e-mail address is

0f379b115b9090a1df9319f17574fa8b

Surprisingly, two e-mail addresses you've previously found have different hashes:

97ec33bbad0a2e26f7fcc1feea6447fc
60597478d2736c4eeb915327474e8fab

Let's see what additional information we can get. We can:

Either explore my profile on my company's website in order to find a screenshot of Password Manager, an app I developed. This screenshot displays two e-mail addresses: my personal one, already found through Google+, and a new one. A quick MD5 test reveals that it matches.

Or look at Google results for my first and last name and notice that they mention lakaidreams.com. A whois search shows not only that I'm the owner of the domain, but also reveals the very same e-mail address.

As you see, if Stack Exchange was relying on the secrecy of my e-mail address to prevent unauthorized access to my account, you couldn't be sure if the person who is typing this answer is really me.


答:
It depends enormously on the guarantees you want to provide to your customers.

If you don't advertise anything, then it should be sufficient to test only on a single platform.

If you state that it works on platforms X, Y and Z, then you better have the test reports to prove it.

And this is where it gets interesting. With PC applications, people tend to be far more accepting of bugs or incompatibilities than with other electronic devices, such as mobile phones. This is reflected in the testing effort and for that reason, major app developers test their app with such a large number of devices, just so they can account for any possible incompatibility.

As an anecdote, I have worked for a company making car-kits (so you can use your mobile phone in a car). Those car-kits get tested against just about every mobile phone that is on the market, because people just don't accept it if their phone does not interoperate flawlessly with their car-kit.


答:
Provide a better API:

```<code>var node = NodeReference.byName("Reporting", "Default", "Patient", _patientGuid.ToString());
</code>```

Or provide utility functions to fetch important nodes

```<code>var node = NodeReference.byName( theDefaultPatientNode(), _patientGuid.ToString() );
</code>```

Or have the various nodes in an enum, and do something like:

```<code>var node = NodeReference.byCategory( REPORT_PATIENT, _patientGuid.ToString() );
</code>```

You aren't going to be able to sell writing 4 lines of code to do something this simple. They are trying to use ids because its too hard to fetch the relevant object otherwise. So make it easier!

Title: Prevent developers from using constants

Body:
Provide a better API:

var node = NodeReference.byName("Reporting", "Default", "Patient", _patientGuid.ToString());

Or provide utility functions to fetch important nodes

var node = NodeReference.byName( theDefaultPatientNode(), _patientGuid.ToString() );

Or have the various nodes in an enum, and do something like:

var node = NodeReference.byCategory( REPORT_PATIENT, _patientGuid.ToString() );

You aren't going to be able to sell writing 4 lines of code to do something this simple. They are trying to use ids because its too hard to fetch the relevant object otherwise. So make it easier!


答:
Code like

```<code>var level = LevelReference.ById(20);
</code>```

should never pass a code review, because it contains magic numbers. That alone should be reason enough to ban such practices.

And if they try to work around it by creating named constants, the reviewer should ask the author for where he got the guarantee that the number is correct for all deployments.

Title: Prevent developers from using constants

Body:
Code like

var level = LevelReference.ById(20);

should never pass a code review, because it contains magic numbers. That alone should be reason enough to ban such practices.

And if they try to work around it by creating named constants, the reviewer should ask the author for where he got the guarantee that the number is correct for all deployments.


问:
Why do we program each file separately and place them in separate folders and how do all these file come together?
I was wondering how the cover flow effect is coded. I used this link which gave me the code on how it all worked out :  http://luwes.co/labs/js-cover-flow/. I am completely new to complex programs so I had a hard time in understanding how it all works out.

Why do we program each file separately and place them in separate folders and how do all these file come together? Why is there build files, what do they do?

答:
Looking at the build file, it is just a command line, I saw uglifyjs2 which is being passed on the command line a list of files.  I googled uglifyjs2 and apperently it is a combiner/minifier.  You can remove most of the whitespace and comments in a javascript file and it will work fine, so we do so to make the file smaller when downloaded to the browser.  This is minification.  We also combine multiple javascript files into one so that only one request is needed to retrieve them.

They are edited in seperate files just to make it easier to understand the layout of the program.  There are other reasons that relate to version control, architecture, frequency of change, etc. that might have been a factor in the developer deciding how to sepereate them out.  Some might actually be javascript files from other projects on which this program depends/needs.  Since those files might be updated by the other projects, keeping them separate allows the developer to just copy the file over the old one when it is updated.  This would be very difficult if he copied those other project's code into a single file.

Since for development you want seperate files, the build file is an automated way to to keep the files seperate, but combine them whenever you want to create the single minified/combined "release" file that you will provide to those who want to use your tool/application.


问:
Where can I turn to if I can't fix a bug?
I am looking for resources to turn to when I don't have the answer for something. I lead a team of software developers. We have been rolling out new software releases on a monthly basis.

When there is a bug that my team cannot fix, it lands on me. Most of the time I can resolve the issue, but there are times when I get stuck.

Unfortunately, I'm the top of the line at our company. There is nobody I can ask for help or assistance in figuring something out.

Do you happen to have any recommendations or guidance for situations like this?

答:
First, you can get better at debugging.  Debugging by David Agans is a good start for helping you improve.  If you don't know how to use a debugger, now is a good time to learn.

Second, you can make your code more debuggable.  Adding unit tests would be the number one suggestion in this area.  Adding logging is another excellent idea.  Learn some design principles and refactor the code to make it cleaner.  On the off chance you aren't using source control, start now.

Finally, ask for help online.  That's what this site and StackOverflow are all about.  Learning techniques like creating short, self-contained, correct examples can both help with debugging in the first place as well as help you get better answers.


问:
NoSQL (Azure Table Storage) RowKey design for ordered data
I store large quantities of GPS data in storage tables.  Each partition can reach up to 1 million entities.  Each GPS entity that is inserted into the table is actually sequential to the previous data inserted, so order matters.

Sometimes I need to perform the following query:

Get the previous/next 3 GPS entities from the current entity (within the same partition).

Options for RowKey design:

Create an incrementing integer.  But how do I track what the current size of the table is?  There is no way to get table row count, or to get the last inserted row.

Use DateTime Ticks.  But how do get the previous/next entity using ticks?

I'm using the SDK version 2.0 in C#.

答:
I think you will need to have a RowKey such Ticks + Guid - and I think you will have to specify a time-measurement precision that is meaningful for your GPS application. You want three data that are sequential in real time not just the recorded time. If you just use Ticks, then you'll end up with duplicates as described in this post: Why am I getting duplicate RowKey with DateTime.UtcNow.Ticks?  Your time measurement system has a finite precision.

You will still need to query the partition for all entities in the partition. But you should then be able to identify data that is truly in time sequence to the practical precision of your system.


问:
What is the best way to store a table in C++
I'm programming a decision tree in C++ using a slightly modified version of the C4.5 algorithm. Each node represents an attribute or a column of your data set and it has a children per possible value of the attribute.

My problem is how to store the training data set having in mind that I have to use a subset for each node so I need a quick way to only select a subset of rows and columns.

The main goal is to do it in the most memory and time efficient possible (in that order of priority).

The best way I have thought of is to have an array of arrays (or std::vector), or something like that, and for each node have a list (array, vector, etc) or something with the column,line(probably a tuple) pairs that are valid for that node.

I now there should be a better way to do this, any suggestions?

UPDATE: What I need is something like this:

In the beginning I have this data:

```<code>Paris    4    5.0    True
New York 7    1.3    True
Tokio    2    9.1    False
Paris    9    6.8    True
Tokio    0    8.4    False
</code>```

But for the second node I just need this data:

```<code>Paris    4    5.0
New York 7    1.3
Paris    9    6.8
</code>```

And for the third node:

```<code>Tokio    2    9.1
Tokio    0    8.4
</code>```

But with a table of millions of records with up to hundreds of columns.

What I have in mind is keep all the data in a matrix, and then for each node keep the info of the current columns and rows. Something like this:

```<code>Paris    4    5.0    True
New York 7    1.3    True
Tokio    2    9.1    False
Paris    9    6.8    True
Tokio    0    8.4    False
</code>```

Node 2:

```<code>columns = [0,1,2]
rows = [0,1,3]
</code>```

Node 3:

```<code>columns = [0,1,2]
rows = [2,4]
</code>```

This way on the worst case scenario I just have to waste

```<code>size_of(int) * (number_of_columns + number_of_rows) * node
</code>```

That is a lot less than having an independent data matrix for each node.

答:
One thing you can do on your model to save some space is managing indexes on your nodes as bit arrays. So from your example:

Node 2:

columns = [0,1,2] = 5 or 101

rows = [0,1,3] = 11 or  1011

Node 3:

columns = [0,1,2] = 5 or 101

rows = [2,4] = 20 or 10100

This would take your requirement from size_of(int) * (number_of_columns + number_of_rows) * node
to sizeof(int) * 2 * node

This approach will restrict your matrix dimension to a sizeof(int) columns and same number of rows.
To overcome this limitation (specially strong on rows) you could store them on blocks. In that case, you
will need a new integer on each node specifying the block, making your total index size to sizeof(int)*3*node
which is still lower than size_of(int) * (number_of_columns + number_of_rows) * node


答: Try pairing with the developer who worked on the issue before you. The two of you might be able to fix the bug. If you can narrow the problem down to a function or a few lines of code, a website like StackOverflow could help. Also advisable would be to write a test for the bug so you know when you've fixed it (or if it returns).</p>

Title: Where can I turn to if I can't fix a bug?

Body:
I am looking for resources to turn to when I don't have the answer for something. I lead a team of software developers. We have been rolling out new software releases on a monthly basis.

When there is a bug that my team cannot fix, it lands on me. Most of the time I can resolve the issue, but there are times when I get stuck.

Unfortunately, I'm the top of the line at our company. There is nobody I can ask for help or assistance in figuring something out.

Do you happen to have any recommendations or guidance for situations like this?