答:
There are several methodologies that have evolved over the years to deal with these issues you've mentioned, which are, I agree, the two main issues that UI frameworks have had to address in recent years. Coming from a WPF background, these are approached as follows:

Declarative design, rather than imperative

When you describe painstakingly writing code to instantiate controls and set their properties, you're describing the imperative model of UI design. Even with the WinForms designer, you're just using a wrapper over that model - open the Form1.Designer.cs file and you see all that code sitting there.

With WPF and XAML - and similar models in other frameworks, of course, from HTML onwards - you're expected to describe your layout, and let the framework do the heavy lifting of implementing it. You use smarter controls such as Panels (Grid, or WrapPanel, etc) to describe the relationship between UI elements, but the expectation is that you don't manually position them.
Flexible concepts such as repeatable controls - like ASP.NET's Repeater or WPF's ItemsControl - help you create dynamically scaling UI without writing repeating code, allowing dynamically growing data entities to be represented dynamically as controls.

WPF's DataTemplates allow you to define - again, declaratively - little nuggets of UI goodness and match them to your data; for instance, a list of Customer data objects might be bound to an ItemsControl, and a different data template invoked depending on whether he's a regular employee (use a standard grid row template with name and address) or a Prime Customer, whereas a different template, with a picture and easy-to-access buttons are displayed. Again, without writing code in the specific window, just smarter controls that are aware of their data-context, and thus allow you to simply bind them to your data and let them perform relevant operations.

Data Binding and Command Separation

Touching on data binding, WPF's databinding (and, again, in other frameworks as well, like AngularJS) allows you to state your intent by linking a control (say, a textbox) with a data entity (say, the Customer's Name) and let the framework handle the plumbing. Logic is handled similarly. Instead of manually wiring up code-behind event-handlers to Controller-based business-logic, you use the Data Binding mechanism to link a controller's behavior (say, a button's Command property) to a Command object which represents the nugget of activity.

It allows this Command to be shared between windows without rewriting the event handlers every time.

Higher Level of Abstraction

Both of these solutions to your two problems represent a move to a higher level of abstraction than the event-driven paradigm of Windows Forms that you rightfully find tiresome.

The idea is that you don't want to define, in code, every single property that the control has, and every single behavior starting from the button click and onwards. You want your controls and underlying framework to do more work for you and allow you to think in more abstract concepts of Data Binding (which exists in WinForms, but is nowhere near as useful as in WPF) and the Command pattern to define links between UI and behavior that don't require getting down to the metal.

The MVVM pattern is Microsoft's approach to this paradigm. I suggest reading up on that.

This is a rough example of how this model would look and how it would save you time and lines of code. This won't compile, but it's pseudo-WPF. :)

Somewhere in your application resources, you define Data Templates:

```<code><DataTemplate x:DataType="Customer">
   <TextBox Text="{Binding Name}"/>
</DataTemplate>

<DataTemplate x:DataType="PrimeCustomer">
   <Image Source="GoldStar.png"/>
   <TextBox Text="{Binding Name}"/>
</DataTemplate>
</code>```

Now, you link your main screen to a ViewModel, a class which exposes your data. Say, a collection of Customers (simply a List<Customer>) and a Command object (again, a simple public property of type ICommand). This link allows binding:

```<code>public class CustomersnViewModel
{
     public List<Customer> Customers {get;}
     public ICommand RefreshCustomerListCommand {get;}
}
</code>```

and the UI:

```<code><ListBox ItemsSource="{Binding Customers}"/>
<Button Command="{Binding RefreshCustomerListCommand}">Refresh</Button>
</code>```

And that's it. The ListBox's syntax will grab the list of Customers off of the ViewModel and attempt to render them to the UI. Because of the two DataTemplates we defined earlier, it will import the relevant template (based on the DataType, assuming PrimeCustomer inherits from Customer) and put it as the contents of the ListBox. No looping, no dynamic generation of controls via code.

The Button, similarly, has preexisting syntax to link its behavior to an ICommand implementation, which presumably knows to update the Customers property - prompting the data-binding framework to update the UI again, automatically.

I've taken some shortcuts here, of course, but this is the gist of it.

Title: Is there some sort of systematic strategy for designing and implementing GUIs?

Body:
I am using Visual Studio to create a GUI application in C#. The Toolbox serves as a nifty component palette that allows me to easily drag and drop buttons and other elements (for clarity I'll say button whenever I mean "control") onto my form, which makes static forms quite easy to do. However, I run into two problems:

Creating the buttons in the first place is a lot of work. When I have a form that is not static (ie. buttons or other controls are created at run time according to what the user does) I cannot use the palette at all. Instead I have to create each button manually, by calling the constructor in whatever method I am using, and then manually initialize by specifying button height, width, position, label, event handler and so on. This is extremely tedious because I have to guess at all these cosmetic parameters without being able to see what the form will look like, and it also generates many lines of repetitive code for each button.

Making the buttons do something is also a lot of work. Dealing with events in a full-featured application is a huge pain. The only way I know how to do this is to select a button, go to the events tab in its properties, click the OnClick event so that it generates the event in the Form's code, then fill in the body of the event. Since I want to separate logic and presentation, all of my event handlers end up being single-line calls to the appropriate business logic function. But using this for many buttons (for instance, imagine the number of buttons present in an application like MS Word) pollutes the code of my Form with dozens of boilerplate event handler methods and it's difficult to maintain this.

Because of these, any GUI program more complicated than Hello World is very impractical to actually make for me. To be clear, I have no problems whatsoever dealing with complexity in programs that I write which have minimal UI - I feel like I am able to use OOP with a fair degree of competence to neatly structure my business logic code. But when developing the GUI, I'm stuck. It seems so tedious that I feel like I'm reinventing the wheel, and there's a book somewhere out there explaining how to do GUI properly that I haven't read.

Am I missing something? Or do all C# developers just accept the endless lists of repetitive event handlers and button creation code?

As a (hopefully helpful) hint, I expect that a good answer will talk about:

Using OOP techniques (such as the factory pattern) to simplify repeated button creation

Combining many event handlers into a single method that checks Sender to figure out which button called it, and behaves accordingly

XAML and using WPF instead of Windows Forms

You don't have to mention any of these, of course. It's just my best guess as to what sort of answer I'm looking for.

Body:
There are several methodologies that have evolved over the years to deal with these issues you've mentioned, which are, I agree, the two main issues that UI frameworks have had to address in recent years. Coming from a WPF background, these are approached as follows:

Declarative design, rather than imperative

When you describe painstakingly writing code to instantiate controls and set their properties, you're describing the imperative model of UI design. Even with the WinForms designer, you're just using a wrapper over that model - open the Form1.Designer.cs file and you see all that code sitting there.

With WPF and XAML - and similar models in other frameworks, of course, from HTML onwards - you're expected to describe your layout, and let the framework do the heavy lifting of implementing it. You use smarter controls such as Panels (Grid, or WrapPanel, etc) to describe the relationship between UI elements, but the expectation is that you don't manually position them.
Flexible concepts such as repeatable controls - like ASP.NET's Repeater or WPF's ItemsControl - help you create dynamically scaling UI without writing repeating code, allowing dynamically growing data entities to be represented dynamically as controls.

WPF's DataTemplates allow you to define - again, declaratively - little nuggets of UI goodness and match them to your data; for instance, a list of Customer data objects might be bound to an ItemsControl, and a different data template invoked depending on whether he's a regular employee (use a standard grid row template with name and address) or a Prime Customer, whereas a different template, with a picture and easy-to-access buttons are displayed. Again, without writing code in the specific window, just smarter controls that are aware of their data-context, and thus allow you to simply bind them to your data and let them perform relevant operations.

Data Binding and Command Separation

Touching on data binding, WPF's databinding (and, again, in other frameworks as well, like AngularJS) allows you to state your intent by linking a control (say, a textbox) with a data entity (say, the Customer's Name) and let the framework handle the plumbing. Logic is handled similarly. Instead of manually wiring up code-behind event-handlers to Controller-based business-logic, you use the Data Binding mechanism to link a controller's behavior (say, a button's Command property) to a Command object which represents the nugget of activity.

It allows this Command to be shared between windows without rewriting the event handlers every time.

Higher Level of Abstraction

Both of these solutions to your two problems represent a move to a higher level of abstraction than the event-driven paradigm of Windows Forms that you rightfully find tiresome.

The idea is that you don't want to define, in code, every single property that the control has, and every single behavior starting from the button click and onwards. You want your controls and underlying framework to do more work for you and allow you to think in more abstract concepts of Data Binding (which exists in WinForms, but is nowhere near as useful as in WPF) and the Command pattern to define links between UI and behavior that don't require getting down to the metal.

The MVVM pattern is Microsoft's approach to this paradigm. I suggest reading up on that.

This is a rough example of how this model would look and how it would save you time and lines of code. This won't compile, but it's pseudo-WPF. :)

Somewhere in your application resources, you define Data Templates:

<DataTemplate x:DataType="Customer">
   <TextBox Text="{Binding Name}"/>
</DataTemplate>

<DataTemplate x:DataType="PrimeCustomer">
   <Image Source="GoldStar.png"/>
   <TextBox Text="{Binding Name}"/>
</DataTemplate>

Now, you link your main screen to a ViewModel, a class which exposes your data. Say, a collection of Customers (simply a List<Customer>) and a Command object (again, a simple public property of type ICommand). This link allows binding:

public class CustomersnViewModel
{
     public List<Customer> Customers {get;}
     public ICommand RefreshCustomerListCommand {get;}
}

and the UI:

<ListBox ItemsSource="{Binding Customers}"/>
<Button Command="{Binding RefreshCustomerListCommand}">Refresh</Button>

And that's it. The ListBox's syntax will grab the list of Customers off of the ViewModel and attempt to render them to the UI. Because of the two DataTemplates we defined earlier, it will import the relevant template (based on the DataType, assuming PrimeCustomer inherits from Customer) and put it as the contents of the ListBox. No looping, no dynamic generation of controls via code.

