答:
Is it just a symptom of my previous classes depending too tightly on each other?

Most probably yes. Although you can get similar effects with a rather nice and clean code base when the requirements change enough

How can I avoid this kind of cascading refactorings in the future?

Apart from stopping to work on legacy code, you can't I'm afraid. But what you can is using a method that avoids the effect of not having a working code base for days, weeks or even months.

That method is named "Mikado Method" and it works like this:

write down the objective you want to achieve on a piece of paper

make the simplest change that takes you into that direction.

check if it works using the compiler and your test suite. If it does continue with step 7. otherwise continue with step 4.

on your paper note the things that need to change to make your current change work. Draw arrows, from your current task, to the new ones.

Revert your changes This is the important step. It is counter intuitive and physically hurts in the beginning, but since you just tried a simple thing, it isn't actually that bad.

pick one of the tasks, that has no outgoing errors (no known dependencies) and return to 2.

commit the change, cross out the task on the paper, pick a task that has no outgoing errors (no known dependencies) and return to 2.

This way you will have a working code base in short intervals. Where you also can merge changes from the rest of the team. And you have a visual representation of what you know you still have to do, this helps to decide if you want to continue with the endevour or if you should stop it.

Title: How do I avoid cascading refactorings?

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


问:
Changing an object's (apparent) class at runtime
I'm looking for a design pattern to solve the following problem:

An object (let's say representing a document) can change its type dynamically during its lifetime (e.g. when it is saved with a different file extension).

The object contains many virtual methods so that depending on the object type it can behave in different ways (e.g. different syntax highlighting).

The application contains many references to the object, which should not become invalid when the object's type changes. So it won't do to destroy the object and create a new one of the new type.

An 'obvious' solution is to use composition, so that the object seen by the application (the outer object) never changes, but it forwards all calls to a contained object that can be destroyed and recreated whenever the type changes.

But this requires a method in the outer object for each virtual method in the contained object to forward the call.

Is there a design pattern that avoids this need for forwarding methods?

(Ideally I'd like a pattern that doesn't require the language to support interfaces.)

Update

Thanks to comments below, I've identified that the State design pattern implements what I want, except that it requires explicitly forwarding every method from the wrapper class to the wrapee class.

So another (perhaps clearer?) way of stating my original question is this: Is there an alternative design pattern that implements the functionality of the State design pattern in (virtually) any object oriented language without needing explicitly to forward every method?

('No' is a perfectly valid answer by the way as long as you can justify it.)

答: The solution you describe in your question is usually called the "bridge pattern". Depending on the language in use, there may be a way of implementing it without manually managing all the delegating methods. For example, in Ruby one can simply define the "method_missing" method to perform a dynamic lookup on the target object and dispatch to a method with the same name as the called method. In Java you may be able to use a bytecode generation library to achieve a similar effect, e.g Javassist.</p>

ContentLicense: CC BY-SA 3.0


问:
Java applets with Safari on Windows as compared to Safari on OS X
I have a developed an Applet which works fine on Chrome/IE/FF on Windows. I am not expecting any users for Safari on Windows but there might be the odd user who may be on a Mac.

As of now, I don't have a Mac to test my applet on.

I was wondering how similar is the behaviour of Safari on Windows is as compared to Safari on a Mac as far as Java Applets go. I was wondering if testing on Safari on Windows would be good enough or do I need to buy a Mac. I know that I can never be sure without actually testing on Mac, but I am on a tight budget for this and am willing to take a risk if it's not too big.

UPDATE: The applet accesses local devices.

答:
I don't think this is the right place for this question, but I am not sure.

However, you can use BrowserStack. It gives you a VM of your desired OS/Browser to work with.


问:
Efficiently save big data structures
I need to save big data structure (Tree with specific nodes) into file efficiently. Data is always changing, so I need to rewrite whole data structure very often, so simple serialization is not good option.

Which algorithms can be used to efficient saving of big data structures?

I used simple serialization, but i want to try algorihms which save only delta of my structure and then union those changes. In which direction should I move?

答:
Short answer: consider to use a database.

Databases allow you easily to save only the changed part of a whole bunch of data very quickly, whilst you don't have to care for the unchanged parts.

And here is a former SO post dealing with the topic of storing tree structures in databases.

Title: Efficiently save big data structures


问:
Is it appropriate to use inheritance to prevent code duplication of the logic for a user control?
Suppose I have two or more UserControl implementations with vastly different implementations but near identical code-behind.  One strategy to avoid code duplication is as follows:

Change each UserControl to inherit from a new abstract class, AwesomeUserControl

Move all of the codebehind from each UserControl into AwesomeUserControl (AwesomeUserControl does not have an ascx file).

Add abstract getters to AwesomeUserControl for any controls from the ascx file of the original UserControls.

Implement these getters in each UserControl.

This strategy works extremely well and is easy to maintain.  However, it also introduces stupid scaffolding code; every new implementation of AwesomeUserControl has a bunch of getters to hook AwesomeUserControl the UI elements inside of the new control.  Any time I find myself using a strategy which requires copy-pasted scaffolding code, I worry that I am doing something wrong.  Though it does have a nice effect of failing to compile if the UI elements are missing (as opposed to skipping the scaffolding code in favor of reflection and required naming).

Is this use of inheritance reasonable?

答:
This strategy works extremely well and is easy to maintain. However,
  it also introduces stupid scaffolding code; every new implementation
  of AwesomeUserControl has a bunch of getters to hook

Access controls directly. On the abstract class:

```<code>#Region "WebControls - Objects must be on derived aspx and deleted from .asx.designer"
  Protected WithEvents SomeDiv As Global.System.Web.UI.HtmlControls.HtmlGenericControl
  Protected WithEvents SomeLabel As Global.System.Web.UI.WebControls.Label
  Protected WithEvents SomeLinkButton As Global.System.Web.UI.WebControls.LinkButton
  ...
#End Region
</code>```

Body:
This strategy works extremely well and is easy to maintain. However,
  it also introduces stupid scaffolding code; every new implementation
  of AwesomeUserControl has a bunch of getters to hook

Access controls directly. On the abstract class:

#Region "WebControls - Objects must be on derived aspx and deleted from .asx.designer"
  Protected WithEvents SomeDiv As Global.System.Web.UI.HtmlControls.HtmlGenericControl
  Protected WithEvents SomeLabel As Global.System.Web.UI.WebControls.Label
  Protected WithEvents SomeLinkButton As Global.System.Web.UI.WebControls.LinkButton
  ...
#End Region


答:
I tend to agree with Doc Brown's answer: you'll better use a database. That might be sqlite or a real database server: mongodb or postgresql, etc.... You could perhaps use an indexed file like GDBM (instead of a database) in some limited circumstances. If the data is small (which apparently it is not) you might consider persisting all of it in some textual formats like JSON (which you could also use inside database tables).

You should also define if your data structure is a real tree (without shared sub-nodes) or if it is a graph. You may have to manage the set of already dumped items, and handle shared data. Shared pointers and smart pointers may matter a lot.

You could store, in every significant object in memory, some database identifier (or id number), and perhaps other meta-information related to saving the data (saving timestamp, change time, etc...)

BTW, copying Garbage Collection algorithms may be relevant (since persisting to some database is quite similar to a copying GC). Read also the GC handbook.

You might be interested by persistence and application checkpointing.

You should design the persistence machinery quite early if possible.

Title: Efficiently save big data structures

Body:
I need to save big data structure (Tree with specific nodes) into file efficiently. Data is always changing, so I need to rewrite whole data structure very often, so simple serialization is not good option.

Which algorithms can be used to efficient saving of big data structures?

I used simple serialization, but i want to try algorihms which save only delta of my structure and then union those changes. In which direction should I move?


问:
In ASP.NET MVC, should the view models have an ID?
When developing an ASP.NET MVC application that allows the model to be updated, you need some way to know how to take the updated view model and match it back to the model that is now updated.  There seems to be a few different ways of doing this and I'm wondering if any of these are not proper MVC (much like having your controller store data that should be in the model is not proper MVC)?

All View Models have an ID:
Pros

Always ensure you can match to your model.

Cons

You have to be real careful that none of the IDs were changed else you can have users updating rows they shouldn't have access to.

Only the bare minimum view models have an ID:
Pros

Far less checking needed to avoid users updating data they shouldn't access.

Cons

Far more difficult to track what view models matches what model.

You still have to check the few view models with IDs to make sure the user isn't updating data they shouldn't have access to.

No view models have ID:

Pros

No need to check IDs for updates.

Cons

You have to abandon statelessness.

So I have two questions.

First, is there a correct/incorrect choice?  (If not, that means the choice is a matter of opinion and my second question opinion based and should be ignored.)

Second, if there is a correct/incorrect choice, which is it?

To clarify on a comment, I'm talking when you have a view model that is a mimic of your database object.

Think this:

```<code>public class InvoiceViewModel  //Does not have ID, does not relate to model.
{
    public CustomerViewModel CustomerVM { get; set; }  //Maybe has ID?  Does relate to model.
    public AddressViewModel BillingAddressVM { get; set; } //Ditto
    public AddressViewModel ShippingAddressVM { get; set; } //Ditto
    public List<InvoiceLineItemViewModel> ItemVMs { get; set; }  //Each one has an ID?
}
</code>```

not this:

```<code>public class InvoiceViewModel
{
    public Customer Customer { get; set; }
    public Address BillingAddress { get; set; }
    public Address ShippingAddress { get; set; }
    public List<InvoiceLineItem> Items { get; set; }
}
</code>```

答: By default you should have an id in view even though you are not using it. Create a column in database named as id and tick the auto increment feature over it so you will be sorted.


问:
How to solve this problem of duplicate code with a design pattern
This is what I am doing,

Creating a new Pdf document using Aspose Pdf

Adding few different types pages you know introduction page, table of content pages etc...

Adding some further documents to it [just created pdf].

Not sure which pattern to use.

I am thinking about creating classes for different types of pages to create specific pages, as different departments can ask for different introduction pages or different layout of table of contents and so on...

Page type classes will have a contruct which will create the page and return the pdf component back.

for each different layout i will create a new page.

答:
IMHO you are approaching this from the very wrong end. You ask for avoiding duplicate code where it seems you do not have any (or at least not much) code so far.

Better start implementing the code for creating one or two PDFs, and whenever you are tempted to copy/paste a piece of code, stop for moment, step back and think if you can avoid the duplication by refactoring the common parts into a single function. Whenever you have to deal with data forming a group which belongs together, try to introduce a struct or a class. And when you note you have isolated operations on that data, refactor to member functions of the created class. When you notice you have similar requirements in different classes, refactor those out to helper classes, common base classes and in the end resusable libraries.

When you follow that path, you may come to a point when you have written real code where you have problems to isolate commonalities - then is a good time to present the problem here, or on stackoverflow.com, or on codereview.stackexchange, and ask if there is a design pattern which can help you.


问:
Application components dependency and decoupling
In my client application I have two major components:

Core: wrapper that handles everything about running the actual application

NetworkClient: A layer that takes care of communicating (receiving/sending packets) with the server.

What I am not sure about is the way the NetworkClient should serve information to the Core process of the application. The core process has an event queue that is executed in update() calls. My initial idea is to have something like this:

NetworkClient receives a snapshot of the state changes

Takes that snapshot

Chops it down to event objects for the Core process to handle.

The problem I see with that, isn't the NetworkClient class too dependent on the Core class? The opposite is not an issue however because, there can be a different client (UDP, TCP, etc) that works with the Core class.

So from a design point of view, is there a reason I might not want the NetworkClient class to be written for the specific implementation of the Core class?

答:
Writing a NetworkClient specifically for the Core class does cause a dependency.

Alternatively you can create an integration layer that abstracts the interaction of the two. For the sake of argument, call it a Service. The Service is neither implemented in the Core or NetworkClient. Typically the Service has knowledge of transporting a resource (e.g. some state) from one place to another, using a specified mechanism (e.g. database, network, etc.) - "I know a guy who can do that for you". The Core is loosely coupled to the Service by subscribing to events that it emits. On the other hand, NetworkClient implements the means of transporting some "state" from one place to another, specifically over a network. The Service depends on the NetworkClient to achieve this.


问:
This way I'm writing this code is testable, but is there something wrong with it I'm missing?
I have an interface called IContext. For the purposes of this it doesn't really matter what's it does except the following:

```<code>T GetService<T>();
</code>```

What this method does is look at the current DI container of the application and attempts to resolve the dependency. Fairly standard I think.

In my ASP.NET MVC application, my constructor looks like this.

```<code>protected MyControllerBase(IContext ctx)
{
    TheContext = ctx;
    SomeService = ctx.GetService<ISomeService>();
    AnotherService = ctx.GetService<IAnotherService>();
}
</code>```

So rather than adding multiple parameters in the constructor for each service (because this will get really annoying and time-consuming for the developers extending the application) I am using this method to get services.

Now, it feels wrong. However, the way I'm currently justifying it in my head is this - I can mock it.

I can. It wouldn't be difficult to mock up IContext to test the Controller. I'd have to anyway:

```<code>public class MyMockContext : IContext
{
    public T GetService<T>()
    {
        if (typeof(T) == typeof(ISomeService))
        {
            // return another mock, or concrete etc etc
        }

        // etc etc
    }
}
</code>```

But as I said, it feels wrong. Any thoughts / abuse welcome.

答:
I am adding an answer to this based on everybody else's contributions. So many thanks everbody. First here's my answer: "No, there's nothing wrong with it".

Doc Brown's "Service Facade" answer
I accepted this answer because what I was looking for (if the answer was "no") was some examples or some expansion upon what I was doing. He provided this in suggesting that A) it's got a name, and B) there are probably better ways to do this.

Benjamin Hodgson's "Service Locator" answer
As much as I appreciate the knowledge I've gained here, what I have is not a "Service Locator". It is a "Service Facade". Everything in this answer is correct but not for my circumstances.

USR's answers

I'll tackle this in more detail:

You're giving up a lot of static information this way. You're
  deferring decisions to runtime like many dynamic languages do. That
  way you loose static verification (safety), documentation and tooling
  support (auto-complete, refactorings, find usages, data flow).

I don't lose any tooling and I'm not losing any "static" typing. The service facade will return what I've configured in my DI container, or default(T). And what it returns is "typed". The reflection is encapsulated.

I don't see why adding additional services as constructor arguments is
  a big burden.

It's certainly not "rare". As I'm am using a base controller, each time I need to change it's constructor, I may have to change 10, 100, 1000 other controllers.

If you use a dependency injection framework you will not even have to
  manually pass in the parameter values. Then again you loose some
  static advantages but not as many.

I am using dependency injection. That's the point.

And finally, Jules' comment on Benjamin's answer
I am not losing any flexibility. It's my service facade. I can add as many parameters to GetService<T> as I want to to distinguish between different implementations, just as one would do when configuring a DI container. So for example, I could change GetService<T>() to GetService<T>(string extraInfo = null) to get around this "potential problem".

Anyway, thanks again to everybody. It's been really useful. Cheers.


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

答: Repositories are typically for Aggregate Roots only. No need for Repositories for non-root (what you call "child" ?) Entities because they are persisted and loaded automatically along with the Aggregate they belong to.</p>


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

答:
You have design-patterns(composite,memento,singletom ...), you have principles of OOD (SRP,Dry,LSP ...) and you have tactics (CJ, Paranoid, NAG ...). The two examples follows different tactics.

Tactics decide if you need performance, logging or readability. They are typically specified by the senior developers or CTO.

Because you say performance is negligible and its Javascript, so we are in View of MVC and you are near to the User i would advice this NAG style (also lets use OOP a little):

```<code>function ToolTipAppearanceManager(){
  /** @param show {Boolean} <code>true</code> to let it appear,
   *                        <code>false</code> to hide.
   */
  this.setVisible = function(show){
    if (show){
      if (tool tip is shown) {
          if(console && console.warn)console.warn('Already visible. Maybe bug!');
      }
      show tooltip;
    } else {
      if (not tool tip is shown){
          if(console && console.warn)console.warn('Already removed. Maybe bug!');
      }
      remove tooltip;
    }

  }
}
var appMan = new ToolTipAppearanceManager();
$(this).plothover(function(item) {
   appMan.setVisible(item && item != "undefined");
});
</code>```

Title: Test & remove, or always remove

Body:
You have design-patterns(composite,memento,singletom ...), you have principles of OOD (SRP,Dry,LSP ...) and you have tactics (CJ, Paranoid, NAG ...). The two examples follows different tactics.

Tactics decide if you need performance, logging or readability. They are typically specified by the senior developers or CTO.

Because you say performance is negligible and its Javascript, so we are in View of MVC and you are near to the User i would advice this NAG style (also lets use OOP a little):

function ToolTipAppearanceManager(){
  /** @param show {Boolean} <code>true</code> to let it appear,
   *                        <code>false</code> to hide.
   */
  this.setVisible = function(show){
    if (show){
      if (tool tip is shown) {
          if(console && console.warn)console.warn('Already visible. Maybe bug!');
      }
      show tooltip;
    } else {
      if (not tool tip is shown){
          if(console && console.warn)console.warn('Already removed. Maybe bug!');
      }
      remove tooltip;
    }

  }
}
var appMan = new ToolTipAppearanceManager();
$(this).plothover(function(item) {
   appMan.setVisible(item && item != "undefined");
});


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

答:
Technical debt is the result of trading code quality for something else you deem more important at that moment. It can be going to market fast to get feedback. It can be shipping a vulnerability patch quickly. It can be focusing on doing one (other) thing well.