The Button, similarly, has preexisting syntax to link its behavior to an ICommand implementation, which presumably knows to update the Customers property - prompting the data-binding framework to update the UI again, automatically.

I've taken some shortcuts here, of course, but this is the gist of it.


问:
Why are return values from compare functions in many languages defined loosely?
Many languages define that compare functions should return ANY negative value, zero, or ANY positive value.  Is there some reason that it shouldn't be clearly defined as -1 0 and 1?  Does a wide range in possible return values help more advanced algorithms to work more efficiently?  If so, what algorithms work this way?</p>

答:
Return value semantics has almost nothing to do with implementation. This specification leaves no space for unspecified behavior and is statically verifiable.

If return value is specified to be an arbitrary number, this can checked statically - compiler can easily verify that function doesn't return string. Otherwise static verification is impossible - values that are outside of given range can't be eliminated statically for non-enum types. Therefore calling code will have to deal with unspecified values in runtime, emitting more unspecified behavior.

We can safely say that this decision is made to mimic behavior Jörg described in his comment - complete specification, every option covered.

ContentLicense: CC BY-SA 3.0


问:
Best practice for using namespaces in my PHP libraries
I've been using a tiny and neat caching library on my projects, but I realize that "Cache" is a very generic name and it's easy to get a collision when using it in large projects.

Also, I would like to publish it in Github in order to share it with colleagues and make it easy for all of us to install using composer.

The problem is that I don't really get all this PSR-4 recommendations.

How should I structure my folders?
How should I namespace the library?
And how should I autoload it from within my projects?

What I need is probably a very comprehensive composer tutorial, that I wasn't able to find yet...

答:
As GordonM mentioned in the comment, you should break it up to something along the lines of

\Vendor\Package\ClassName

So maybe for your cache library it would be something along the lines of

\SG\Cache\CacheClass

Directory structures usually mirror the above.  So it'd be located in /SG/Cache/CacheClass.php of your root directory.  If you're using a particular framework there should be some documentation on namespace usage for the framework.


问:
Test & remove, or always remove
I have a function to show or hide a certain UI control. In my example case below, the framework is jQuery I'm using for an event to show a tool tip that may fire a LOT (based on mouse movements) - but the underlying problem is more general and may also arise in a similar manner in lots of other UI frameworks. In fact, the problem could be even more generalized to any kind of component with two states to be switched often, not just UI components.

Consider:

Code A:

```<code>$(this).plothover(function(item) {
   if(item&&item!="undefined"){
      show tooltip
   }
   else
     remove tooltip
});
</code>```

Code B:

```<code>$(this).plothover(function(item) {
   if(item&&item!="undefined"){
      show tooltip
   }
   else {
      if(tool tip is shown){
           remove tooltip
      }
   }
});
</code>```

item will exist at defined Cartesian points where datapoints exist (ie, graph coordinates on a canvas).  In other words, the odds are ~10000:1 in the favor of the else condition firing on a DPI basis.

As the mouse moves,

Code A removes it with no regard to any condition
Code B only removes it if it was already created, but has to test the creation first

So, which is considered 'right'?
Blind hide the control whether it is visible or not, or only hide it if it is visible?

I've benchmark'ed it through jsperf and the differences are negligible performance wise but does lean towards the blind destroy.  But if it's 'wrong' by theory to do it, i'd rather chose the best practice route.

--- EDIT ---
To clarify, The actual invocation is not important (ie, how is it removed). Nor am I looking for a code review. The above given example is one of many times I've run into this case.

Rather, I wish to discuss the theory involved in "Destroy what may exist" or "search and destroy if it exists".

答:
When there are two equal alternatives to implement something, where one needs more code and the second less (and "less code" is indeed simpler, not a "clever hack" which stresses your mind), I would typically prefer the simpler one over the more complicated. Easier to read and understand, easier to maintain, easier to change.

Of course, in a case like the one shown above, you have be sure that the API of the component you are using allows to apply "remove" regardless of the tool tip to be shown before, and that you can really leave out the test without introducing a bug (if the API design is sane, one could IMHO expect that, but not all APIs are robust). On the other hand, adding a test like if(tool tip is shown) though it is not needed shows that you did not understand the API fully and leaves you with a bad example if you are going to write a similar code snippet later again.

Title: Test & remove, or always remove


问:
Two user inputs that alter each other
I have a user interface with two numeric input boxes, send amount and receive amount. The values are in different currencies and are related by an exchange rate. That is, receive amount should always be send amount * exchange rate. But the user is allowed to click into either input box and modify the value, which causes the other value to be updated.

I've got a simple system to observe changes to either value and update the other one. I've had problems with infinite loops of the values updating each other because they're floats and multiplying then dividing by the exchange rate doesn't always create precisely the same value. So I added a simple flag to ignore updates while the updater itself is running.

But now I'm adding more functionality when the user updates an amount field, requiring other objects to listen to the fields. As a result some of those objects end up changing one of the amount fields, which sets off an infinite loop.

I've always felt like this is a fragile modelling of the problem, but I haven't thought of anything better. Is there any established pattern or approach to modelling two values that update each other?

答:
Add an argument called sender which can be chained together as events are raised.  As a first step check to see if if the current object is on the chain, if so, just mark as handled so no updates occur.

Example

Button1 initiates change.

Sender:  Button1

Button2 intercepts, first thing it does is check if it's already on the sender chain.  In this case it is not, so it does an update, adding another sender on the chain (Button1, Button2) and raises an event that it has changed.  Button1 intercepts, inspects chain, Button1 and Button2 are on the chain, so it shouldn't do an update and thus no more events will be raised.

This way the UI doesn't end up chasing its tail.

Title: Two user inputs that alter each other


问:
Is it always a best practice to write a function for anything that needs to repeat twice?
Myself, I can't wait to write a function when I need to do something more than twice. But when it comes to things that only appear twice, it's a bit more tricky.

For code that needs more than two lines, I'll write a function. But when facing things like:

```<code>print "Hi, Tom"
print "Hi, Mary"
</code>```

I'm hesitant to write:

```<code>def greeting(name):
    print "Hi, " + name

greeting('Tom')
greeting('Mary')
</code>```

The second one seems too much, doesn't it?

But what if we have:

```<code>for name in vip_list:
    print name
for name in guest_list:
    print name
</code>```

And here is the alternative:

```<code>def print_name(name_list):
    for name in name_list:
        print name

print_name(vip_list)
print_name(guest_list)
</code>```

Things become tricky, no? It's hard to decide now.

What's your opinion about this?

答:
Neither of the cases you give seem worth refactoring.

In both cases, you are performing an operation which is expressed clearly and succinctly, and there is no danger of an inconsistent change being made.

I recommend you always look for ways to isolate code where:

There is an identifiable, meaningful task which you could separate out, and

Either

a. the task is complex to express (taking into account the functions available to you) or

b. the task is performed more than once, and you need a way of making sure it is changed the same way in both places,

If condition 1 is not satisfied then you will not find the right interface for the code: if you try to force it you will end up with loads of parameters, multiple things you want to return, lots of contextual logic, and will quite possibly be unable to find a good name. Try documenting the interface you are thinking of first, it's a good way of testing the hypothesis that it's the right bundling of functionality and comes with the added bonus that when you write your code, it's already specced and documented!