Technical debt is a conscious tradeoff. It's different from making a mess.

ContentLicense: CC BY-SA 2.5


答:
The best arguments against the Service Locator anti-pattern are plainly stated by Mark Seemann so I won't go too much into why this is a bad idea - it is a learning journey that you have to take the time to understand for yourself (I also recommend Mark's book).

OK so to answer the question - let's re-state your actual problem:

So rather than adding multiple parameters in the constructor for each service (because this will get really annoying and time-consuming for the developers extending the application) I am using this method to get services.

There is a question that addresses this issue on StackOverflow. As mentioned in one of the comments there:

The best remark: "One of the wonderful benefits of Constructor Injection is that it makes violations of the Single Responsibility Principle glaringly obvious."

You're looking in the wrong place for the solution to your problem. It is important to know when a class is doing too much. In your case I strongly suspect that there is no need for a "Base Controller". In fact, in OOP there is almost always no need for inheritance at all. Variations in behaviour and shared functionality can be achieved entirely through appropriate use of interfaces, which usually results in better factored and encapsulated code - and no need to pass dependencies to superclass constructors.

In all of the projects I have worked on where there is a Base Controller, it was done purely for the purposes of sharing convenient properties and methods, such as IsUserLoggedIn() and GetCurrentUserId(). STOP. This is horrible misuse of inheritance. Instead, create a component that exposes these methods and take a dependency on it where you need it. This way, your components will remain testable and their dependencies will be obvious.

Aside from anything else, when using the MVC pattern I would always recommend skinny controllers. You can read more about this here but the essence of the pattern is simple, that controllers in MVC should do one thing only: handle arguments passed by the MVC framework, delegating other concerns to some other component. This again is the Single Responsibility Principle at work.

It really would help to know your use case to make a more accurate judgment, but honestly I can't think of any scenario where a base class is preferable to well-factored dependencies.

Title: This way I'm writing this code is testable, but is there something wrong with it I'm missing?

Body:
I have an interface called IContext. For the purposes of this it doesn't really matter what's it does except the following:

```<code>T GetService<T>();
</code>```

What this method does is look at the current DI container of the application and attempts to resolve the dependency. Fairly standard I think.

In my ASP.NET MVC application, my constructor looks like this.

```<code>protected MyControllerBase(IContext ctx)
{
    TheContext = ctx;
    SomeService = ctx.GetService<ISomeService>();
    AnotherService = ctx.GetService<IAnotherService>();
}
</code>```

So rather than adding multiple parameters in the constructor for each service (because this will get really annoying and time-consuming for the developers extending the application) I am using this method to get services.

Now, it feels wrong. However, the way I'm currently justifying it in my head is this - I can mock it.

I can. It wouldn't be difficult to mock up IContext to test the Controller. I'd have to anyway:

```<code>public class MyMockContext : IContext
{
    public T GetService<T>()
    {
        if (typeof(T) == typeof(ISomeService))
        {
            // return another mock, or concrete etc etc
        }

        // etc etc
    }
}
</code>```

But as I said, it feels wrong. Any thoughts / abuse welcome.


问:
If you could only have one programming related book on your bookshelf what would it be and why?
One per answer please. I'll add my favourite as an answer.</p>

答:
Object Design: Roles, Responsability and Collaborations

This is by far my favorite programming book (even if it is not language dependent). In my humble opinion is the book that better presents the case on how to design objects that relate to their cousins/brothers/neighboors. A must have in any serious programmer bookshelf.


问:
DRYest approach to "rendering" drag-and-drop template editor results to HTML
I'm in the process of designing a browser based system that will allow non-technical users to quickly and easily change the content of certain parts of a web page via a WYSIWYG template-based drag-and-drop editor. Essentially, the user can choose from a few prepared templates, drop some image files into predefined areas within the template, edit some text or links in predefined areas, and the result will be reflected on the actual website.

I have a simple prototype of the editor interface written in Polymer, which works great so far. I am now trying to figure out the best way to save the results of this server-side, and produce the final static HTML output based on it. I'm pretty keen on keeping Polymer client-side, as the interface is rather complex and dynamic and more traditional pure-Javascript approaches can get very messy very quickly.

However, including the same Polymer templates client-side is not feasible I think; I'll need to produce compact, no-Javascript, highly compatible pure HTML output.

The obvious solution would be to prepare two parts to the same template: an editable Polymer version which results in some blob of attributes being stored on the server (e.g. template: 1, placeholder1: imageXYZ, placeholder2: "Foobar", etc.), coupled with some server-side rendering process which takes this data and produces the final HTML output. The problem is that this requires two versions of the same HTML template to be kept in sync.

Another solution may be to produce some meta-template from which both an editable version and the rendered result can be produced programmatically; this approach seems to be very complex though, possibly too complex for the scope of this project.

Are there any other well known approaches for dealing with this problem, or well defined meta-template libraries/systems/approaches that will work well in my scenario? Or will I simply have to bite the bullet and accept the redundancy as part of the task?

答:
place the blanc templates on the server, you client(s) download them and respond with a certain configuration for it, keeping a lot of clients in sync and maybe with problems in their template (bugs etc) might cause more problems, on (i assume php) server do a format check when updating.

Ik you keep it all in templates, there is even no need for static HTML, but then you need some kind of MysQL backend to generate Page(x) that used template(y) which had picture links collection, and data block collections etc...

BTW all lot of such programs do exist and they are called content management systems.


问:
Use and manage Front End Assets for Web
I am  a beginner and am currently developing a kind of cms using PHP. The number of libraries that we can potentially use in the front end is large.  I have a question about properly selecting, managing and using front end asset libraries.

I don't think just including a bunch of front end libraries like this is the best approach:

```<code><script src="library1" /></script>
<script src="library2" /></script>
<script src="library3" /></script>
// and soon..
</code>```

What if we use, let's say 20 ? Is that good practice, declaring the script tags 20 times ?

What I do currently is use Assetic, a php library for managing assets. I create a dump file (and cache it) for each request to my application before loading a template. My controller (I use MVC) could be something like this:

```<code>function indexAction()
{
    // some logic

    $assetManager = $this->get('assetic'); // get assetic service
    $css = $assetManager->createAsset(array(
            '@bootstrap',
            '@jquery_ui'
             // and many other library
    ));

     $assetContent = $css->dump();

     // create asset url, dont mind about this
     $data['stylesheet'] = $this->createAssetUrl($assetContent);

    return $this->render('index-template', $data);
}
</code>```

And in the template (index-template), I could put kind of:

```<code><link href="<?php echo $stylesheet ?>" rel="stylesheet" type="text/css">
</code>```

I do that in almost every controller to include a bunch of assets to view. But I am not sure if this is the best method. Are there any better practical method that I don't know ?

答: You might consider managing your frontend dependencies with some dedicated frontend tools. A common combination is using Grunt and Bower to manage your javascript and CSS files. A dedicated setup like this makes it easy to do things like define different tasks for development and production, so while developing you include as many scripts and styles as you need, but for the production build you include a minification and/or concatenation task to combine everything into one file.</p>

Title: Use and manage Front End Assets for Web


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

答:
As a corollary to @DocBrown's comment to @RobertHarvey about using functions to create abstractions: if you can't come up with an adequately informative function name that isn't significantly more concise or clearer than the code behind it, you are not abstracting much. Absent any other other good reason for making it a function, there is no need to do so.

Also, a function name rarely captures its full semantics, so you may have to go check its definition, if it isn't commonly-enough used to be familiar. Particularly in other than a functional language, you may need to know if it has side-effects, what errors may occur and how they are responded to, its time complexity, whether it allocates and/or frees resources, and whether it is thread-safe.

Of course, we are by definition considering only simple functions here, but that goes both ways - in such cases, inlining is not likely to add complexity. Furthermore, the reader probably will not realize that it is a simple function until he looks. Even with an IDE that hyperlinks you to the definition, the visual jumping around is an impediment to understanding.

Generally speaking, recursively factoring code into more, smaller functions will eventually bring you to the point where the functions no longer have independent meaning, because as the code fragments they are made from get smaller, those fragments get more of their meaning from the context created by the surrounding code. As an analogy, think of it like a picture: if you zoom in too closely, you can't make out what you are looking at.


问:
How can I ensure my JavaScript code will run in both Node.js and Io.js
With the danger of fragmentation due to the fork in Node, how can I make sure a "Node" project will run across both Node and its fork?

The hope is that they will join together again once Joyent and the creators of io.js resolve their differences but one cannot hope that this will definitely be the case. So as a node contributor it would make sense to bet on both options and having your codebase require less maintenance if the fork does become a long term one.

答:
The same way you always do when trying to make a program "platform independent":

you try to use only features available on both platforms

you provide different implementations for functions where this not possible, and switch between the implementation by detecting which platform you are using

and the most important step: you test it on both platforms