2a is possible without 2b: sometimes I have taken code out the flow even when I know it only gets used once, simply because moving it elsewhere and replacing it with a single line means that the context in which it is called is suddenly much more readable (especially if it's an easy concept which the language happens to make difficult to implement). It's also clear when reading the extracted function where the logic begins and ends and what it does.

2b is possible without 2a: The trick is having a feel for what sort of changes are more likely. Is it more likely that your company policy will change from saying "Hi" everywhere to "Hello" all the time or that your greeting changes to a more formal tone if you're sending a demand for payment or an apology for a service outage? Sometimes it might be because you're using an external library you're not sure about and want to be able to swap that for another one quickly: the implementation might change even if the functionality doesn't.

Most often, though, you'll have some a mixture of 2a and 2b. And you'll have to use your judgment, taking into account the business value of the code, the frequency it gets used, whether it's well-documented and understood, the state of your test suite, etc.

If you notice the same bit of logic used more than once, by all means you should take the opportunity to consider refactoring. If you're beginning new statements more than n indentation levels in in most languages, that's another, slightly less significant trigger (pick a value of n you're comfortable with for your given language: Python might be 6, for instance).

So long as you're giving thought to these things and taking down the big spaghetti-code monsters, you should be fine - don't spend so long worrying about how fine-grained your refactoring needs to be that you don't have time for things like tests or documentation worked up about. If it does need doing, time will tell.


问:
Why empty function are needed
I started learning Python and I am wondering why empty function are needed in a programming language.

e.g. in python:

```<code>def empty_func():
    pass
</code>```

Even in shell scripts empty functions are available.

My Understandings and question:

Why do programming languages need empty functions?  Is it for just playing around with programming language or nothing else that really matters?

If this has a purpose, can anyone describe the use case or give a real example of the usage of empty functions?

Or is there any tradition of programming languages allowing empty functions?

EDIT (Things I got from reading your answers):

For Sketching Algorithms or with Abstract Functions

For Submitting forms with no action needs to be performed

Placeholder for some mandatory operations

答:
It depends on where you stand in the development cycle, but sometimes when sketching out an algorithm, you want to make abstraction about complex blocks without implementing them right away.

```<code>def full_algo():
  init_stuff()
  process_stuff()
  ...
</code>```

You know how init_stuff will work, it's rather simple in your head but you don't really need it right away, so you declare it as an empty function. It will allow your code to compile and run without bothering about the gory details.

Another use for released applications is when using inheritance. Suppose that you have a large class that defines the behavior of platform specific code. You might end up with a logic similar to this :

```<code>init_filesystem();
access_files();
release_filesystem();
</code>```

This code will work on many platforms, but some platforms might not need filesystem initialization. Then your inheritance will look like this (virtual with = 0 in C++ just means that derived classes MUST implement those methods) :

```<code>class FileSystem{
  virtual void init_filesystem() = 0;
  virtual void access_files() = 0;
  virtual void release_filesystem() = 0;
};
</code>```

Then a particular implementation of this class (interface) might do nothing for some of those methods. Alternatively, the base class could declare empty methods for init/release instead of declaring them virtual.

Finally (and shamefully), sometimes you maintain a very old application. You fear that deleting methods will break things. This happens when you have complex inheritance that is not properly understood or when you have a lot of function pointers (callbacks). You just delete code inside of them so they get called anyway without breaking anything.

ContentLicense: CC BY-SA 4.0

Title: Why empty function are needed

Body:
It depends on where you stand in the development cycle, but sometimes when sketching out an algorithm, you want to make abstraction about complex blocks without implementing them right away.

def full_algo():
  init_stuff()
  process_stuff()
  ...

You know how init_stuff will work, it's rather simple in your head but you don't really need it right away, so you declare it as an empty function. It will allow your code to compile and run without bothering about the gory details.

Another use for released applications is when using inheritance. Suppose that you have a large class that defines the behavior of platform specific code. You might end up with a logic similar to this :

init_filesystem();
access_files();
release_filesystem();

This code will work on many platforms, but some platforms might not need filesystem initialization. Then your inheritance will look like this (virtual with = 0 in C++ just means that derived classes MUST implement those methods) :

class FileSystem{
  virtual void init_filesystem() = 0;
  virtual void access_files() = 0;
  virtual void release_filesystem() = 0;
};

Then a particular implementation of this class (interface) might do nothing for some of those methods. Alternatively, the base class could declare empty methods for init/release instead of declaring them virtual.

Finally (and shamefully), sometimes you maintain a very old application. You fear that deleting methods will break things. This happens when you have complex inheritance that is not properly understood or when you have a lot of function pointers (callbacks). You just delete code inside of them so they get called anyway without breaking anything.


问:
How to make my program do something when an errors pops up instead of crashing?
Basically i'm writing a game in Java where i want the program to tell the user that he can't move right or left if that move will cause the player to move out of the array, which means this:

```<code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Game.printmap(Game.java:58)
at Game.main(Game.java:17)
</code>```

The Array is the map where the character can move and i want to avoid it from going outside of it. It is the game world where the player can move inside.

Is there a way to make my program ask for input again if the player choice implies an OutOfBounds error?

Thank you

答:
Well, the best way to deal with this is to fix the error that caused the exception to be thrown in the first place.

That said, you could always write a top-level try catch block.  This will catch any exceptions that weren't handled elsewhere.

```<code>public static void main(String args[])
{
    while (userDidNotExit)
    {
        try
        {
            // execute entry point of program here.
        }
        catch (Exception e)
        {
            // perform some sort of recovery here.
            //
        }
    }
}
</code>```

Body:
Well, the best way to deal with this is to fix the error that caused the exception to be thrown in the first place.

That said, you could always write a top-level try catch block.  This will catch any exceptions that weren't handled elsewhere.

public static void main(String args[])
{
    while (userDidNotExit)
    {
        try
        {
            // execute entry point of program here.
        }
        catch (Exception e)
        {
            // perform some sort of recovery here.
            //
        }
    }
}


答:
While it isn't something you'd expect to do in Python, there are times in the world of device drivers where you need to supply an empty function, to handle an event that you either (a) know won't happen or (b) don't care about even if it does.

You also see this in C with callbacks.  Occasionally, you will see code that just ASSUMES you supplied a callback, and tries to call it, ignoring the risk of a null pointer.  All you can do in that case is supply an empty callback routine.  (Yes, I have a particular vendor in mind.)

Title: Why empty function are needed

Body:
I started learning Python and I am wondering why empty function are needed in a programming language.

e.g. in python:

```<code>def empty_func():
    pass
</code>```

Even in shell scripts empty functions are available.

My Understandings and question:

Why do programming languages need empty functions?  Is it for just playing around with programming language or nothing else that really matters?

If this has a purpose, can anyone describe the use case or give a real example of the usage of empty functions?

Or is there any tradition of programming languages allowing empty functions?

EDIT (Things I got from reading your answers):

For Sketching Algorithms or with Abstract Functions

For Submitting forms with no action needs to be performed

Placeholder for some mandatory operations


问:
Should I be extracting strings from source in core java the way android does?
I just started doing android development stuff after getting pretty comfortable with Java. Android apps tend to do this weird thing where they have all strings for their program held in an XML file called strings and the program refers to the strings instead of string literals in the code or even String objects.

The only reason I can think of to do this is internationalization. Is that it? What are the advantages/disadvantages of this approach? Should I be employing it in my other programming endeavors (such as regular Java)?

Seems like an unnecessary level of abstraction.

答:
According to this stackoverflow question the reason for the strings in XML is for localization.  </p>

<p>Should you do this in your other endeavours? The hard line answer is probably yes.  That said, my gut tells me, if you're only going to deploy in one language then possibly it's a premature optimization. So my answer is a hard maybe. </p>

Body:
According to this stackoverflow question the reason for the strings in XML is for localization.

Should you do this in your other endeavours? The hard line answer is probably yes.  That said, my gut tells me, if you're only going to deploy in one language then possibly it's a premature optimization. So my answer is a hard maybe.


答:
The reason Android puts strings in separate XML files is for localization.

Should you do it? Yes. Even if your app will support only one language, you never know if you'll be supporting others in the future, in which case you would only need to add another XML file.

This is not weird at all, it is actually the rule.

All platforms have some sort of mechanism like this. Microsoft's .Net platform uses .resx files, Android uses .xml files and "regular Java" uses .properties files (see the docs).

Title: Should I be extracting strings from source in core java the way android does?

Body:
I just started doing android development stuff after getting pretty comfortable with Java. Android apps tend to do this weird thing where they have all strings for their program held in an XML file called strings and the program refers to the strings instead of string literals in the code or even String objects.

The only reason I can think of to do this is internationalization. Is that it? What are the advantages/disadvantages of this approach? Should I be employing it in my other programming endeavors (such as regular Java)?

Seems like an unnecessary level of abstraction.


问:
Are `switch` statements generally used wrong?
I see most developers using switch statements with breaks in each and every case. Is this usage of switch statements inappropriate since a simple set of if-else statements would suffice?

Is it OK for me to think that the only reason for you to use a switch is because two or more cases are related, so you intentionally want some statements to "fall through"?

An example in which I think it's OK to use a switch is the case in which you want to update the schema of a database; so if you are updating from version 1 to version 4, you want to make sure the schema goes through versions 2 and 3 first:

```<code>private void updateDatabase(int oldVersion){
   switch(oldVersion){
      case 1:
         updateToVersion2();
      case 2:
         updateToVersion3();
      case 3:
         updateToVersion4();
   }
}
</code>```

A NOT OK example of a switch is where I use it in a video game to move a character based on the button pressed. I would have to break each case so that when pressing LEFT the character doesn't move in all directions:

```<code>private void onButtonPressed(Button button){
   switch(button){
      case LEFT:
         moveLeft();
         break;
      case RIGHT:
         moveRight();
         break;
      case UP:
         moveUp();
         break;
      case DOWN:
         moveDown();
         break;
    }
 }
</code>```

答:
I see what you're saying, but this is ultimately not improper.

If it's just one or two elses, an if-else change will suffice.  But if it grows to be more than that, I'd say switch statements can quickly turn into something that's just cleaner and less of an eyesore to look at.  Or...depending on who you are personally, it could turn it into something that's even messier.

It's strictly cosmetic in the case where you always break out of everything, but saying that it's particularly bad is like saying that between /*...*/ comments and // comments, one is completely better than the other.  If nothing's wrong with long if-else chains, then what's wrong with the more trivial switch statements?  It's just cosmetic, in cases where this question applies, and you'll find people on each side of the fence on which looks neater.  There is no huge convention over this.

But if something is wrong with switch statements where you do break out of everything, as opposed to just using if-else chains, then what is there to justify switch statements where you don't break out of everything?  Take your first example (which I agree with Brandon, it was sharp!):

```<code>private void updateDatabase(int oldVersion){
    switch(oldVersion){
        case 1:
            updateToVersion2();
        case 2:
            updateToVersion3();
        case 3:
            updateToVersion4();
    }
}
</code>```

Couldn't this just as easily have been written as the following:

```<code>private void updateDatabase(int oldVersion){
    if (oldVersion > 0 && oldVersion < 4){
        if (oldVersion < 3){
            if (oldVersion < 2){
                updateToVersion2();
            }
            updateToVersion3();
        }
        updateToVersion4();
    }
}
</code>```

Is this better or worse cosmetically?  It's a matter of opinion.  Is this better or worse in terms of performance?  Technically, depending on how the language is compiled, there's probably one extra int vs. int comparison that's been introduced, but is that really going to cause one microscopic fraction of the performance hit that using a high-level programming language will?  Realistically, you've probably either already made sure that oldVersion is more than 0, or you would need to add a similar check to your function with the switch statement.

Some people even think this:

```<code>switch (true)
{
    case variable1:
        doSomething1();
        break;

    case variable2 && variable3:
        doSomething2();
        break;

    case !variable4 && variabl5:
        doSomething3();
        break;
        .
        .
        .
    default:
        doSomethingElse();
}
</code>```

is ultimately cleaner code than:

```<code>if (variable1)
{
    doSomething1();
}
else if (variable2 && variable3)
{
    doSomething2();
}
else if (!variable4 && variable5)
{
    doSomething3();
.
.
.
}
else
{
    doSomethingElse();
}
</code>```

(Notice the difference in where the curly braces were placed in the last two snippets; when people do it this way, which is the subject of an ongoing debate in certain languages, it will probably affect their disposition towards the cleanliness of switch statements.)

Nothing's wrong with the trivial break-out-of-everything use of switch statements, but an experienced programmer should be able to see what it is you hold against them.

Body:
I see what you're saying, but this is ultimately not improper.

If it's just one or two elses, an if-else change will suffice.  But if it grows to be more than that, I'd say switch statements can quickly turn into something that's just cleaner and less of an eyesore to look at.  Or...depending on who you are personally, it could turn it into something that's even messier.

It's strictly cosmetic in the case where you always break out of everything, but saying that it's particularly bad is like saying that between /*...*/ comments and // comments, one is completely better than the other.  If nothing's wrong with long if-else chains, then what's wrong with the more trivial switch statements?  It's just cosmetic, in cases where this question applies, and you'll find people on each side of the fence on which looks neater.  There is no huge convention over this.

But if something is wrong with switch statements where you do break out of everything, as opposed to just using if-else chains, then what is there to justify switch statements where you don't break out of everything?  Take your first example (which I agree with Brandon, it was sharp!):

private void updateDatabase(int oldVersion){
    switch(oldVersion){
        case 1:
            updateToVersion2();
        case 2:
            updateToVersion3();
        case 3:
            updateToVersion4();
    }
}

Couldn't this just as easily have been written as the following:

private void updateDatabase(int oldVersion){
    if (oldVersion > 0 && oldVersion < 4){
        if (oldVersion < 3){
            if (oldVersion < 2){
                updateToVersion2();
            }
            updateToVersion3();
        }
        updateToVersion4();
    }
}

Is this better or worse cosmetically?  It's a matter of opinion.  Is this better or worse in terms of performance?  Technically, depending on how the language is compiled, there's probably one extra int vs. int comparison that's been introduced, but is that really going to cause one microscopic fraction of the performance hit that using a high-level programming language will?  Realistically, you've probably either already made sure that oldVersion is more than 0, or you would need to add a similar check to your function with the switch statement.

Some people even think this:

switch (true)
{
    case variable1:
        doSomething1();
        break;

    case variable2 && variable3:
        doSomething2();
        break;

    case !variable4 && variabl5:
        doSomething3();
        break;
        .
        .
        .
    default:
        doSomethingElse();
}

is ultimately cleaner code than:

if (variable1)
{
    doSomething1();
}
else if (variable2 && variable3)
{
    doSomething2();
}
else if (!variable4 && variable5)
{
    doSomething3();
.
.
.
}
else
{
    doSomethingElse();
}

(Notice the difference in where the curly braces were placed in the last two snippets; when people do it this way, which is the subject of an ongoing debate in certain languages, it will probably affect their disposition towards the cleanliness of switch statements.)

Nothing's wrong with the trivial break-out-of-everything use of switch statements, but an experienced programmer should be able to see what it is you hold against them.


问:
Shared code across many (web) projects using git
I work in a small team that creates and maintains quite a lot (> 100) of ASP.NET website projects. Our current workflow is that our projects are all located on a network drive, which everyone works from directly. We have a couple of shared code libraries, which contain both binaries and css, js and xsl files. With each addition to this shared code, the files are distributed by copying them to all projects on the network drive using a script.

Our current project "layout" looks something like this:

```<code>Shared code project
   |- Deployment (compiled binaries)
   |- Library (C# source code)
   |- Web (a website project that contains the default css, js, etc)
       |- css
           |- default (shared css code)
       |- js
           |- default (shared js code)
       |- xsl ... etcetera

Website project
   |- Bin (shared code binaries)
   |- css
       |- default (shared css code)
       |- specific (project specific css)
   |- js
       |- default (shared js code)
       |- specific (project specific js)
   |- xsl ... etcetera.
</code>```

I'm currently in the process of trying to get us to switch to using git and working locally on our own machines. I've got most potential issues covered, except for how to deal with the shared code. Obviously we can no longer use the copy & replace script if we're all working locally. So something a bit more sophisticated will have to be put in its place.

If I was using SVN I might use svn externals to reference certain files in the shared code repositories. The nice thing with that is that I can pick just those files I need (no C# source code), and put it exactly where I need it to be. But with git that doesn't really seem to be an option. I've been reading a lot about git submodules and subtrees, but neither seem to be the ideal candidate.

I have also considered using a package manager like NuGet or Bower, but is this really a good idea for first-party dependencies? For one, it would mean that everyone who would want to git clone a website project would have to have the package manager installed.

What would a typical git setup for a website project with "first party" dependencies be?

A few details that I think are relevant to the choice:

I only need one-way synchronizing. Changes to shared code are made in the shared code libraries. I don't need to be able to push to shared code libraries from a project library.

The shared code libraries are updated and distributed relatively frequently; a few times per week at least.

Both shared code libraries and website projects will be git repositories.

I don't want to pull in the C# source code for the shared binaries.

答:
You could stand up your own, private NuGet package feed on an internal server in your company. Publish each dependency to your NuGet site as a separate package and use NuGet to manage those dependencies. Furthermore, if you need to make code changes to a package you can create a local package feed so you can change code, compile and update. When you are ready to share with coworkers, tag and push in Git, then publish to your company feed.

Hosting Your Own NuGet Feeds (NuGet Docs)

The nice thing about this approach is you get backwards compatibility with your packages. You can make API breaking changes without requiring other projects to be on the same release cycle as yours. As an added bonus project structures probably wouldn't be affected if you change source control systems.


答:
Since if/else is similar to a switch and often interchangeable, your confusion is understandable.

Some languages, such as Python, don't even have a switch statement. Not surprisingly, when you Google for "python switch", the first result points to an alternative—a map. Not an if/else, but a map.

While you can use if/else every time instead of a switch, you should also understand that your colleagues are not wrong when they use a switch statement. Either they were simply told by a teacher or a mentor that they should use a switch when there are more than two branches, or they simply find it more elegant or readable, both terms being perfectly subjective.

Your first example, by the way, annoys me a lot. If I were a reviewer of your code, I would immediately flag it, because it's easy to overlook the lack of break statements, and so it looks like if oldVersion is 2, only updateToVersion3() will be executed, but not updateToVersion4(). Avoid writing code which is prone to errors. For instance, such syntax is forbidden in C# precisely in order to avoid mistakes which are so easily avoidable.

Your second example is a case where switch is perfectly fine. Although I would use instead either a map (mapping functions—or even lambda expressions, and not their results) or inheritance, I would switch to switch statement if I know that my code will be read by beginners who may not understand those two approaches.

If the style guidelines of your code base allow it, your second example may even be written this way:

```<code>switch (button){
    case LEFT: moveLeft(); break;
    case RIGHT: moveRight(); break;
    case UP: moveUp(); break;
    case DOWN: moveDown(); break;
}
</code>```

or like this:

```<code>switch (button){
    case LEFT:  moveLeft();  break;
    case RIGHT: moveRight(); break;
    case UP:    moveUp();    break;
    case DOWN:  moveDown();  break;
}
</code>```

making the code shorter and more readable (again, readability is subjective) than an if/elif/else variant.

An important aspect highlighted by J Trana is that in this second example, if/elif/else may be error prone. I can't easily find a more illustrative example where you can migrate to switch, but the following piece of code shows the idea. Are you able to immediately see why the following code will sometimes throw an exception at runtime (imagine it's 6 PM and you've spent three hours inspecting code)?

```<code>if (!fs.FileExists(fileFullPath)) {
    debug("The file appears to be missing. Check if the location is set in the options.");
}
if (fs.ReadFile(fileFullPath).Contains(textToFind)) {
    found = true;
    debug("The file contains the expected text.");
}
else {
    debug("The text was not found.");
}
</code>```

Here again, in C#, the official style guide will prevent you from writing this error prone piece of code: it would require to add a line break before the second if, and the author of the code will immediately see that he wrote if instead of else if.

That's why, in order to reduce the risk of writing code which doesn't express clearly the intentions of the author and can easily be misread:

Avoid the missing breaks in switch statements, except in the case where the previous case contains no logic:

```<code>switch (something)
{
    case 1: // Not having a `break` is fine. The intention of the author is clear.
    case 2:
        hello();
        break;

    case 3:
        world();
        break;
}
</code>```

Avoid else if which may be confused with or, by mistake, replaced by, an if, unless the style guidelines are protecting you.

Use maps and inheritance when appropriate. In most cases, maps and inheritance are more appropriate than if/elif/else or switch. Longer if/elif/else or switch tend to be a good sign that they should be replaced by a map (often) or an inheritance (rarely) or should be completely refactored (often).

The record I've seen so far is a switch statement containing approximately a thousand cases (written by an expert proud of his 15 years' professional experience as a lead developer).

Flatten hierarchies when possible. This code:

```<code>if (n == a) {
    f1();
}
else {
    if (n == b) {
        f2();
    }
    else {
        f3();
    }
}
</code>```

should immediately be refactored to:

```<code>if (n == a) {
    f1();
}
else if (n == b) {
    f2();
}
else {
    f3();
}
</code>```

or:

```<code>switch (n) {
    case a:  f1(); break;
    case a:  f2(); break;
    default: f3();
}
</code>```

Beware of insane programmers. This piece of code is equivalent to the one in the previous point, if a, b, c and n are numbers (things would be different if those were calls to functions with side effects):

```<code>if (!(n == a)) {
    if (n - b == 0 && !(n > b)) {
        f2();
    }
}

if (!(n == a) && n - b < 0 || b - n < 0) {
    f3();
}

if (n != a) {
    // Do nothing.
}
else {
    if (!(n > a) && ! (n < a)) {
        f1();
    }
}
</code>```

Title: Are `switch` statements generally used wrong?

Body:
I see most developers using switch statements with breaks in each and every case. Is this usage of switch statements inappropriate since a simple set of if-else statements would suffice?

Is it OK for me to think that the only reason for you to use a switch is because two or more cases are related, so you intentionally want some statements to "fall through"?

An example in which I think it's OK to use a switch is the case in which you want to update the schema of a database; so if you are updating from version 1 to version 4, you want to make sure the schema goes through versions 2 and 3 first:

```<code>private void updateDatabase(int oldVersion){
   switch(oldVersion){
      case 1:
         updateToVersion2();
      case 2:
         updateToVersion3();
      case 3:
         updateToVersion4();
   }
}
</code>```

A NOT OK example of a switch is where I use it in a video game to move a character based on the button pressed. I would have to break each case so that when pressing LEFT the character doesn't move in all directions:

```<code>private void onButtonPressed(Button button){
   switch(button){
      case LEFT:
         moveLeft();
         break;
      case RIGHT:
         moveRight();
         break;
      case UP:
         moveUp();
         break;
      case DOWN:
         moveDown();
         break;
    }
 }
</code>```

Body:
Since if/else is similar to a switch and often interchangeable, your confusion is understandable.

Some languages, such as Python, don't even have a switch statement. Not surprisingly, when you Google for "python switch", the first result points to an alternative—a map. Not an if/else, but a map.

While you can use if/else every time instead of a switch, you should also understand that your colleagues are not wrong when they use a switch statement. Either they were simply told by a teacher or a mentor that they should use a switch when there are more than two branches, or they simply find it more elegant or readable, both terms being perfectly subjective.

Your first example, by the way, annoys me a lot. If I were a reviewer of your code, I would immediately flag it, because it's easy to overlook the lack of break statements, and so it looks like if oldVersion is 2, only updateToVersion3() will be executed, but not updateToVersion4(). Avoid writing code which is prone to errors. For instance, such syntax is forbidden in C# precisely in order to avoid mistakes which are so easily avoidable.

Your second example is a case where switch is perfectly fine. Although I would use instead either a map (mapping functions—or even lambda expressions, and not their results) or inheritance, I would switch to switch statement if I know that my code will be read by beginners who may not understand those two approaches.

If the style guidelines of your code base allow it, your second example may even be written this way:

switch (button){
    case LEFT: moveLeft(); break;
    case RIGHT: moveRight(); break;
    case UP: moveUp(); break;
    case DOWN: moveDown(); break;
}

or like this:

switch (button){
    case LEFT:  moveLeft();  break;
    case RIGHT: moveRight(); break;
    case UP:    moveUp();    break;
    case DOWN:  moveDown();  break;
}

making the code shorter and more readable (again, readability is subjective) than an if/elif/else variant.

An important aspect highlighted by J Trana is that in this second example, if/elif/else may be error prone. I can't easily find a more illustrative example where you can migrate to switch, but the following piece of code shows the idea. Are you able to immediately see why the following code will sometimes throw an exception at runtime (imagine it's 6 PM and you've spent three hours inspecting code)?

if (!fs.FileExists(fileFullPath)) {
    debug("The file appears to be missing. Check if the location is set in the options.");
}
if (fs.ReadFile(fileFullPath).Contains(textToFind)) {
    found = true;
    debug("The file contains the expected text.");
}
else {
    debug("The text was not found.");
}

Here again, in C#, the official style guide will prevent you from writing this error prone piece of code: it would require to add a line break before the second if, and the author of the code will immediately see that he wrote if instead of else if.

That's why, in order to reduce the risk of writing code which doesn't express clearly the intentions of the author and can easily be misread:

Avoid the missing breaks in switch statements, except in the case where the previous case contains no logic:

switch (something)
{
    case 1: // Not having a `break` is fine. The intention of the author is clear.
    case 2:
        hello();
        break;

    case 3:
        world();
        break;
}

Avoid else if which may be confused with or, by mistake, replaced by, an if, unless the style guidelines are protecting you.

Use maps and inheritance when appropriate. In most cases, maps and inheritance are more appropriate than if/elif/else or switch. Longer if/elif/else or switch tend to be a good sign that they should be replaced by a map (often) or an inheritance (rarely) or should be completely refactored (often).

The record I've seen so far is a switch statement containing approximately a thousand cases (written by an expert proud of his 15 years' professional experience as a lead developer).

Flatten hierarchies when possible. This code:

if (n == a) {
    f1();
}
else {
    if (n == b) {
        f2();
    }
    else {
        f3();
    }
}

should immediately be refactored to:

if (n == a) {
    f1();
}
else if (n == b) {
    f2();
}
else {
    f3();
}

or:

switch (n) {
    case a:  f1(); break;
    case a:  f2(); break;
    default: f3();
}

Beware of insane programmers. This piece of code is equivalent to the one in the previous point, if a, b, c and n are numbers (things would be different if those were calls to functions with side effects):

if (!(n == a)) {
    if (n - b == 0 && !(n > b)) {
        f2();
    }
}

if (!(n == a) && n - b < 0 || b - n < 0) {
    f3();
}

if (n != a) {
    // Do nothing.
}
else {
    if (!(n > a) && ! (n < a)) {
        f1();
    }
}


问:
How do I avoid cascading refactorings?
I've got a project. In this project I wished to refactor it to add a feature, and I refactored the project to add the feature.

The problem is that when I was done, it turned out that I needed to make a minor interface change to accommodate it. So I made the change. And then the consuming class can't be implemented with its current interface in terms of the new one, so it needs a new interface as well. Now it's three months later, and I've had to fix innumerable virtually unrelated problems, and I'm looking at solving issues that were roadmapped for a year from now or simply listed as won't fix due to difficulty before the thing will compile again.

How can I avoid this kind of cascading refactorings in the future? Is it just a symptom of my previous classes depending too tightly on each other?

Brief edit: In this case, the refactor was the feature, since the refactor increased the extensibility of a particular piece of code and decreased some coupling. This meant that external developers could do more, which was the feature I wanted to deliver. So the original refactor itself should not have been a functional change.

Bigger edit that I promised five days ago:

Before I began this refactor, I had a system where I had an interface, but in the implementation, I simply dynamic_cast through all the possible implementations that I shipped. This obviously meant that you couldn't just inherit from the interface, for one thing, and secondly, that it would be impossible for anybody without implementation access to implement this interface. So I decided that I wanted to fix this issue and open up the interface for public consumption so that anybody could implement it and that implementing the interface was the entire contract required- obviously an improvement.

When I was finding and killing-with-fire all the places that I had done this, I found one place that proved to be a particular problem. It depended upon implementation details of all the various deriving classes and duplicated functionality that was already implemented but better somewhere else. It could have been implemented in terms of the public interface instead and re-used the existing implementation of that functionality. I discovered that it required a particular piece of context to function correctly. Roughly speaking, the calling previous implementation looked kinda like

```<code>for(auto&& a : as) {
     f(a);
}
</code>```

However, to get this context, I needed to change it into something more like

```<code>std::vector<Context> contexts;
for(auto&& a : as)
    contexts.push_back(g(a));
do_thing_now_we_have_contexts();
for(auto&& con : contexts)
    f(con);
</code>```

This means that for all operations that used to be a part of f, some of them need to be made a part of the new function g that operates without a context, and some of them need to be made of a part of the now-deferred f. But not all methods f call need or want this context- some of them need a distinct context that they obtain through separate means. So for everything that f ends up calling (which is, roughly speaking, pretty much everything), I had to determine what, if any, context they needed, where they should get it from, and how to split them from old f into new f and new g.

And that's how I ended up where I am now. The only reason that I kept going is because I needed this refactoring for other reasons anyway.

答: I think you usually cannot unless you are willing to keep things as they are. However, when situations like yours, I think the better thing is to inform the team and let them know why there should be some refactoring done in order to continue more healthy development. I wouldn't just go and fix things by myself. I would talk about it during Scrum meetings (assuming you guys have them), and approach it systematically with other developers.</p>

Title: How do I avoid cascading refactorings?


问:
Find 'Connected Components' in undirected, unweighted graph coded as a 2d array
Given an undirected, unweighted graph coded as a 2d array, how can I find the number of different connected components?

Example

There is the following 2d array (I'm not putting any brackets to make it more readable):

```<code>1 1 3 1
1 2 2 2
1 3 3 2
4 4 1 4
</code>```

Since each discrete number can create a component with the same number/colour (different adjacent number cannot be clustered together). This should return 8.

My thoughts on the problem

A possible solution to the problem would be to consider each different number as a version of the problem defined and solved here.

For example, for number 1:

```<code>1 1 0 1
1 0 0 0
1 0 0 0
0 0 1 0
</code>```

For number 2:

```<code>0 0 0 0
0 2 2 2
0 0 0 2
0 0 0 0
</code>```

etc.

However my consideration with this approach is that it would probably require either iterating |colours| times through the original array, or allocating |colours| arrays.

Another approach would be to associate each colour with a its coordinates in the graph, like this:

```<code>1: <00, 01, 03, 10, 20, 32>
2: <11, 12, 13, 23>
3: <02, 21, 22>
4: <30, 31, 33>
</code>```

However this approach would require to check all combinations of coordinates for adjacency.

Your thoughts?

答: Wikipedia has a nice little section on algorithms for this. @Hey's suggestion lines up with the recommendation for simply doing a bread- or depth-first search from the list of vertices.</p>


问:
How does the consumer-producer solution work?
I'm only a beginner, and my book doesn't cover this subject. I have researched my problem and found that an implementation of the consumer-producer pattern is the ideal solution, and have Googled it, read what I could, tried to enact examples... but haven't been lucky. I would really appreciate a bit of guidance.

I am writing in Ruby, if that makes a difference.

Background

I am writing a script that scrobbles my music library backlog to Last.FM. For anyone who isn't familiar with that service, that simply means that I am making lots of POST requests to a HTTP API.

I start with an array, each element is a hash/dictionary like {artist: "The Cure", track: "Siamese Twins"}. I make the calls by iterating over the array and issuing the simple method call lastfm.track.scrobble artist: song[:artist], track: song[:track].

Problem

Doing this in a straightforward one-at-a-time blocking style works perfectly, but is very very slow, because I'm waiting ~2 seconds for each HTTP request to travel the world and return. I could finish 5 times faster if I sent 5 HTTP requests simultaneously.

I asked on Stack Overflow what the best solution would be. Split the array into five parts, and give part a thread running one request at a time? Something like JavaScript's XMLHttpRequest which has an event loop and a callback function? They told me that this qusetion would be better suited to Programmers SE, and that I probably want the consumer-producer pattern. I looked it up, and it does sound like the kind of thing I need.

My Attempt in Ruby, based off a StackOverflow post

```<code># "lastfm" is an object representing my Last.FM profile,
# its .track.scrobble method handles a POST request and waits until it returns
# "songs" is an array of hashes like {artist: "The Cure", track: "One Hundred Years"}

queue = SizedQueue.new(10) # this will only allow 10 items on the queue at once

p1 = Thread.new do
  songs.each do |song|
      scrobble = lastfm.track.scrobble artist: song[:artist], track: song[:track]
      puts "Scrobbled #{song[:track]} by #{song[:artist]}."
      queue << scrobble
  end
  queue << "done"
end

consumer = Thread.new do
  blocker = queue.pop(true) # don't block when zero items are in queue
  Thread.exit if blocker == "done"
  process(blocker)
end

# wait for the consumer to finish
consumer.join
</code>```

My Error

Failure on the "pop" method call with error "queue empty".

I don't know enough about this stuff to really understand what's happening. It looks like one thread is filling a queue with API calls to make, never more than 10 at a time, while another thread is consuming from that queue and performing them. But why pop? Where is it ever actually executed? Why am I appending "done" to the queue?

I'm concerned about the line scrobble = lastfm.track.scrobble artist: song[:artist], track: song[:track]. Won't this call the lastfm.track.scrobble method outright, and store its return value as scrobble? Should I be using a proc or lambda instead, and calling that proc/lambda in the consumer?

答:
The answer by scriptin is giving a reasonable solution, but doesn't answer your questions about the failure of the implementation you had.

You get a 'queue empty' error when you call pop on a Ruby queue in non-blocking mode (true passed) and there are no items on the queue.

Your "producer" thread is created and your "consumer" thread is created, but they'll run independently and start executing whenever Ruby feels like it.

If your "consumer" runs before the "producer" has pushed anything onto the queue, then obviously the "consumer" will pop an empty queue and throw an exception.

The solution to this one is easy; the consumer shouldn't use non-blocking mode. Don't pass true, just call pop(). The whole point of the consumer thread is that it can block on a queue waiting for the producer, without the rest of the application halting.

As for calling lastfm.track.scrobble - yes, this is executing that method immediately and pushing the result on the queue, which is exactly not what you want :-D and is in fact the reason why "reliably" your consumer thread gets to pop its queue before the producer ever has a chance to push anything (even if the producer thread runs first, it hits a slow 'scrobble' call and sits waiting for HTTP requests/responses to complete; so the consumer thread executes and tries to read from the empty queue).

You want to push the parameters to scrobble onto the queue, then have the consumer thread do the scrobbling. It's "nicer"/more structured to make little classes encapsulating the work and push instances of those onto your queue, but a cheap-and-nasty solution just uses the Hash which scrobble takes as input. We also need to remember to loop over the queue entries inside the consumer, instead of only processing one! Thus (UNTESTED) we might have:

```<code>queue = SizedQueue.new(10)

Thread.new do
  songs.each do |song|
      queue << { artist: song[:artist], track: song[:track] }
  end
  queue << "done"
end

consumer = Thread.new do
  loop do
    scrobble_args = queue.pop()
    Thread.exit if scrobble_args == "done"
    lastfm.track.scrobble(scrobble_args)
    puts "Scrobbled #{scrobble_args[:track] by scrobble_args[:artist]}."
  end
end

consumer.join
</code>```

This should technically work but is totally pointless, because that one lonely consumer thread is just processing the queue in serial. So let's simplify this. Really, you just want to dump all of 'songs' into the queue and have the consumer thread do the work. Since we want to run in parallel, we'll make an array of threads.

```<code># I'm not bothering with the producer thread here so the queue size is unlimited.
# You could just as well put the 'songs.each' inside a producer thread with a
# a sized queue, as per your original code, if you wanted.
#
queue = Queue.new
songs.each do | song |
  queue << song
end

consumers = []

1.upto( 10 ) do
  consumers << Thread.new do

    # Keep looping until asked to exit
    #
    loop do
      song = queue.pop()
      Thread.exit if song == 'done'
      lastfm.track.scrobble( artist: song[ :artist ], track: song[ :track ] )
      puts "Scrobbled #{ song[ :track ] } by #{ song[ :artist ] }."
    end
  end

  # Push one 'done' exit instruction for each consumer
  #
  queue << 'done'
end

# Wait for all consumer threads to complete
#
consumers.each do | consumer |
  consumer.join()
end
</code>```

...and that should do the trick. The "Parallel" gem will probably be doing much the same sort of thing under the hood.

Body:
The answer by scriptin is giving a reasonable solution, but doesn't answer your questions about the failure of the implementation you had.

You get a 'queue empty' error when you call pop on a Ruby queue in non-blocking mode (true passed) and there are no items on the queue.

Your "producer" thread is created and your "consumer" thread is created, but they'll run independently and start executing whenever Ruby feels like it.

If your "consumer" runs before the "producer" has pushed anything onto the queue, then obviously the "consumer" will pop an empty queue and throw an exception.

The solution to this one is easy; the consumer shouldn't use non-blocking mode. Don't pass true, just call pop(). The whole point of the consumer thread is that it can block on a queue waiting for the producer, without the rest of the application halting.

As for calling lastfm.track.scrobble - yes, this is executing that method immediately and pushing the result on the queue, which is exactly not what you want :-D and is in fact the reason why "reliably" your consumer thread gets to pop its queue before the producer ever has a chance to push anything (even if the producer thread runs first, it hits a slow 'scrobble' call and sits waiting for HTTP requests/responses to complete; so the consumer thread executes and tries to read from the empty queue).

You want to push the parameters to scrobble onto the queue, then have the consumer thread do the scrobbling. It's "nicer"/more structured to make little classes encapsulating the work and push instances of those onto your queue, but a cheap-and-nasty solution just uses the Hash which scrobble takes as input. We also need to remember to loop over the queue entries inside the consumer, instead of only processing one! Thus (UNTESTED) we might have:

queue = SizedQueue.new(10)

Thread.new do
  songs.each do |song|
      queue << { artist: song[:artist], track: song[:track] }
  end
  queue << "done"
end

consumer = Thread.new do
  loop do
    scrobble_args = queue.pop()
    Thread.exit if scrobble_args == "done"
    lastfm.track.scrobble(scrobble_args)
    puts "Scrobbled #{scrobble_args[:track] by scrobble_args[:artist]}."
  end
end

consumer.join

This should technically work but is totally pointless, because that one lonely consumer thread is just processing the queue in serial. So let's simplify this. Really, you just want to dump all of 'songs' into the queue and have the consumer thread do the work. Since we want to run in parallel, we'll make an array of threads.

# I'm not bothering with the producer thread here so the queue size is unlimited.
# You could just as well put the 'songs.each' inside a producer thread with a
# a sized queue, as per your original code, if you wanted.
#
queue = Queue.new
songs.each do | song |
  queue << song
end

consumers = []

1.upto( 10 ) do
  consumers << Thread.new do

    # Keep looping until asked to exit
    #
    loop do
      song = queue.pop()
      Thread.exit if song == 'done'
      lastfm.track.scrobble( artist: song[ :artist ], track: song[ :track ] )
      puts "Scrobbled #{ song[ :track ] } by #{ song[ :artist ] }."
    end
  end

  # Push one 'done' exit instruction for each consumer
  #
  queue << 'done'
end

# Wait for all consumer threads to complete
#
consumers.each do | consumer |
  consumer.join()
end

...and that should do the trick. The "Parallel" gem will probably be doing much the same sort of thing under the hood.


答:
The two input boxes are two views onto the same value. If one box is changed, the other is changed as well. Therefore, there should be no separate “on change” event to subscribe to. The two immediate event handlers just emit one common event that takes note of which box was edited. Pseudocode:

```<code>class ConvertFromTo(from: Input, to: Input) {
  val on-change = new Observable[ChangeEvent]()
  from.on-change.add(e => on-change.emit(new ChangeEvent(this, Direction.From, e.value))
  to.on-change.add(e => on-change.emit(new ChangeEvent(this, Direction.To, e.value))
}
</code>```

This allows external listeners to subscribe to the combined ConvertFromTo.on-change observable. You can use this abstraction layer to weed out events that didn't actually change the conversion value. If some component needs to be notified on changes to the displayed value, the can still subscribe directly to the change event of that input field.

Title: Two user inputs that alter each other

Body:
I have a user interface with two numeric input boxes, send amount and receive amount. The values are in different currencies and are related by an exchange rate. That is, receive amount should always be send amount * exchange rate. But the user is allowed to click into either input box and modify the value, which causes the other value to be updated.

I've got a simple system to observe changes to either value and update the other one. I've had problems with infinite loops of the values updating each other because they're floats and multiplying then dividing by the exchange rate doesn't always create precisely the same value. So I added a simple flag to ignore updates while the updater itself is running.

But now I'm adding more functionality when the user updates an amount field, requiring other objects to listen to the fields. As a result some of those objects end up changing one of the amount fields, which sets off an infinite loop.

I've always felt like this is a fragile modelling of the problem, but I haven't thought of anything better. Is there any established pattern or approach to modelling two values that update each other?

Body:
The two input boxes are two views onto the same value. If one box is changed, the other is changed as well. Therefore, there should be no separate “on change” event to subscribe to. The two immediate event handlers just emit one common event that takes note of which box was edited. Pseudocode:

class ConvertFromTo(from: Input, to: Input) {
  val on-change = new Observable[ChangeEvent]()
  from.on-change.add(e => on-change.emit(new ChangeEvent(this, Direction.From, e.value))
  to.on-change.add(e => on-change.emit(new ChangeEvent(this, Direction.To, e.value))
}

This allows external listeners to subscribe to the combined ConvertFromTo.on-change observable. You can use this abstraction layer to weed out events that didn't actually change the conversion value. If some component needs to be notified on changes to the displayed value, the can still subscribe directly to the change event of that input field.


问:
UI automation patterns and best practice for desktop applications
Background

I'm currently automating some tests for a plugin for MS Office. We are creating Coded UI tests in VS 2010. I suppose I could use the "Coded UI test builder" tool, but it does not really suit my particular case.

Because of this I created my own UI Map class and extension methods for each UI Control/Map where I add different action functionality. For example press buttons or assert some UI values.

The scenarios of the test cases are in the test classes.

I am new in this area and also I'm new in working as a automation tester.

The question

Would people be kind enough to share their experience and advice for some good practices for test automation on desktop applications from a programming/design point of view?

答:
Build functional tests from re-usable use cases

When the time comes to test your application end to end in-situ, you're performing functional testing. Typically you'll have a set of requirements that you're testing against and you'll be able to construct various use cases that represent them.

As an example, consider the "Login as standard user" use case. Your test framework fires up the application, waits for the login screen, enters some credentials, clicks the login button and verifies that the appropriate screen is now showing that login was successful.

After you've done the "Login as standard user" use case, you'll want to build on that to do something else, perhaps the "Edit my user details" use case. You won't want to repeat all the code from the "Login as standard user" use case, so you just make a reference to the test framework code that does that bit.

This implies that you have some kind of over-arching functional test containing a list of use cases. These use cases contain the test framework methods to cause application behaviour (click button X) and verify the behaviour (screen turned blue).

Overall, you can build up a body of re-usable use cases that target specific sequences and test for specific responses, and then aggregate them into various functional tests that correlate closely with the business requirements. Once you've got that in place, then you're in a great position to fully automate your entire build process.

If you're interested in reading further I've written about this approach elsewhere, but the article targets web applications in Java (using Maven and SeleniumRC) rather than desktop applications which you have requested.

ContentLicense: CC BY-SA 2.5


问:
Are there any programming languages that don't descend from C?
I mean descend as in languages who's original compiler/interpreter was written in C or in a language that descends from C.

If you don't count assembly, the only thing that comes to my mind is B. Are there any others?

答: Lisp and Smalltalk are good examples of such languages who were not descended from C. There was also a programming language named BCPL before C which isn't in use nowadays.   </p>


问:
Interface or boolean?
I have a CustomObject class which has the abilities like being Clickable, KeyPressable and Movable. I created interfaces: IClickable, IKeyPressable and IMovable and make different CustomObject classes to implement them. For example;

```<code>public class ClickableObject: IClickable {...}
public class MovableObject: IMovable {...}
public class ClickableAndMovableObject: IClickable , IMovable {...}
</code>```

But I'm thinking now that I can do it with one class and less lines like below;

```<code>public class CustomObject
{
    public bool isClickable;
    public bool isMovable;
    public bool isKeyPressable;

    // OnClick, OnMove and OnKeyPress events and other functions.
}
</code>```

and use this bool values if they are clickable or movable etc.

I am not sure which is the correct way to do.

答:
If the interfaces are empty and you find yourself querying:

```<code>if (someObject is IClickable)
{
    ...
}
</code>```

then those interfaces are probably not very useful and can be replaced by boolean values.

If on the other hand the interfaces contain members which are actively used, for example:

```<code>clickableObject = someObject as IClickable;
if (clickableObject != null)
{
    clickableObject.Click(this.coordinates);
}
</code>```

then it makes perfect sense to use interfaces. If you are afraid of code duplication, make an abstract class inherited by any object which uses one of your interfaces. In this abstract class, create properties such as:

```<code>protected bool IsClickable
{
    get
    {
        return this is IClickable;
    }
}

protected bool AsClickable
{
    get
    {
        return this as IClickable;
    }
}
</code>```

or go fancy with:

```<code>protected bool RunIfClickable(Action<IClickable> action)
{
    var clickable = this.AsClickable;
    if (clickable != null)
    {
        action(clickable);
    }
}
</code>```

which makes the earlier example as easy as:

```<code>someObject.RunIfClickable(c => c.Click(this.coordinates));
</code>```

Title: Interface or boolean?

Body:
If the interfaces are empty and you find yourself querying:

if (someObject is IClickable)
{
    ...
}

then those interfaces are probably not very useful and can be replaced by boolean values.

If on the other hand the interfaces contain members which are actively used, for example:

clickableObject = someObject as IClickable;
if (clickableObject != null)
{
    clickableObject.Click(this.coordinates);
}

then it makes perfect sense to use interfaces. If you are afraid of code duplication, make an abstract class inherited by any object which uses one of your interfaces. In this abstract class, create properties such as:

protected bool IsClickable
{
    get
    {
        return this is IClickable;
    }
}

protected bool AsClickable
{
    get
    {
        return this as IClickable;
    }
}

or go fancy with:

protected bool RunIfClickable(Action<IClickable> action)
{
    var clickable = this.AsClickable;
    if (clickable != null)
    {
        action(clickable);
    }
}

which makes the earlier example as easy as:

someObject.RunIfClickable(c => c.Click(this.coordinates));


答:
Don't forget Algol, which has been called a vast improvement over most of its imitators, including C.

Both COBOL and FORTRAN came long before C. I've seen a COBOL compiler written in RPG.

It's not unusual for a language's first compiler to be written in that language. The first compilation can be done by hand, and the first thing compiled with the hand-compiled compiler is the very same source code that was just hand-compiled. And the first thing compiled with that first machine-compiled compiler is the same source file yet again. If the hand-built compiler and the self-compiled compiler produce exactly the same output from this same source file, you know the compiler works "well enough", and the hand-compiled compiler can be thrown away.

Notice that the hand-built compiler doesn't need to produce efficient code or produce it efficiently. In fact, it doesn't even need to compile any feature of the language that the compiler itself doesn't use. That makes it feasible to bootstrap even "large" languages this way.

Forth might be considered to have been written this way. There is only a tiny part of the Forth runtime that needs to be written in Assembler, and everything else can be written in Forth itself.

Title: Are there any programming languages that don't descend from C?

Body:
I mean descend as in languages who's original compiler/interpreter was written in C or in a language that descends from C.

If you don't count assembly, the only thing that comes to my mind is B. Are there any others?


答:
In addition to Lisp, Smalltalk, Forth, COBOL, and FORTRAN mentioned by others, there's Pascal, Modula, Fortran, PL/I, BASIC, Snobol, and APL, to name some of the more popular languages that were neither descended from nor implemented in C. Early languages were implemented or bootstrapped in assembler.

Here's a small family tree of programming languages.

Also see Wikipedia: early programming languages and Establishing fundamental paradigms.


答:
No, switch statements are not generally used wrong.

They are mostly used for their intended use: enumerating action alternatives for a smallish set of possible input values. It's more readable then a long if/else chain, compilers can emit very efficient code if the checked values are reasonably contiguous, and it's easier to write error-checking compilers that warn you when you forget an alternative. All this is well and good. (Using switch when inheritance and dynamic dispatch would be preferable is a common mistake among beginners who don't understand OOP very well yet, but that is a higher-level issue.)

However, switch is defined badly in most languages.

Since by far the most common use case is to do something different for each case, it's annoying and clutterful having to write break after each case that isn't a fall-through. The switch statement would work much better if break were the default after a case body, and you had to order fall-through via an explicit fallthrough keyword (unless two cases are directly adjacent). That would remove a lot of unnecessary lines, and many, many people wouldn't have made subtle errors by forgetting a break.

However, it's definitely too late now to do anything about that; C does it that way, and none of its descendants was brave enough to change anything about it, so for the time being, switch will probably stay as it is.


答: If it's only about localisation then there would be many 'regular' Java applications where this wouldn't be necessary, or even helpful. In cases where the program uses strings that won't be displayed to humans then multiple languages won't be important. An example of this would be where strings are used to build text based protocols to talk to external systems that expect a specific language for the syntax of the protocol messages e.g. JSON.</p>


答:
Only if the duplication is intentional rather than accidental.

Or, put another way:

Only if you would expect them to co-evolve in the future.

Here's why:

Sometimes, two pieces of code just happen to become the same even though they have nothing to do with each other. In that case you must resist the urge to combine them, because the next time someone performs maintenance on one of them, that person will not expect the changes to propagate to a previously-nonexistent caller, and that function may break as a result. Hence you have to only factor out code when it makes sense, not whenever it seems to reduce code size.

Rule of thumb:

If the code only returns new data and doesn't modify existing data or have other side effects, then it's very likely to be safe to factor out as a separate function. (I can't imagine any scenario in which that would cause a breakage without entirely changing the intended semantics of the function, at which point the function name or signature should change too, and you'd need to be careful in that case anyway.)

Title: Is it always a best practice to write a function for anything that needs to repeat twice?

Body:
Myself, I can't wait to write a function when I need to do something more than twice. But when it comes to things that only appear twice, it's a bit more tricky.

For code that needs more than two lines, I'll write a function. But when facing things like:

```<code>print "Hi, Tom"
print "Hi, Mary"
</code>```

I'm hesitant to write:

```<code>def greeting(name):
    print "Hi, " + name

greeting('Tom')
greeting('Mary')
</code>```

The second one seems too much, doesn't it?

But what if we have:

```<code>for name in vip_list:
    print name
for name in guest_list:
    print name
</code>```

And here is the alternative:

```<code>def print_name(name_list):
    for name in name_list:
        print name

print_name(vip_list)
print_name(guest_list)
</code>```

Things become tricky, no? It's hard to decide now.

What's your opinion about this?


答:
Some languages (Scala compiled to JVM, Haskell, Ocaml, etc...) have pattern matching which is superior to switch since its deconstruct data structures and bind variables (locally to the matching case).

For example, in Ocaml you might define a simplistic AST data type (a sum type or tagged union) for expressions as:

```<code>type expr =
    Num of int
   | Sum of expr * expr
   | Diff of expr * expr
   | Prod of expr * expr
  (* etc... *)
;;
</code>```

Then you would represent the AST of 2*(3+4) as

```<code>   Prod (Num 2, Sum (Num 3, Num 4))
</code>```

and your recursive evaluation function is

```<code>let rec eval exp =
  match exp with
   Num x -> x
   | Sum (el,er) -> (eval el) + (eval er)
   | Diff (el,er) -> (eval el) - (eval er)
   | Prod (el,er) -> (eval el) * (eval er)
   (* etc....*)
</code>```

Notice that the matching variables el and er have their scope limited to each match clause, like lines above starting with | (and they are bound by the matching operation)

The compiler generally translates pattern matching into switch like constructs (e.g. indexed jumps) and field extractions.

Body:
Some languages (Scala compiled to JVM, Haskell, Ocaml, etc...) have pattern matching which is superior to switch since its deconstruct data structures and bind variables (locally to the matching case).

For example, in Ocaml you might define a simplistic AST data type (a sum type or tagged union) for expressions as:

type expr =
    Num of int
   | Sum of expr * expr
   | Diff of expr * expr
   | Prod of expr * expr
  (* etc... *)
;;

Then you would represent the AST of 2*(3+4) as

   Prod (Num 2, Sum (Num 3, Num 4))

and your recursive evaluation function is

let rec eval exp =
  match exp with
   Num x -> x
   | Sum (el,er) -> (eval el) + (eval er)
   | Diff (el,er) -> (eval el) - (eval er)
   | Prod (el,er) -> (eval el) * (eval er)
   (* etc....*)

Notice that the matching variables el and er have their scope limited to each match clause, like lines above starting with | (and they are bound by the matching operation)

The compiler generally translates pattern matching into switch like constructs (e.g. indexed jumps) and field extractions.


问:
What is the status of @ and $ characters in C++?
C++ syntax uses almost all printable ASCII characters and some of them in several contexts. Only two unused are @ and $ characters. Why they are not used? Are they reserved for some "meta" purpose?</p>

答:
It is implementation defined (so you should avoid using them if you care about portability).

Some compilers (e.g. GCC)  accept $ in identifiers.

BTW, the backquote ` is also unused in C++.

Notice that early definition of C or C++ languages did not require (and where not used) on systems using ASCII. This explains why some ASCII characters remain unused. (Some systems used EBCDIC and had a C compiler).

Read also about the (ugly) trigraphs (they might go away in C++17)

Be aware of UTF-8 (perhaps some compilers accept it as an extension...)

As Jules commented, read also about name mangling.


问:
Job and workers, pattern / design
I have x number of worker classes which all implement a specific interface, i have a job descriptions
Each job description States the different worker classes that should execute to complete the job
Am I smelling a strategy pattern here?

All workers share some configuration  data so I think I should have a seperate configuration classes that I can be passed into the constructor at worker creation

AM I walking down the right path?

EDIT

more high level details

the job description specifies the different workers that needs to run to produce a sample file.

each worker deals with a specific set of data domains

all workers share the same output generation class to produce file(s) that are structurally same.

there can be y number of job definitions and x number of workers so

y(1) uses x(1),x(2),x(3)

y(2) uses x(2),x(3),x(4)

i could have a JobFactory that returns a collection of the required worker classes and then iterate through the collection while invoking the worker execute method.

just looking for more ideas/opinions.

答:
The design that springs to mind for me is to have a Job class, which holds the recipe for the job and a collection of abstract Worker instances.

To create the concrete workers required by the recipe, I would use a WorkerFactory (creating one worker per request).

The responsibility of the Job class is to create the string of workers needed for a job and to execute those workers.

Title: Job and workers, pattern / design


问:
How to add new child entity to a repository in DDD?
I'm new to Domain-Driven Design and I'm using it in an application I am developing. I'm getting stuck on how to put new entities into a repository. My repository is just a big collection of entities that I can query.

One of my entities can have child entities, so I gave it an AddChild() method. It uses a factory to instantiate the child and adds the child to a child collection.

How should I add this new child entity to my repository?

I don't want the caller of AddChild() to add it, and I have read that entities themselves should not access repositories.

答:
I have a similar situation, in that my domain model consists of a web of linked entities. I have solved it in this way:

For each Entity type, I have a corresponding EntityRepository. The Entities are completely unaware of the existence of the repositories.

Each EntityRepository type maintains a cache of the Entity instances that it knows about (those that were retrieved from that repository), and it has references to the repositories of linked entities.

When saving an Entity in its repository, the repository checks if it knows about the entity and either inserts it in the database (and its cache), or it updates the database. For linked entities, the repository requests the repository of the linked item to save that item and then it updates the database links between the entities.

Entities that are disassociated from each other are detected automatically in a similar way in the repositories.

To give an example in pseudocode:

```<code>// Entities
class Child { }

class Parent
{
    addChild(Child);
    Child[] getChildren();
}

// Repositories
class ChildRepository
{
    save(Child entity)
    {
        if (cache.contains(entity))
            updateDatabase(entity);
        else
            AddToDatabase(entity);
    }
    Child[] cache
}

class ParentRepository
{
    save(Parent entity)
    {
        if (cache.contains(entity))
            updateDatabase(entity);
        else
            AddToDatabase(entity);
        childRepo.save(entity.children());
        updateParentChildLinkTable();
    }
    Parent[] cache
    ChildRepository childRepo
}
</code>```

Body:
I have a similar situation, in that my domain model consists of a web of linked entities. I have solved it in this way:

For each Entity type, I have a corresponding EntityRepository. The Entities are completely unaware of the existence of the repositories.

Each EntityRepository type maintains a cache of the Entity instances that it knows about (those that were retrieved from that repository), and it has references to the repositories of linked entities.

When saving an Entity in its repository, the repository checks if it knows about the entity and either inserts it in the database (and its cache), or it updates the database. For linked entities, the repository requests the repository of the linked item to save that item and then it updates the database links between the entities.

Entities that are disassociated from each other are detected automatically in a similar way in the repositories.

To give an example in pseudocode:

// Entities
class Child { }

class Parent
{
    addChild(Child);
    Child[] getChildren();
}

// Repositories
class ChildRepository
{
    save(Child entity)
    {
        if (cache.contains(entity))
            updateDatabase(entity);
        else
            AddToDatabase(entity);
    }
    Child[] cache
}

class ParentRepository
{
    save(Parent entity)
    {
        if (cache.contains(entity))
            updateDatabase(entity);
        else
            AddToDatabase(entity);
        childRepo.save(entity.children());
        updateParentChildLinkTable();
    }
    Parent[] cache
    ChildRepository childRepo
}


问:
What is the definition of "technical debt"?
What is the definition of technical debt?</p>

答:
It pretty much means the bad design choices made during software development in order to get a product out of the door.

The idea being that you will "pay the debt" later on and fix the bad design when you have the time.

Wikipedia has a more detailed explanation.

OwnerDisplayName: Oded


答:
The Technical Debt Metaphor is meant to evoke an analogy to Financial Debt.

Financial Debt can be used as a tool to bootstrap a business: you need machines to make money, but you need money to buy machines. You break this catch-22 by taking out a loan to buy machines, and then repaying the loan using the money you gained using the machines.

Technical Debt can be used as a tool to boostrap your understanding of the domain: you need to play around with the software to figure out what it's all about, but you need to know what it's about to write the software. You break this catch-22 by writing the software as best as you can using the partial understanding you have currently, then rewrite the software using the understanding you gained from playing around with it.

Just like Financial Debt, Technical Debt needs to be small, needs to be paid back, and it accumulates interest if it isn't paid back.

It's very important that Technical Debt is a tool for understanding. It is not an excuse for bad code, bad design or bad decicions. It is not about getting a product out of the door.

It is about getting experience. (Note that getting a product out of the door might very well be a prerequisite to getting experience, but it's not what Technical Debt is about.)

Ward Cunningham originally coined the term when he was explaining to his boss why refactoring was important. The software they were working on was financial software, the company was a financial company, the boss was a finance guy, so he used a financial metaphor.

Since you specifically asked about a definition, here's mine:

Technical Debt is the difference between your current understanding of the domain and the understanding that is reflected in the current version of the software.

Title: What is the definition of "technical debt"?

Body: What is the definition of technical debt?</p>

OwnerDisplayName: Jörg W Mittag


答:
The original term was coined by Ward Cunningham, and the idea is that if you cut corners in the short term, you’re borrowing against the future maintainability of the software and that at some point, not unlike a credit card, you’ll pay down that debt by going back and fixing the hacky solutions that were put in place.

See the blog post here for more information and how to mitigate it:

Technical Debt

OwnerDisplayName: Ben Lakey


问:
What is the best way to create dynamically a DOM?
I know that there are plenty answers to this question on stackoverflow, but I can´t find one that give me an answer that can help me to solve a question that came out after read a lot of Javascript, JQuery articles and using those languages for several months.

Here is the deal:

Apparently, I can do a generic site that can charge a Dom dynamically, I read article that says that do this and adding element to the dom at the time the page is loading is dangerous, and use this on framework like Angularjs is almost a sin to think on angular as a jquery background.

So, with that in mind.

Why is such a big deal to make a Dom loading dynamically (input a Json File)?

And the finally Question is, there’s a right way to do it?
Thanks in advance!

答:
I think you should use jQuery when you manipulate an existing DOM.
Of course with jQuery you can insert HTML snippets too, but i think its harder to separate the view from the js code in this way.

In Angular you define the view in HTML and the js code will make it workable.

I can summarise the main difference between the jquery and the angular way:

with jquery you manipulate DOM (and handle events)

with angular you define the view and the behavior