问:
Is it a good idea to have a database row that represents an unknown value within a system
We have two systems, System A imports a list of sports events from system B, it only wants to import the events we will be providing live data for, the filter used to hide events that we are not providing data for is if the event has a referee assigned to it.

The problem with this is that we don't know who the referee will be for particular events but we know there will be one so someone has created a referee with the name TBC and assigned it to a bunch of events so they will get imported.

Now there is a request to be able to mass assign this TBC referee to multiple events to save our operations staff from having to manually assign the referee for each event one by one.

This to me seems like a very bad idea, I don't like the idea of a referee called TBC in the first place but i can't really explain why, just seems like an anti pattern to me.

Can someone help me out and explain if it is a bad idea or not and why ?

答:
Let us assume there's an EVENT table and a REFEREE table, and that the first one has a PK (referee_id) which refers to REFEREE's PK (referee_id).

Then one "TBC" referee (not a real person), is inserted in table REFEREE, so any event that has no referee assigned a the moment of insertion can at least be assigned the code of that imaginary referee.

That doesn't look like a very good idea to me, compared to simply leaving the FK in it's null state:

As FKs must accept null, there's always the possibility of having events with "TBC" as well as others with nothing (null). That means code must handle both situations everywhere. For example a report listing all events with no referees should consider both cases.

My recomendation is:

Create a view that shows the literal "TBC" whenever there's no assigned referee, like this:

```<code>create view v_events as
select
    e.event_name,
    e.event_date,
    nvl(r.referee_name,'TBC') as referee_name
from
    event e left join referee r (on e.referee_id = r.referee_id);
</code>```

In the case the referee is not it's own table but just a text column in EVENT:

```<code>create view v_events as
select
    e.event_name,
    e.event_date,
    nvl(e.referee_name,'TBC') as referee_name
from
    event e;
</code>```

Note: NVL is an Oracle function, substitute with an equivalent function in your RDBMS, like COALESCE in Postgres.

Have all code select that view instead of the real table. That way everyone will think there's a "TBC" referee assined by default.

Body:
Let us assume there's an EVENT table and a REFEREE table, and that the first one has a PK (referee_id) which refers to REFEREE's PK (referee_id).

Then one "TBC" referee (not a real person), is inserted in table REFEREE, so any event that has no referee assigned a the moment of insertion can at least be assigned the code of that imaginary referee.

That doesn't look like a very good idea to me, compared to simply leaving the FK in it's null state:

As FKs must accept null, there's always the possibility of having events with "TBC" as well as others with nothing (null). That means code must handle both situations everywhere. For example a report listing all events with no referees should consider both cases.

My recomendation is:

Create a view that shows the literal "TBC" whenever there's no assigned referee, like this:

create view v_events as
select
    e.event_name,
    e.event_date,
    nvl(r.referee_name,'TBC') as referee_name
from
    event e left join referee r (on e.referee_id = r.referee_id);

In the case the referee is not it's own table but just a text column in EVENT:

create view v_events as
select
    e.event_name,
    e.event_date,
    nvl(e.referee_name,'TBC') as referee_name
from
    event e;

Note: NVL is an Oracle function, substitute with an equivalent function in your RDBMS, like COALESCE in Postgres.

Have all code select that view instead of the real table. That way everyone will think there's a "TBC" referee assined by default.


问:
What is the efficient way to eliminate duplication? Design patterns?
I have a helper class which has a method that perform some checks against a field in a model. I have two models, ModelA and ModelB, they have some similarities but not all. One of them is they both have a field, lets say string ProductCheckField. The ProductCheckMethod returns back the Model, because of that it has created duplication of methods which does the same thing but returns a different model. Even the extracted methods are duplicates. Is there a good design pattern or any other good practice/technique I can use to eliminate duplication of having to create two methods?

N.B I can't use a shared Interface as the models are not the same.

Currently I have..

```<code>public class ModelA
   string blah..
   int blah
   .....
   string ProductCheckField

public class ModelB
   string xyz
   int xyz
   .....
   string ProductCheckField

public class HelperClass
{

    public ModelA ProductCheckMethod(ModelA model)
    {
       /// do somthing
       performX(model);
       checkY(model);
       return model;
    }

    public ModelB ProductCheckMethod(ModelB model)
    {
       /// do somthing
       performXDuplicate(model);
       checkYDuplicate(model);
       return model;
    }
}
</code>```

答:
You seem to have some sort of mental block going on.  If you want a design that eliminates the duplication, you're going to have to change your design somehow, which you seem resistant to do.  You need to look past your current design.

Some ways to eliminate the duplication, some of which are better than others:

Put the common stuff of the models into a common class, with your models containing a reference to that object, as Telastyn suggested in the comments.

Reverse of Telastyn's suggestion, where you have a ProductCheckStuff class, with pointers inside it to one of the models.

Use generics in HelperClass or its methods, with the model as the generic parameter.

Have each model implement an interface with getters for the fields you need.

Extend the model from a base class that implements the ProductCheckMethod.

Put the product check fields and methods into a mixin (if your language supports it) that is mixed in with the other fields of your model.

You can't make an omelette without breaking some eggs.  You have a ton of choices here.  Keep trying them until you find one that works.


答:
It's hard to understand fully what you need done here. It looks like you MIGHT have a case for the Visitor pattern but you said you can't use the same interface.

The only other alternative would be the Strategy pattern where the CheckMethod would be implemented in a strategy class for each Model and instead of the overloaded methods you can use generics to map the Model to the strategy.

```<code>public class HelperClass
{
  public T CheckMethod(T model)
  {
    var strategy GetStrategyFor(typeof(T));
    var result = strategy.Execute(model);
    return result;
  }
}
</code>```

You could use an IoC container or other methods for determining how a type maps to a given strategy. But once you've done that, you can add new models and matching strategies to your heart's content.

Title: What is the efficient way to eliminate duplication? Design patterns?

Body:
I have a helper class which has a method that perform some checks against a field in a model. I have two models, ModelA and ModelB, they have some similarities but not all. One of them is they both have a field, lets say string ProductCheckField. The ProductCheckMethod returns back the Model, because of that it has created duplication of methods which does the same thing but returns a different model. Even the extracted methods are duplicates. Is there a good design pattern or any other good practice/technique I can use to eliminate duplication of having to create two methods?

N.B I can't use a shared Interface as the models are not the same.

Currently I have..

```<code>public class ModelA
   string blah..
   int blah
   .....
   string ProductCheckField

public class ModelB
   string xyz
   int xyz
   .....
   string ProductCheckField

public class HelperClass
{

    public ModelA ProductCheckMethod(ModelA model)
    {
       /// do somthing
       performX(model);
       checkY(model);
       return model;
    }

    public ModelB ProductCheckMethod(ModelB model)
    {
       /// do somthing
       performXDuplicate(model);
       checkYDuplicate(model);
       return model;
    }
}
</code>```

Body:
It's hard to understand fully what you need done here. It looks like you MIGHT have a case for the Visitor pattern but you said you can't use the same interface.

The only other alternative would be the Strategy pattern where the CheckMethod would be implemented in a strategy class for each Model and instead of the overloaded methods you can use generics to map the Model to the strategy.

public class HelperClass
{
  public T CheckMethod(T model)
  {
    var strategy GetStrategyFor(typeof(T));
    var result = strategy.Execute(model);
    return result;
  }
}

You could use an IoC container or other methods for determining how a type maps to a given strategy. But once you've done that, you can add new models and matching strategies to your heart's content.


问:
Best approach to implement an update operation of a container object?
I have an Invoice object wich may contain several FacturedServices objects stord as a list.

In may interface, the user can edit an Invoice object, delete add or edit its FacturedServices list.

Whe the user hit the save button, the updates made to  Invoice object should be passed to the database as well.

The problem is the FacturedServices list will contain heterogenous data, because some of its elements are new, others changed and some of them have been deleted from the list.

What is the best way to implement hte update of the Invoice object in the database ?

I was thinking to add a dirty property on every FacturedService object, whenever it is changed, or set the property to "new" when its newely created and then do some if else in my controller :\

If you think my question should be rephrased, please do it

EDIT :
Say I have an object Invoice I
, It has 3 FacturedServices FS1, FS2, FS3

In the interface, the user edited FS1, deleted FS2, and added FS4 to the list

now the list contains edited FS1, unchanged FS3 and newly created FS4.

in my databse, I have an InvoiceTable and a FactureServicesTable whith a referencial inetgrety to the invoice id.

my problem is in my controller there must be a way to know which FS is new which one is updated and which one was deleted, so I can execute the correct SQL commands depending on the situation.

I know this is not something new, in every desktop application at some point there should be something similar to my problem. so what is the best way to do this.

答: Why not just pass the entire list into your database (restructured as a user-defined table type)? Then you can iterate over it in the stored procedure and take the appropriate action? If the row exists in the database, update it. If it exists for that invoice in the new table but not in the database, insert it. If it exists in the database but not in the new table, delete it.</p>


问:
What's the best way to synchronise an event over multiple processes?
Imagine I have two distinct OS processes (the actual OS is unimportant). Process A is responsible for playing a video file. Process B is responsible for playing the audio that accompanies the video file. Both processes are clients, connected via a local area network to a server.

Assuming that the video and audio streams are synchronized at the file level, what mechanisms would I use to ensure that both processes coordinate with the server to absolutely ensure that once instructed they begin and continue playing in sync?

This feels like a common problem but I am struggling to find any detailed, practical solutions.

答:
According to EBU Recommendation R37:

“The relative timing of the sound and vision components of a television signal” states that end-to-end audio/video sync should be within +40ms and -60ms (audio before / after video, respectively) and that each stage should be within +5ms and -15ms.

This quote is the summary from the Audio to video synchronization wikipedia page.

This suggests that you need timing accuracy measured in 10's of milliseconds.

Karl Bielefeldt's suggestion of Precision Time Protocol was a good one, but seems like overkill to me. PTP has a sub microsecond accuracy (on a local LAN), so is 3 orders of magnitude (more than 1000 times) more accurate than we need and consequently much more difficult to implement.

The much older and more widely available Network Time Protocol (NTP) should result in clocks being synchronised to within a millisecond on a LAN, which is an order of magnitude (more than 10 times) more accurate than we require. Even if your server and clients were on the Internet, you should be able to get clocks synchronisied to 10's of ms if you don't have problems with asymmetric routes and network congestion.

NTP client/server software is standard on most operating systems, all you need to do is sync both clients to the same server. Note that even if both clients are individually synced to the server with an accuracy of plus/minus 1ms, with respect to each other they are only synchronsed to plus/minus 2ms (one could be 1ms ahead of the server while the other is 1ms behind), but this is still well within the threshold of perception.

Once your system times are synchronised, clients would fill their initial buffer and inform the server of the earliest time they could guarantee starting to serve that content. Once the server had received both times, it would send the worst case time back to both clients and they would both be expected to start at that time.

Finally, since clocks can drift over time, your clients and server would have to keep synchronising clocks, and if the video drifts too far from the audio, you should duplicate or skip frames of video to maintain synchronisation. This should only be needed if you are running very long streams though.

Incidentally, the reason for adjusting the video rather than the audio is that we are far less likely to notice a 1 frame dup/skip in video (assuming 20fps or higher) than even a 1/60th of a second audio glitch.


问:
Is an enterprise-wide data model truly feasible?
I've consulted for a number of Fortune 500 and 100 companies all of whom have made some kind of effort at creating a "Master" data model even to the point that they'd attempt to have all applications work with a shared database (Imagine the change management issues in that world).

I've seen companies throw millions of dollars at these efforts and still come up short of what they envisioned (although there were in many cases some benefits realized from the effort).

My question here is has anyone seen a truly enterprise-wide master data model implemented and consistently used for anything larger than 100 or so tables?

My instinct leans more toward a message driven/SOA model where individual components were responsible for a subset of data and any component that needs access to that data would go through the appropriate channel. But even then, the "ideal" and reality tend to have a significant difference.

答:
My question here is has anyone seen a truly enterprise-wide master data model implemented and consistently used for anything larger than 100 or so tables?

Kind of.

I've seen one implemented that defined the core list of products and configurations for the (~5k employee) company. It was used for sales, maintenance, engineering. The actual implementation was 10+ years old when I encountered it, and it was built from something even older (going back to non-electronic storage, from what I understood). And it consistently served as the source of truth for all product and client data across the company.

Is an enterprise-wide data model truly feasible?

"But".

The reason the thing was 100+ tables is because it grew with the company. It was an unmaintainable, fragile, unweildy mess. It had everything from results of physical tolerance tests to pictures of the products stored right in the DB. They ended up needing export processes anyways to seed smaller databases for specific needs.

So I mean... I wouldn't consider that feasible over the long term.


答:
One hundred database tables is not a whole lot, once you consider ordinary data tables, lookup tables, many-to-many linking tables, OLAP, and so forth.

Is an enterprise-wide data model truly feasible?

It better be.  How else are you going to maintain and extend it?

Rather than think of an enterprise data model as a "big ball of mud," it's more useful to think of it in terms of subsystems or departments.  Every data processing system larger than a single application has multiple applications and multiple data stores that talk to each other through well-defined interfaces. You can readily capture such high-level architecture with a block diagram or data flow diagram, and have database schemas for each data store at the ready when you need to perform systems analysis.

Body:
I've consulted for a number of Fortune 500 and 100 companies all of whom have made some kind of effort at creating a "Master" data model even to the point that they'd attempt to have all applications work with a shared database (Imagine the change management issues in that world).

I've seen companies throw millions of dollars at these efforts and still come up short of what they envisioned (although there were in many cases some benefits realized from the effort).

My question here is has anyone seen a truly enterprise-wide master data model implemented and consistently used for anything larger than 100 or so tables?

My instinct leans more toward a message driven/SOA model where individual components were responsible for a subset of data and any component that needs access to that data would go through the appropriate channel. But even then, the "ideal" and reality tend to have a significant difference.


问:
Is a license header in source files required when applying the Apache Software License 2.0 to a project?
Reading through the Apache Software License 2.0 appendix I am left unclear what exactly I have to do now:

APPENDIX: How to apply the Apache License to your work

To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]" replaced
with your own identifying information. (Don't include the brackets!)
The text should be enclosed in the appropriate comment syntax for the
file format. We also recommend that a file or class name and
description of purpose be included on the same "printed page" as the
copyright notice for easier identification within third-party
archives.

To explain a bit more: I am currently contributing to an open-source project on github, where the decision to license under ASL2.0 was made. In the latest commit, the license text was added as LICENSE to the root directory.

The interesting part is now: What else has to be done to fully license the code under Apache Software License. In specific: What is considered "work" and is it mandatory to include the boilerplate notice to each and every source-file in the project?

I figure it should be possible to add the notice to the already existing README, as I have seen it in other open source projects. Something along the lines of:

License:

Unless explicitly stated otherwise all files in this repository are
licensed under the Apache Software License 2.0 [insert boilerplate notice here]

I think that should be okay, because the Apache Policy on Source Headers (even though intended for Apache Software Foundation owned projects only) states:

Each original source document (code and documentation, but excluding
the LICENSE and NOTICE files) SHOULD include a short license header at
the top. If the distribution contains documents not covered by CLA,
CCLA or Software Grant (such as third-party libraries) then see the
policy guide.

Each source file should include the following license header -- note that there should be no copyright notice in the header:

Specifically the "should" here makes me think, that a license header in every file is not mandatory for each and every source-file of a project licensed under ASL.

答:
No, it is not necessary to include the license in every file. This is a recommended practice, because it ensures that if somebody is viewing one of the files from your project in isolation from the rest they will be able to identify the terms of use for it, but in the end, as long as you do something that makes it clear what the intended license terms are, that is enough, legally speaking.

(Note that this is not legal advice; if this is important you should seek advice of a lawyer in your jurisdiction, etc.)


答:
My instinct leans more toward a message driven/SOA model where individual components were responsible for a subset of data and any component that needs access to that data would go through the appropriate channel.

We actually have something just like this where I work. Our company offers financial services, so the overwhelming majority of data we want to show customers boils down to "for security X, what is the value of field Y?" The security might be Google stock or US Treasury bonds, and the field might be today's price or the 52-week high or the short interest ratio or what have you.

Most of the time requesting a certain field through the company-wide standard interface will result in a call to some service that talks to some database. Each team of backend programmers owns a subset of these fields, along with the services and databases they use to implement them. Any one of those teams can completely change their implementation without affecting the other fields, and the frontend guys like me don't even notice the change. In fact, part of my new hire training was reimplementing a small group of relatively simple fields. I've never counted, but I'm fairly sure we have several hundreds if not thousands of database tables for all the data we support.

But we do have some data that simply doesn't fit this model, and it does get stored and accessed differently. It's probably impossible for a single model of anything to apply to 100% of a company's needs, but you can definitely get close to that ideal.

Title: Is an enterprise-wide data model truly feasible?


问:
Breaking dependencies on remote APIs
The system I'm working on has a core web application where the bulk of the work is done. However, it relies on another server to handle transactional finance data. It connects to the server using a REST API. I'm trying to work only on the core web application but I keep hitting pages and function calls that rely on the REST API.

For getting up and running, I was told that the best option is to connect to the VPN and to point the API client to the shared REST API server.

While that's a reasonable solution for a quick bug fix or QA, I feel that it isn't very good for the application in general. This massive dependency makes it hard to test and develop but I don't know how to break it.

What are my options?

Should I be mocking out all the API client calls? Should I be using mocks and patches only when I'm fixing something? Or should I just suck it up and use the VPN and shared REST API server?

答:
The two approaches I've seen are as follows:

Duplicate the dependency in a Development environment.

This clearly requires more resources, and can be a hassle when it comes to keeping your environments in sync, but it's as representative of Production as you can get.

All you have to change is the endpoint of your REST API dependency.

Create a dependency Mock you can use when debugging

This is an option I've used when it simply wasn't possible to create a Dev environment representative of Production.  It will require writing a mock of your own, but, depending on the complexity of your scenarios, might not actually be much work.

If you like building manual testing tools, this can be a lot of fun.  It also makes demos a bit more interesting!

Not much else to say, really :)

Title: Breaking dependencies on remote APIs


答:
There seems to be too many business rules that rely on the existence of a referee id:  Who is the ref and whethere or not this event is streamed.  For all the streamed/non-refereed events, the field is null. It would be difficult to look at your database and make this determination.

I don't know how much of your data structure you could change, but this holding ID for a TBD referee is going to have to be addressed in other queries as well.

Ideally, there should be some sort of table:

EventReferee

EventID

RefereeID

a lot of other data can be put here that may typically also be null in your Event table: assignment date, etc.

This way, you would have a record in this table to designate those that do not provide a live feed/have a referee, but still may or may not have a referee ID assigned.

A query for who still needs a referee assigned is very simple by checking for null.

A query for events that have a referee will have this record related to the event.
A query for events that a streamed will not have a record in the EventReferee table.

Title: Is it a good idea to have a database row that represents an unknown value within a system

Body:
We have two systems, System A imports a list of sports events from system B, it only wants to import the events we will be providing live data for, the filter used to hide events that we are not providing data for is if the event has a referee assigned to it.

The problem with this is that we don't know who the referee will be for particular events but we know there will be one so someone has created a referee with the name TBC and assigned it to a bunch of events so they will get imported.

Now there is a request to be able to mass assign this TBC referee to multiple events to save our operations staff from having to manually assign the referee for each event one by one.

This to me seems like a very bad idea, I don't like the idea of a referee called TBC in the first place but i can't really explain why, just seems like an anti pattern to me.

Can someone help me out and explain if it is a bad idea or not and why ?


问:
How did people write end-user software in Smalltalk?
There is something I've never understood about Smalltalk, since reading about it in a book when I was a child, tho' I have never used it "in anger". I know that it is turtles-all-the-way-down, that you can break into the program at any time, inspect the state of your objects, even change the code, and resume running. This is obviously a dream come true for a researcher, whether in CS or in industry, an engineer simulating a system, an analyst modelling a market, and so on. I also know that there was no concept of writing source in text files and compiling them into a binary, the editor and the runtime are the same thing. But how do you deliver software to an end user who wouldn't know a debugger if it bit them on the nose, and couldn't care less what an object is? Was there a secret keystroke to turn all those features off and make it behave like "normal" software? Or was Smalltalk software only ever sold to sophisticated users who were programmers too?</p>

答:
Or was Smalltalk software only ever sold to sophisticated users who were programmers too?

No. It's the other way around: Smalltalk was designed so that every user can be a programmer, without needing to be sophisticated. In fact, Smalltalk was designed for children.

The basic idea is that a user would read a manual about the length of a middle-sized undergrad college textbook in order to use sophisticated machinery. Say, you are a carpenter and buy a CNC machine, you wouldn't expect to be able to use it right away, but you also wouldn't expect to need years to learn how to use it. You would probably expect to read about 10000 to 100000 lines of manual and learn about a couple of days to a couple of weeks.

For a software system, the ultimate manual is the source code. So, in order to be usable, the software system should consist of no more than 100000 lines of code, so that the user can read all of them. (And it should be written in such a way and such a language that she can understand it.) That's the goal of Smalltalk: the original Smalltalk system was about 60000 lines of code for everything, the "OS", the hardware drivers, the VM, the compiler, the interpreter, the IDE, the debugger, the editor, an office suite, a distributed document management system, etc. In the 1970s, that was the best they could do, today, 40 years later, we have much better languages available, and the replacement system and language(s) that Alan Kay's team are working on currently, is expected to be less than 20000 lines for the same feature set. (Compare that to e.g. Windows, which has 50 million lines.)

That was the idea. How well that idea worked, well … judge for yourself :-)

Modern Smalltalks try to make a distinction between development and deployment. Basically, you define some application root object, the system traces the connections between all objects in the system, and copies out only those objects which are directly or indirectly connected to the root application object, leaving you with a streamlined image that contains only the application and the libraries and frameworks needed by it.

You typically also don't edit the running system directly, but use some kind of version control system (e.g. Monticello) that stores your modifications as a series of semantic changes to the system and thus can be replayed on a different system. There is also research into module systems and package management systems, and most modern Smalltalks have at least one of the two.

So, the way that Smalltalk systems are deployed today is that there is some minimal "clean" image, and you apply CVS changesets or install packages or link modules on top of that, which yields an image which is specialized just for that application. If you want to do development, you start with a development image which includes the editor, compiler, IDE, etc. and apply those same changes on top of that.

The languages that came after Smalltalk (e.g. Self, Newspeak) often included a textual serialization format for code (Smalltalk itself doesn't have syntax for classes or methods, because they are created programmatically by the IDE (e.g. creating a class is actually just calling the subclass method on some class which will return a class which is a subclass of the class the method was called on); it only has syntax for expressions and statements.), that could be used to "file in" classes and methods into the system, and modern Smalltalks also have that capability.


答: The likely problem is if you adopt IOjs your code (if you are using newer features) will only work there. It will not work on node (v10x)...unless you stick to es5.</p>

Title: How can I ensure my JavaScript code will run in both Node.js and Io.js

Body:
With the danger of fragmentation due to the fork in Node, how can I make sure a "Node" project will run across both Node and its fork?

The hope is that they will join together again once Joyent and the creators of io.js resolve their differences but one cannot hope that this will definitely be the case. So as a node contributor it would make sense to bet on both options and having your codebase require less maintenance if the fork does become a long term one.


问:
How to use scala case classes when delegation is needed
Let's assume in our application we want to model cars. We also want to model a car repository where we store some registered cars. How should that be modeled in scala?

Here comes my approach: First, I create a case class PlainCar. This is just a car how it exists in real world, with nothing special in it. Next I create a CarRepository. I also create a RegisteredCar. The CarRepository can now store PlainCars and return them as RegisteredCars. Both PlainCar and RegisteredCar extend the trait Car which provides all the comon methods like drive. RegisteredCar however is special - it owns an instance of PlainCar but also adds a method registrationNumber which returns the registration number; all other methods are just delegated to the PlainCar instance.

I feel however, that there are some flaws of this design. One is that I have to change RegisteredCar when I add a method/property to PlainCar which I think should not have to be done.

My question is therefore, can this be modeled better and if so, how? Are there other drawbacks that I am missing?

Some advice on naming conventions would also be appreciated because PlainCar sounds quite awkward to me.

答:
It sounds as if registration is a state which only has meaning in the context of a repository.  You have described two states, (registered with the repository, not registered with the repository).  It sounds to me as if what you need is a car container (wrapper if you like).  Think of it as a collection which can hold one car, in the same way that Option[Car] or Either[Car, Motorbike] can only hold one object.

So create a RepositoryItem sealed base trait (or sealed abstract class) and create case class instances (which extend RepositoryItem) for each state.  The Registered variant would have a registration number.  Make your Repository a container of RepositoryItems.  It should not be part of the same set of case classes.

Advantages of this approach include

You can make it generic (RepositoryItem[A] or RepositoryItem[+A] rather than RepositoryItem[Car]).  This means it could become a repository of other things (or could easily expand to hold motorbikes as well as cars).

Complete separation of concerns between repository implementation and car implementation.  One can change (or add new features) without affecting the other.

You can create new subclasses of Car as often as you like.  Even if you create Repository[Car] from the start, rather than making it generic, it will be able to hold Car subclasses with no modification.

Have a look at the way Option and Either are designed.  You might want to implement at least map, so that you can manipulate a car (or replace it with a bike) without having to take it out of the repository slot.

EDIT:

To explain a point which may have created confusion, judging by your comment...

The Option and Either types have a map function (as does List and any other monad).  The map function allows you to pass in a function which can manipulate the object contained.  You get back a transformed object still wrapped in the Option.

```<code>scala> val o = Some(3)
o: Some[Int] = Some(3)

scala> o map (_ * 5)
res2: Option[Int] = Some(15)
</code>```

No dependencies between Option and Int but because Option implements map you can manipulate the Int without removing it from Option wrapping.

Body:
It sounds as if registration is a state which only has meaning in the context of a repository.  You have described two states, (registered with the repository, not registered with the repository).  It sounds to me as if what you need is a car container (wrapper if you like).  Think of it as a collection which can hold one car, in the same way that Option[Car] or Either[Car, Motorbike] can only hold one object.

So create a RepositoryItem sealed base trait (or sealed abstract class) and create case class instances (which extend RepositoryItem) for each state.  The Registered variant would have a registration number.  Make your Repository a container of RepositoryItems.  It should not be part of the same set of case classes.

Advantages of this approach include

You can make it generic (RepositoryItem[A] or RepositoryItem[+A] rather than RepositoryItem[Car]).  This means it could become a repository of other things (or could easily expand to hold motorbikes as well as cars).

Complete separation of concerns between repository implementation and car implementation.  One can change (or add new features) without affecting the other.

You can create new subclasses of Car as often as you like.  Even if you create Repository[Car] from the start, rather than making it generic, it will be able to hold Car subclasses with no modification.

Have a look at the way Option and Either are designed.  You might want to implement at least map, so that you can manipulate a car (or replace it with a bike) without having to take it out of the repository slot.

EDIT:

To explain a point which may have created confusion, judging by your comment...

The Option and Either types have a map function (as does List and any other monad).  The map function allows you to pass in a function which can manipulate the object contained.  You get back a transformed object still wrapped in the Option.

scala> val o = Some(3)
o: Some[Int] = Some(3)

scala> o map (_ * 5)
res2: Option[Int] = Some(15)

No dependencies between Option and Int but because Option implements map you can manipulate the Int without removing it from Option wrapping.


问:
Why is it bad if view engines encourage logic in templates
I once read this, because I wanted to see if handlebars is the right view engine for me or rather something else.

A thing that I wonder since then is the following, why is it considered bad, if a view engine

encourages logic in templates?

答: Business logic doesn't belong in the view. The view should just iterate over your list of objects and output them and provide controls for facilitating change.</p>


问:
Why are good programmers referred to as Ninjas?
How is a Ninja programmer defined? If it is just an experienced developer, then is there really no better way to describe that? Ninja sounds like a childish marketing ploy designed to attract developers with delusions of self-grandeur. Or am I missing something? In particular I want to know what qualities of a Ninja are desired in programmers that makes the comparison valid (besides the coolness factor)?

I did find this article which makes some good comparisons between Ninja characteristics and Agile development. However, I would like to hear from people who have used the word Ninja for hiring purposes and what their motivation was behind it.

Update: There were several good points raised on both sides of the argument. I've tried to summarize these in my blog post. I've chosen JB's answer as the accepted one because it summarizes all the valid reasons for making the comparison.

答:
I'm going to go counter to popular sentiment here. I think there is a lot of romanticizing taking place and over stretching to make the connection between ninjas and engineers. I would keep it simple as ninjas get in, do the job, and get out usually without being detected. The only leap I would make is that in the subculture you can hear jokes about Chuck Norris versus ninjas and obviously every programmer wants to be Chuck Norris or Jack Bauer, but there is only one Chuck Norris and Jack Bauer so we can each be a (anonymous) ninja.

Secondly, ninja is a term used frequently in WoW and can have negative connotations. In addition, the traditional ninja is not honorable in comparison to samurai. So with all the admirable qualities of a samurai, you would think we would see "samurai programmer" more often if it were the case that it's the outward perceived qualities that is being praised. This is why I subscribe to the idea that the use of ninja is more to emphasize the mysterious, cloak and dagger, sneaky skills. To spin it more positively, these are the stock skills in the spy trade; rogues, intelligence, and secret agents inclusive.


问:
Does frequent committing prevent merge conflicts?
Is there any situation, where git merge command uses frequent committing in one or both branches to prevent merge conflict (as opossed to one giant commit of week-long work followed by immidiate merge), or are those things independent?

答: Frequent committing and merge conflicts are independent of each other. By committing often you reduce the probability of a merge conflict, you cannot eliminate it. If two people both clone a repository, change the same line in a file, commit, and push it then it will result in a merge conflict. It does not matter how quick they were.


问:
Dealing with several custom getters
I have a data structure with data units containing different types of data. I've wrapped the data in "Field" objects so that each field is able to independently parse user input in a desired way.

```<code>public abstract class<T> AField {

    protected T value = null;

    public T getValue() {
        return this.value;
    }

    // This is the main reason I'm using a custom Field class
    public abstract void parse(String data) throws ParseException;

}

public class IntegerField extends AField<Integer>{

    public void parse(String data) {
        super.value = data.trim();
    }

}

public class StringField extends AField<String> {

    ...

}

// Note this has the same type as StringField but different parse implementation
public class PhoneNumberField extends AField<String> {

    ....

}

public class DataUnit {

    private AField[] fields;
    private IntegerField number = new IntegerField();
    private StringField name = new StringField();

    public DataUnit() {
        this.fields = new Field {
            this.number,
            this.name
        }
    }

    public void parseAll(String... data) throws ParseException {
        for (int i = 0; i < this.fields.length; i++) {
            fields[i].parse(data[i]);
        }
    }

    // Now the troublesome methods

    public Integer getNumber() {
        return this.number.getValue(),
    }

    public void parseNumber(String data) throws ParseException {
        this.number.parse(data);
    }

    public String getName() {
        ...
    }

    public void parseName(String data) throws ParseException {
        ...
    }

}
</code>```

You can see how the number of methods would quickly go up as I add more types of fields to the DataUnit class or more methods to the AField class. DataUnit has to pass all the methods of all the Field classes forward because I'd rather not expose the Field objects directly to other classes. What's the best way around this method mess? Are there better patterns to achieve this?

答:
Just create helper class with static helper methods.

Example:

```<code>public class DataHelper {

    public static String asString(final Object value) {
        return asString(value, null);
    }

    public static String asString(final Object value, final String defaultValue) {
        if (value instanceof String)
            return (String) value;
        return defaultValue;
    }

    public static Number asNumber(final Object value) {
        return asNumber(value, null);
    }

    public static Number asNumber(final Object value, final Number defaultValue) {
        if (value instanceof Number)
            return (Number) value;

        // If necessary you can parse string values
        if (value instanceof String && ((String) value).matches("^[0-9]\\.?[0-9]*$"))
            return Double.valueOf((String) value);

        return defaultValue;
    }

    public static Integer asInteger(final Object value) {
        return asInteger(value, null);
    }

    public static Integer asInteger(final Object value, final Integer defaultValue) {
        Number rv = asNumber(value);
        if (rv != null)
            return rv.intValue();
        return defaultValue;
    }

    public static Double asDouble(final Object value) {
        return asDouble(value, null);
    }

    public static Double asDouble(final Object value, final Double defaultValue) {
        Number rv = asNumber(value);
        if (rv != null)
            return rv.doubleValue();
        return defaultValue;
    }

    public static String asPhoneNumber(final Object value) {
        return asPhoneNumber(value, null);
    }

    // Here you could return custom object instead of string (if needed)
    public static String asPhoneNumber(final Object value, final String defaultValue) {
        String rv = asString(value);
        if (rv != null) {
            // Do your transformations
            // ...
            return rv;
        }
        return defaultValue;
    }

    public static Boolean asBoolean(final Object value) {
        return asBoolean(value, null);
    }

    public static Boolean asBoolean(final Object value, final Boolean defaultValue) {
        if (value instanceof Boolean)
            return (Boolean) value;

        if (value instanceof Number)
            return ((Number) value).intValue() > 0;

        if (value instanceof String && ((String) value).toLowerCase().matches("true|false|1|0|yes|no"))
            return ((String) value).toLowerCase().matches("true|1|yes");

        return defaultValue;
    }

    // ... etc.
}
</code>```

Usage:

```<code>public class Usage {

    public static void main(String[] args) {

        final Map<String, Object> sampleData = ImmutableMap.of(
                "name", "Sample name",
                "active", "1",
                "age", 37,
                "weight", "75.7"
        );

        final String name = DataHelper.asString(sampleData.get("name"));
        final Boolean active = DataHelper.asBoolean(sampleData.get("active"), false);
        final Integer age = DataHelper.asInteger(sampleData.get("age"), 0);
        final Double weight = DataHelper.asDouble(sampleData.get("weight"));

        // ... etc.

    }

}
</code>```

Title: Dealing with several custom getters

Body:
Just create helper class with static helper methods.

Example:

public class DataHelper {

    public static String asString(final Object value) {
        return asString(value, null);
    }

    public static String asString(final Object value, final String defaultValue) {
        if (value instanceof String)
            return (String) value;
        return defaultValue;
    }

    public static Number asNumber(final Object value) {
        return asNumber(value, null);
    }

    public static Number asNumber(final Object value, final Number defaultValue) {
        if (value instanceof Number)
            return (Number) value;

        // If necessary you can parse string values
        if (value instanceof String && ((String) value).matches("^[0-9]\\.?[0-9]*$"))
            return Double.valueOf((String) value);

        return defaultValue;
    }

    public static Integer asInteger(final Object value) {
        return asInteger(value, null);
    }

    public static Integer asInteger(final Object value, final Integer defaultValue) {
        Number rv = asNumber(value);
        if (rv != null)
            return rv.intValue();
        return defaultValue;
    }

    public static Double asDouble(final Object value) {
        return asDouble(value, null);
    }

    public static Double asDouble(final Object value, final Double defaultValue) {
        Number rv = asNumber(value);
        if (rv != null)
            return rv.doubleValue();
        return defaultValue;
    }

    public static String asPhoneNumber(final Object value) {
        return asPhoneNumber(value, null);
    }

    // Here you could return custom object instead of string (if needed)
    public static String asPhoneNumber(final Object value, final String defaultValue) {
        String rv = asString(value);
        if (rv != null) {
            // Do your transformations
            // ...
            return rv;
        }
        return defaultValue;
    }

    public static Boolean asBoolean(final Object value) {
        return asBoolean(value, null);
    }

    public static Boolean asBoolean(final Object value, final Boolean defaultValue) {
        if (value instanceof Boolean)
            return (Boolean) value;

        if (value instanceof Number)
            return ((Number) value).intValue() > 0;

        if (value instanceof String && ((String) value).toLowerCase().matches("true|false|1|0|yes|no"))
            return ((String) value).toLowerCase().matches("true|1|yes");

        return defaultValue;
    }

    // ... etc.
}

Usage:

public class Usage {

    public static void main(String[] args) {

        final Map<String, Object> sampleData = ImmutableMap.of(
                "name", "Sample name",
                "active", "1",
                "age", 37,
                "weight", "75.7"
        );

        final String name = DataHelper.asString(sampleData.get("name"));
        final Boolean active = DataHelper.asBoolean(sampleData.get("active"), false);
        final Integer age = DataHelper.asInteger(sampleData.get("age"), 0);
        final Double weight = DataHelper.asDouble(sampleData.get("weight"));

        // ... etc.

    }

}


答:
Making several small commits rather than one big one will not magically prevent conflicts, but it usually makes them less frequent and easier to deal with.

If you commit and push lots of small changes to master, then it's harder for conflicts to arise in the first place, since less code is changing between commits and the other developers will see some of your changes before they start to make their own.

If you have a feature branch that's broken up into lots of small commits when you merge, then the merge is done one commit at a time, so if there are a lot of conflicts, you only have to resolve one commit's worth of conflicts at a time, which is usually a lot easier than resolving them all at once.

The git merge command itself does not perform any commits, except for a single "merge commit" if necessary. It will not retroactively split an existing commit into several smaller commits or anything like that (I don't believe there's an easy way to do that in git, or any other VCS).

Title: Does frequent committing prevent merge conflicts?

Body: Is there any situation, where git merge command uses frequent committing in one or both branches to prevent merge conflict (as opossed to one giant commit of week-long work followed by immidiate merge), or are those things independent?


问:
What is the best way to store short-lived data?
I have to save some data about users with their location. This data will only be valid for like 5-10 minutes, then it will never be used again.

So I am having a simple data structure like:

```<code>{
    user_id: 4434993283283,
    major: 5,
    minor: 33
}
</code>```

major and minor are used to track the position of the user. It is possible that the minor value is sometimes not available and therefore null. When I get the data. I want to get a list of users filtered by the major and, if available, the minor value.

So now my question is "What's the best way to store and retrieve this kind of data?"

I have considered using a redis database where I make keys with a expiration time or a postgres database with a timestamp, but I am open to other suggestions.

答:
If it only has a lifetime of 5 to 10 minutes, and there isn't a whole lot of it, then store it in memory.

If those things are not true, any key/value store or relational database will do.


问:
Is there any value in writing a unit test that is a subset of another test?
To give a slightly contrived example, let's say I want to test that a function returns two numbers, and that the first one is smaller than the second one:

```<code>def test_length():
    result = my_function()
    assert len(result) == 2

def test_order()
    a, b = my_function()
    assert a < b
</code>```

Here, if test_length fails, then test_order will fail too. Is it a best practice to write test_length, or to skip it?

EDIT: note that in this situation, both tests are mostly independent from each other, each one can be run in isolation, or they could be run in reverse order, this does not matter. So none of these former questions

How should I test the functionality of a function that uses other functions in it?

Do I need unit test if I already have integration test?

How to structure tests where one test is another test's setup?

How to manage success dependency between unit tests

is a duplicate of the one above.

答:
I'd leave these tests separate if that is how they've evolved to be. Yes test_order is likely to fail whenever test_length does, but you definitely know why.

I'd also agree that if the test_order appeared first and you found a testable failure was that the result was possibly not two values, adding that check as an assert and renaming the test to test_length_and_order makes sense.

If you had to also check the types of the values returned were integers, I'd include that in this "omnibus" results test.

But note now you have a battery of tests for the result of my_function(). If there are multiple contexts (or, more likely, multiple parameters) to test this can now be a subroutine to test all results from my_function().

However, when I write unit tests, I normally test the edge and bad cases separately from good input and normal output (partly because most of my "unit" tests are often mini integration tests), and often with multiple asserts, which are only broken into separate tests if they fail in ways where I find I want more information without debugging.

So I would probably start with your separate tests and expand test_length to test_length_and_types and leave test_order separate, assuming the latter is seen to be "normal processing".


答:
Not a direct answer, just the practice that works best for me:

Have a central repository with a master branch in it.

Clone / pull the central repo's master branch before taking on a new task / ticket / feature.

As you go, do local commits often.

After each commit, or at least periodically, do a git pull --rebase. This will put your current work on top of master's most recent state. Since you do it often, automatic merges will usually suffice. When conflicts arise, they will arise on your branch and will be hopefully small.

When you are done and ready to push your feature, you have zero conflicts, by definition.

I usually don't work on the master branch locally but instead make a separate named branch (or several, try various approaches); this prevents me from an accidental push.

Even better is if you have a code review tool like Gerrit installed, and your master repo can't be directly pushed to (only via code review).


答:
I feel like I'm missing something, but I would just make your CarRepository a Map[RegistrationNumber, PlainCar] or something similar.  Usually with immutable objects, it's much easier to create this kind of association outside the original object.

My second choice would be RegisteredCar extends PlainCar, but I think this creates unnecessary coupling and copies.  Both of those options would allow you to just rename PlainCar to Car.

Title: How to use scala case classes when delegation is needed

Body:
Let's assume in our application we want to model cars. We also want to model a car repository where we store some registered cars. How should that be modeled in scala?

Here comes my approach: First, I create a case class PlainCar. This is just a car how it exists in real world, with nothing special in it. Next I create a CarRepository. I also create a RegisteredCar. The CarRepository can now store PlainCars and return them as RegisteredCars. Both PlainCar and RegisteredCar extend the trait Car which provides all the comon methods like drive. RegisteredCar however is special - it owns an instance of PlainCar but also adds a method registrationNumber which returns the registration number; all other methods are just delegated to the PlainCar instance.

I feel however, that there are some flaws of this design. One is that I have to change RegisteredCar when I add a method/property to PlainCar which I think should not have to be done.

My question is therefore, can this be modeled better and if so, how? Are there other drawbacks that I am missing?

Some advice on naming conventions would also be appreciated because PlainCar sounds quite awkward to me.


问:
Global state of games(or other). Example : Waiting,Betting,Battling in gambling game
So I'm making a IRC betting bot. Basically the game/bot has three states of taking-in chat.

State 1 : Betting
If anyone says "!bet team money" parse it and record.

State 2 : Battling
Take nothing in, no more !bet etc. Just watch.

State 3 : Waiting/Bank
Don't take bets. But take-in "!bank" and print out the users money count.

Right now for each of my bot message parsers I have a big fat IF.

```<code>if (global_state == BETTING):
    blah blah bah
</code>```

AND I'm starting to need to have my bot do stuff when the state changes.  So now I'm starting to do this (which hurts my soul a little every time I read it)

```<code>if (global_state == BETTING && past_state == WAITING):
    do blah stuff like reset the bet money
</code>```

As some of you might have noticed I'm using Python, but this problem definitely is not python-only. What should I do instead?

答:
This looks like a good application of the ideas of "Finite State Machine" and "Polymorphism".

You've already defined your states, so the next step is to define the transitions between states, and the behavior of the system when it's in each state.

There are many ways to implement state machines, but in this case you might benefit from three classes, one for each state. Each should have functions "parse(...)" and "transition(...)". The parse method just reads a line of input and does the right thing. The transition function decides what to do based on the new state that its going to, and returns the new state object.

(That's a very rough cut for the transition function; there are probably better ways to do it.)

Then your state variable, instead of referring to a string, actually refers to the current state object. Then you can use nice syntax like "global_state.parse(...)" and "global_state = global_state.transition(...)"

That's an extremely high-level view, and there are lots of ways to do it, but even if you just do that much, you'll get rid of almost all the big fat ifs in your program, and your heart will feel lighter.