问:
Is depending on lazy loading a code smell?
During my short experience with DDD I often find myself in the situation where I wished for some type of lazy loading mechanism to solve some dangerous cases where large nested data sets might be loaded.

However after a while I realized that each time, that was the symptom of a poorly designed aggregate root that was taking too much responsibility. Additionally it used to be the case where the aggregates should be fully loaded to perform consistency operations. Getting used to work with Entity ids made things slightly easier.

So after a while, I am wondering... is lazy loading a code smell? Is it something just to build non mature models without causing a big problem?

答:
My short answer: yes!

Lazy loading and other fetching strategies indicate that the domain model is being used to perform queries.  This is something that should not be done.  A simple query layer best serves that purpose.  So, in my opinion, you have come to the correct conclusion :)

The domain model should only contain current transactional state.  This means that, typically, there should be no large data sets as these are more common for historical data.  This does not mean that historical data cannot be used to create new transaction aggregates, though.

OwnerDisplayName: Francisco Garcia

OwnerDisplayName: Eben Roux


问:
Questions about God's algorithm and Rubik's cube
I am creating Rubik's cube solver. It will be good if solver could solve cubes of any size and if it could generate short solutions.

I have found many various information about God's algorithm, which as I understand is able to solve various puzzles, not only Rubic's cube.

So I want to implement God's algorithm, but I cannot find any simple explanation of this algorithm.

In simple words, how does God's algorithm actually work?

答:
The algorithm works a lot like the perfect strategy in chess: from the solved state, recursively enumerate all neighbour states. Once you reach a state that equals your current state, the path that you took to find it is the shortest route to the solution.

The trouble with it is that the space and time required to actually construct the complete tree becomes astronomical, far too large to actually expend them. So its only advantage is that we know it exists, and how to perform it if we could afford it.

Obviously, we would like to have something better; a method that will reliably find the shortest path with much less effort. If we could get hold of such an algorithm, it would make the problem much easier, and presumably (particularly if it were elegant) it would then inherit the appellation "God's algorithm", because it would be superior to the naive solution in every respect. The trouble is that not only do we not know such a method, we don't even know whether it exists.

ContentLicense: CC BY-SA 3.0


答:
I don't think it's possible to do better than to quote Wikipedia:God's algorithm:

God's algorithm ... refers to any algorithm which produces a solution having the fewest possible number of moves, the idea being that an omniscient being would know an optimal step from any given configuration.

So it's not "an" algorithm whose working can be described. There are multiple such algorithms, including breadth-first-search and meet-in-the-middle (which performs breadth-first-search from the current position and the solved position and looks for a position reachable by both).

Title: Questions about God's algorithm and Rubik's cube

Body:
I am creating Rubik's cube solver. It will be good if solver could solve cubes of any size and if it could generate short solutions.

I have found many various information about God's algorithm, which as I understand is able to solve various puzzles, not only Rubic's cube.

So I want to implement God's algorithm, but I cannot find any simple explanation of this algorithm.

In simple words, how does God's algorithm actually work?


问:
Is it sufficient to use acceptance and integration tests instead of unit test?
Short introduction to this question. I have used now TDD and lately BDD for over one year now.  I use techniques like mocking to make writing my tests more efficiently. Lately I have started a personal project to write a little money management program for myself. Since I had no legacy code it was the perfect project to start with TDD. Unfortunate I did not experience the joy of TDD so much. It even spoiled my fun so much that I have given up on the project.

What was the problem? Well, I have used the TDD like approach to let the tests / requirements evolve the design of the program. The problem was that over one half of the development time as for writing / refactor tests. So in the end I did not want to implement any more features because I would need to refactor and write to many test.

At work I have a lot of legacy code. Here I write more and more integration and acceptance tests and less unit tests. This does not seem to be a bad approach since bugs are mostly detected by the acceptance and integration tests.

My idea was, that I could in the end write more integration and acceptance tests than unit tests. Like I said for detecting bugs the unit tests are not better than integration / acceptance tests. Unit test are also good for the design. Since I used to write a lot of them my classes are always designed to be good testable. Additionally, the approach to let the tests / requirements guide the design leads in most cases to a better design. The last advantage of unit tests is that they are faster. I have written enough integration tests to know, that they can be nearly as fast as the unit tests.

After I was looking through the web I found out that there are very similar ideas to mine mentioned here and there. What do you think of this idea?

Edit

Responding to the questions one example where the design was good,but I needed a huge refactoring for the next requirement:

At first there were some requirements to execute certain commands. I wrote an extendable command parser - which parsed commands from some kind of command prompt and called the correct one on the model. The result were represented in a view model class:

There was nothing wrong here. All classes were independent from each other and the I could easily add new commands, show new data.

The next requirement was, that every command should have its own view representation - some kind of preview of the result of the command. I redesigned the program to achieve a better design for the new requirement:

This was also good because now every command has its own view model and therefore its own preview.

The thing is, that the command parser was changed to use a token based parsing of the commands and was stripped from its ability to execute the commands. Every command got its own view model and the data view model only knows the current command view model which than knows the data which has to be shown.

All I wanted to know at this point is, if the new design did not break any existing requirement. I did not have to change ANY of my acceptance test. I had to refactor or delete nearly EVERY unit tests, which was a huge pile of work.

What I wanted to show here is a common situation which happened often during the development. There were no problem with the old or the new designs, they just changed naturally with the requirements - how I understood it, this is one advantage of TDD, that the design evolves.

Conclusion

Thanks for all the answers and discussions. In summary of this discussion I have thought of an approach which I will test with my next project.

First of all I write all tests before implementing anything like I always did.

For requirements I write at first some acceptance tests which tests the whole program. Then I write some integration tests for the components where I need to implement the requirement. If there is a component which work closely together with another component to implement this requirement I would also write some integration tests where both components are tested together. Last but not least if I have to write an algorithm or any other class with a high permutation - e.g. a serializer - I would write unit tests for this particular classes. All other classes are not tested but any unit tests.

For bugs the process can be simplified. Normally a bug is caused by one or two components. In this case I would write one integration test for the components which tests the bug. If it related to a algorithm I would only write a unit test. If it is not easy to detect the component where the bug occurs I would write an acceptance test to locate the bug - this should be an exception.

答:
I think it's a horrible idea.

Since acceptance tests and integration test touch broader portions of your code to test a specific target, they're going to need more refactoring over time, not less. Worse yet, since they do cover broad sections of the code, they increase the time you spend tracking down the root cause since you've got a broader area to search from.

No, you should usually write more unit tests unless you have a on odd app that is 90% UI or something else that's awkward to unit test. The pain you're running into isn't from unit tests, but doing test first development. Generally, you should only spend 1/3 of your time at most writing tests. After all, they're there to serve you, not vice versa.


问:
Documenting/defining data structures in Python
What is the preferred way to document the contents of and logic behind  dynamically generated data structures in Python? E.g. a dict which contains the mapping of a string to a list of lists of strings? </p>

<p>I find it hard to transport the meaning and algorithmic workings of the data elements through Python code alone. It is unsatisfying and sometimes counterproductive to try to shape the code which erects such a dict into a form which tells another programmer easily about the structure of a dict entry. Similarly, placing a comment with an example entry is anything but optimal in my eyes. </p>

答:
Names. They should mean something. Argument names shouldn't be d or a, more likely user_id_to_instance_dict or something like that.

Docstrings. Functions and classes can have documentation strings, you can explain types and structure in them

```<code>class UserRegistry:
    """
    Here we tell what does this class do.

    Fields:
    - some_public_field - this field is used to store such and such data

    Private fields:
    - _user_id_to_instance - this is dictionary mapping user ID to User instance.
    """
    <class code>
</code>```

Annotations. Python3 allows us to annotate function arguments and output with arbitrary python expression.

```<code>def count_women(self, id_to_instance_dict: "dict( user id -> User instance)") -> int:

def average_age(self, id_to_instance_dict: dict) -> float:
</code>```

Comments. You can also describe fields with comments:
class UserRegistry:

```<code>some_field = {} # dict(str -> int)

def __init__(self):
    self.another_field = [] # list(tuple(str, str))
</code>```

PS. Can someone help me with formatting?

Body:
Names. They should mean something. Argument names shouldn't be d or a, more likely user_id_to_instance_dict or something like that.

Docstrings. Functions and classes can have documentation strings, you can explain types and structure in them

class UserRegistry:
    """
    Here we tell what does this class do.

    Fields:
    - some_public_field - this field is used to store such and such data

    Private fields:
    - _user_id_to_instance - this is dictionary mapping user ID to User instance.
    """
    <class code>

Annotations. Python3 allows us to annotate function arguments and output with arbitrary python expression.

def count_women(self, id_to_instance_dict: "dict( user id -> User instance)") -> int:

def average_age(self, id_to_instance_dict: dict) -> float:

Comments. You can also describe fields with comments:
class UserRegistry:

some_field = {} # dict(str -> int)

def __init__(self):
    self.another_field = [] # list(tuple(str, str))

PS. Can someone help me with formatting?


问:
Is a 'God' ViewModel desired in WPF
My application has user controls within user controls. Please see a screen shot of one of the most beautiful applications of all time (UC = user control):

All the properties live in the MainWindow code behind, there are none in my UserControls. To bind to my properties I use

```<code>DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1,AncestorType=Window}}"
</code>```

This works fine but, it does mean all binding properties are in my MainWindow code behind (or the MainWindow ViewModel).

Is this desired in a MVVM (or should I say WPF) approach, in that all the children share the same ViewModel?

答:
I think its bad practice to have a God ViewModel, the topmost ViewModel, let's call it MainWindowViewModel, should only hold data and behavior coupled to that of the MainWindow, which usually is very thin, all other work should be delegated to submodels.

If you have a docking manager or other window manager logic that code should reside in the MainWindowViewModel.

Here is a example of a ViewModel I've made that delegates the behavior to sub models

https://github.com/AndersMalmgren/FreePIE/blob/master/FreePIE.GUI/Shells/MainShellViewModel.cs

I do not think it's good practice to pass around data to sub models, it creates dependencies between models. It's better to use a Event aggregation pattern, this way all models interested in data change can subscribe to the event.

Update: I did an improvement to my Main window model, instead of the constructor taking all sub view models it now takes a collection of viewmodels. And then I configure the IoC to inject correct models

```<code>private void ConfigurePanels()
{
    kernel.Bind<PanelViewModel>().To<ConsoleViewModel>();
    kernel.Bind<PanelViewModel>().To<ErrorsViewModel>();
    kernel.Bind<PanelViewModel>().To<WatchesViewModel>();
}
</code>```

This makes the main model a little less coupled to the sub models, before change

```<code>    public MainShellViewModel(ConsoleViewModel consoleViewModel,
                              ErrorsViewModel errorsViewModel,
                              WatchesViewModel watchesViewModel
        )
        : base(resultFactory)
    {
        Tools = new BindableCollection<PanelViewModel> {consoleViewModel, errorsViewModel, watchesViewModel};
    }
</code>```

and after

```<code>    public MainShellViewModel(IEnumerable<PanelViewModel> panels)
        : base(resultFactory)
    {
        Tools = new BindableCollection<PanelViewModel> (panels);
    }
</code>```

https://github.com/AndersMalmgren/FreePIE/commit/1102292d35a26d7693593266042cde9d9f3b4c89

Title: Is a 'God' ViewModel desired in WPF

Body:
I think its bad practice to have a God ViewModel, the topmost ViewModel, let's call it MainWindowViewModel, should only hold data and behavior coupled to that of the MainWindow, which usually is very thin, all other work should be delegated to submodels.

If you have a docking manager or other window manager logic that code should reside in the MainWindowViewModel.

Here is a example of a ViewModel I've made that delegates the behavior to sub models

https://github.com/AndersMalmgren/FreePIE/blob/master/FreePIE.GUI/Shells/MainShellViewModel.cs

I do not think it's good practice to pass around data to sub models, it creates dependencies between models. It's better to use a Event aggregation pattern, this way all models interested in data change can subscribe to the event.

Update: I did an improvement to my Main window model, instead of the constructor taking all sub view models it now takes a collection of viewmodels. And then I configure the IoC to inject correct models

private void ConfigurePanels()
{
    kernel.Bind<PanelViewModel>().To<ConsoleViewModel>();
    kernel.Bind<PanelViewModel>().To<ErrorsViewModel>();
    kernel.Bind<PanelViewModel>().To<WatchesViewModel>();
}

This makes the main model a little less coupled to the sub models, before change

    public MainShellViewModel(ConsoleViewModel consoleViewModel,
                              ErrorsViewModel errorsViewModel,
                              WatchesViewModel watchesViewModel
        )
        : base(resultFactory)
    {
        Tools = new BindableCollection<PanelViewModel> {consoleViewModel, errorsViewModel, watchesViewModel};
    }

and after

    public MainShellViewModel(IEnumerable<PanelViewModel> panels)
        : base(resultFactory)
    {
        Tools = new BindableCollection<PanelViewModel> (panels);
    }

https://github.com/AndersMalmgren/FreePIE/commit/1102292d35a26d7693593266042cde9d9f3b4c89


答:
Yes, of course it is.

Consider this:

a unit test is a small, targeted piece of testing that exercises a small piece of code. You write lots of them to achieve a decent code coverage, so that all (or the majority of the awkward bits) are tested.

an integration test is a large, broad piece of testing that exercises a large surface of your code. You write few of them to achieve a decent code coverage, so that all (or the majority of the awkward bits) are tested.

See the overall difference....

The issue is one of code coverage, if you can achieve a full test of all your code using integration/acceptance testing, then there's not a problem. Your code is tested. That's the goal.

I think you may need to mix them up, as every TDD-based project will require some integration testing just to make sure that all the units actually work well together (I know from experience that a 100% passed unit tested codebase does not necessarily work when you put them all together!)

The problem really comes down to the ease of testing, debugging the failures, and fixing them. Some people find their unit tests are very good at this, they are small and simple and failures are easy to see, but the disadvantage is that you have to reorganise your code to suit the unit test tools, and write very many of them. An integration test is more difficult to write to cover a lot of code, and you will probably have to use techniques like logging to debug any failures (though, I'd say you have to do this anyway, you can't unit test failures when on-site!).

Either way though, you still get tested code, you just need to decide which mechanism suits you better. (I'd go with a bit of a mix, unit test the complex algorithms, and integrate test the rest).

Title: Is it sufficient to use acceptance and integration tests instead of unit test?

Body:
Short introduction to this question. I have used now TDD and lately BDD for over one year now.  I use techniques like mocking to make writing my tests more efficiently. Lately I have started a personal project to write a little money management program for myself. Since I had no legacy code it was the perfect project to start with TDD. Unfortunate I did not experience the joy of TDD so much. It even spoiled my fun so much that I have given up on the project.

What was the problem? Well, I have used the TDD like approach to let the tests / requirements evolve the design of the program. The problem was that over one half of the development time as for writing / refactor tests. So in the end I did not want to implement any more features because I would need to refactor and write to many test.

At work I have a lot of legacy code. Here I write more and more integration and acceptance tests and less unit tests. This does not seem to be a bad approach since bugs are mostly detected by the acceptance and integration tests.

My idea was, that I could in the end write more integration and acceptance tests than unit tests. Like I said for detecting bugs the unit tests are not better than integration / acceptance tests. Unit test are also good for the design. Since I used to write a lot of them my classes are always designed to be good testable. Additionally, the approach to let the tests / requirements guide the design leads in most cases to a better design. The last advantage of unit tests is that they are faster. I have written enough integration tests to know, that they can be nearly as fast as the unit tests.

After I was looking through the web I found out that there are very similar ideas to mine mentioned here and there. What do you think of this idea?

Edit

Responding to the questions one example where the design was good,but I needed a huge refactoring for the next requirement:

At first there were some requirements to execute certain commands. I wrote an extendable command parser - which parsed commands from some kind of command prompt and called the correct one on the model. The result were represented in a view model class:

There was nothing wrong here. All classes were independent from each other and the I could easily add new commands, show new data.

The next requirement was, that every command should have its own view representation - some kind of preview of the result of the command. I redesigned the program to achieve a better design for the new requirement:

This was also good because now every command has its own view model and therefore its own preview.

The thing is, that the command parser was changed to use a token based parsing of the commands and was stripped from its ability to execute the commands. Every command got its own view model and the data view model only knows the current command view model which than knows the data which has to be shown.

All I wanted to know at this point is, if the new design did not break any existing requirement. I did not have to change ANY of my acceptance test. I had to refactor or delete nearly EVERY unit tests, which was a huge pile of work.

What I wanted to show here is a common situation which happened often during the development. There were no problem with the old or the new designs, they just changed naturally with the requirements - how I understood it, this is one advantage of TDD, that the design evolves.

Conclusion

Thanks for all the answers and discussions. In summary of this discussion I have thought of an approach which I will test with my next project.

First of all I write all tests before implementing anything like I always did.

For requirements I write at first some acceptance tests which tests the whole program. Then I write some integration tests for the components where I need to implement the requirement. If there is a component which work closely together with another component to implement this requirement I would also write some integration tests where both components are tested together. Last but not least if I have to write an algorithm or any other class with a high permutation - e.g. a serializer - I would write unit tests for this particular classes. All other classes are not tested but any unit tests.

For bugs the process can be simplified. Normally a bug is caused by one or two components. In this case I would write one integration test for the components which tests the bug. If it related to a algorithm I would only write a unit test. If it is not easy to detect the component where the bug occurs I would write an acceptance test to locate the bug - this should be an exception.


答:
"God's algorithm" is no actual algorithm. It is the theoretical algorithm which solves a given problem in the optimal way. But this algorithm is always specific to a problem.

There are problems which can be solved by an algorithm which was mathematically proven to be ideal, so this algorithm can be called "God's algorithm" for that given problem.

For others problems there are algorithms which are suspected to be "God's algorithm" but there is no proof yet.

There are problems for which algorithms exist, but there is reason to believe that there must be a better algorithm, so God's algorithm for that problem still needs to be found.


问:
How should one debug a PHP web application securely without exposing secrets to competitors?
Recently I made a program. I forget to delete 2 line of codes. That mistake cost me $800 per day every day.

I was programming with PHP. If a visitor uses proxy it redirect somewhere else. Using debugger was impossible because some code contains ioncube. Because the program simply redirect somewhere else no matter what, it's hard to see which part of the code is executed.

So I put a bunch debugging info everywhere. I thought I'll delete them latter anyway.

The most natural way to debug is of course to put debugging info into a file. The problem is I often use proxy. So after I change the program, I often have to download the text file with filezilla. Often the text file does not show what I think it should show. Finally I decided to just display error on the web.

I considered having debugging mode. However, I am afraid I will forget to delete debugging info.

I considered having debugging mode if user do ?debuggingmode=1 for example. However, I was paranoid that somehow my competitor can guess the secret keyword.

I deleted most debugging info. I forget to delete one and that one only show up if users use proxy from the right country. Turns out I do not have proxy from the right country and didn't realize that. After the program works for 24 hours, I uploaded that to my main domain.

My competitor, using proxy, see the debugging code. He copy the idea and that's how I lost $800 per day.

In retrospect, I really have a hard time seeing where I went wrong. I have been super careful. Yet it happened.

How should one debug a PHP web application securely without exposing secrets to competitors?

答:
You should never debug in production.

You should always have a test environment which is identical to the production environment and debug there.

When you need to change code in the test environment (like for adding debugging statements), you should make sure that they don't go into production.

A professional setup usually looks like this:

```<code>Production
   ^
Staging
   ^
Development
</code>```

The "Production", "Staging" and "Development" instances of your application should be as identical as possible so that a bug which occurs in "Production" can be reproduced in "Staging" and "Development", but still be completely separated from each other so that whatever happens in one of the instances doesn't affect the others.

When you need to analyze a problem, you do so in "Development". Mess around with debug statements and experiment all you want. When you found a solution, you apply that fix to the unchanged codebase in "Staging" and verify that the fix works. Then you promote the fix to "Production".

A proper version control and build management system can help you with that.

Body:
You should never debug in production.

You should always have a test environment which is identical to the production environment and debug there.

When you need to change code in the test environment (like for adding debugging statements), you should make sure that they don't go into production.

A professional setup usually looks like this:

Production
   ^
Staging
   ^
Development

The "Production", "Staging" and "Development" instances of your application should be as identical as possible so that a bug which occurs in "Production" can be reproduced in "Staging" and "Development", but still be completely separated from each other so that whatever happens in one of the instances doesn't affect the others.

When you need to analyze a problem, you do so in "Development". Mess around with debug statements and experiment all you want. When you found a solution, you apply that fix to the unchanged codebase in "Staging" and verify that the fix works. Then you promote the fix to "Production".

A proper version control and build management system can help you with that.


问:
Windows Phone 8 development on Windows 7 - is it or will be possible?
I was trying to install Windows Phone 8 SDK on my Windows 7 machine and it hit me with the 'supported only on Windows 8' message. I actually wanted to develop Phone 7.5 apps on Visual Studio 2012, impossible thing with the 7.1 SDK, so I thought 8 SDK will do the job.

As if it was not enough that the 8 SDK was controversial upon release, now that it's generally available, to me it seems like a horrible decision to make it available only for Windows 8, because in my humble opinion, no serious and sane developer will install Windows 8 ever, or at least in the near future, just because of the Metro UI.

So, anyone knows any workarounds for developing Windows Phone 8 on Windows 7, or at least develop for 7.5 but using Visual Studio 2012?

答:
(Your have probably already found a solution for your problem, but i think this might be useful to other that, as me, are setting their environment for the first time.)

Windows Phone 8 SDK includes Visual Studio 2012 Express.

If you install it on a virtual machine, like explained in this Nokia Developer Wiki article, you should be able to continue using your Windows 7 machine and avoid moving to Windows 8, while having a working WP8 Emulator.


问:
Can we live without constructors?
Let's say in some reason all objects are created this way $obj = CLASS::getInstance(). Then we inject dependencies using setters and perform starting initialization using $obj->initInstance(); Are there any real troubles or situations, which can't be solved, if we won't use constructors at all?

P.s. the reason to create object this way, is that we can replace class inside getInstance() according to some rules.

I'm working in PHP, if that matter

答:
I'd say that this severly hinders your design space.

Constructors are a great place to initialize and validate parameters passed in. If you can no longer use them for that, then initialization, state handling (or plain out denying constructor of "broken" objects) becomes a lot harder and partially impossible.

For example, if every Foo object needs a Frobnicator then it might check in its constructor if the Frobnicator is non-null. If you take away the constructor, then it gets harder to check. Do you check at every point where it would be used? In an init() method (effectively externalizing the constructor method)? Never check it and hope for the best?

While you could probably still implement everything (after all, you're still turing complete), some things will be a lot harder to do.

Personally I'd suggest looking into Dependency Injection/Inversion of Control. These techniques also allow switching concrete implementation classes, but they don't prevent writing/using constructors.

Title: Can we live without constructors?


答:
Well, I have used the TDD like approach to let the tests / requirements evolve the design of the program. The problem was that over one half of the development time as for writing / refactor tests

Unit tests work best when the public interface of the components they are used for does not change too often. This means, when the components already are designed well (for example, following the SOLID principles).

So believing a good design just "evolves" from "throwing" a lot of unit tests at a component is a fallacy. TDD is no "teacher" for good design, it can only help a little bit to verify that certain aspects of the design are good (especially testability).

When your requirements change, and you have to change the internals of a component, and this will break 90% of your unit tests, so you have to refactor them very often, then the design most probably was not so good.

So my advice is: think about the design of the components you have created, and how you can make them more following the open/closed principle. The idea of the latter is to make sure the functionality of your components can be extended later without changing them (and thus not breaking the component's API used by your unit tests). Such components can (and should be) covered by unit test tests, and the experience should not be as painful as you have described it.

When you cannot come up with such a design immediately, acceptance and integration tests may be indeed a better start.

EDIT: Sometimes the design of your components can be fine, but the design of your unit tests may cause issues. Simple example: You want to test the method "MyMethod" of the class X and write

```<code>    var x= new X();
    Assert.AreEqual("expected value 1" x.MyMethod("value 1"));
    Assert.AreEqual("expected value 2" x.MyMethod("value 2"));
    // ...
    Assert.AreEqual("expected value 500" x.MyMethod("value 500"));
</code>```

(assume the values have some kind of meaning).

Assume further, that in production code there is just one call to X.MyMethod. Now, for a new requirement, the method "MyMethod" needs an additional parameter (for example, something like context), which cannot be omitted. Without unit tests, one would have to refactor the calling code in just one place. With unit tests, one has to refactor 500 places.

But the cause here is not the unit tests itself, it is just the fact that the same call to "X.MyMethod" is repeated again and again, not strictly following the "Don't Repeat Yourself (DRY) principle. So the solution here is to put the test data and the related expected values in a list and run the calls to "MyMethod" in a loop (or, if the testing tool supports so called "data drive tests", to use that feature). This reduces the number of places to change in the unit tests when the method signature changes to 1 (as opposed to 500).

In your real world case, the situation might be more complex, but I hope you get the idea - when your unit tests use a components API for which you don't know if it may become subject to change, make sure you reduce the number of calls to that API to a minimum.

Body:
Well, I have used the TDD like approach to let the tests / requirements evolve the design of the program. The problem was that over one half of the development time as for writing / refactor tests

Unit tests work best when the public interface of the components they are used for does not change too often. This means, when the components already are designed well (for example, following the SOLID principles).

So believing a good design just "evolves" from "throwing" a lot of unit tests at a component is a fallacy. TDD is no "teacher" for good design, it can only help a little bit to verify that certain aspects of the design are good (especially testability).

When your requirements change, and you have to change the internals of a component, and this will break 90% of your unit tests, so you have to refactor them very often, then the design most probably was not so good.

So my advice is: think about the design of the components you have created, and how you can make them more following the open/closed principle. The idea of the latter is to make sure the functionality of your components can be extended later without changing them (and thus not breaking the component's API used by your unit tests). Such components can (and should be) covered by unit test tests, and the experience should not be as painful as you have described it.

When you cannot come up with such a design immediately, acceptance and integration tests may be indeed a better start.

EDIT: Sometimes the design of your components can be fine, but the design of your unit tests may cause issues. Simple example: You want to test the method "MyMethod" of the class X and write

    var x= new X();
    Assert.AreEqual("expected value 1" x.MyMethod("value 1"));
    Assert.AreEqual("expected value 2" x.MyMethod("value 2"));
    // ...
    Assert.AreEqual("expected value 500" x.MyMethod("value 500"));

(assume the values have some kind of meaning).

Assume further, that in production code there is just one call to X.MyMethod. Now, for a new requirement, the method "MyMethod" needs an additional parameter (for example, something like context), which cannot be omitted. Without unit tests, one would have to refactor the calling code in just one place. With unit tests, one has to refactor 500 places.

But the cause here is not the unit tests itself, it is just the fact that the same call to "X.MyMethod" is repeated again and again, not strictly following the "Don't Repeat Yourself (DRY) principle. So the solution here is to put the test data and the related expected values in a list and run the calls to "MyMethod" in a loop (or, if the testing tool supports so called "data drive tests", to use that feature). This reduces the number of places to change in the unit tests when the method signature changes to 1 (as opposed to 500).

In your real world case, the situation might be more complex, but I hope you get the idea - when your unit tests use a components API for which you don't know if it may become subject to change, make sure you reduce the number of calls to that API to a minimum.


问:
How do you move beyond code examples without a project?
I am currently learning Scala and I find a mental blog of how to proceed to a degree where I can use Scala daily beyond the normal examples. I just do not have a particular project in mind of what I can do.

This is not really Scala specific in mind, just generally how do you get yourself proficient in a language via self learning without doing / having a project in your hand?

答:
I always consider reading other people's code important part of learning how to program both generally and in a specific language. So I would recommend to find an open-source project that uses Scala and does something that might be interesting for you and to try to contribute to it.

Every open-source project has untriaged bugs they will be happy to get help with and some of them will surely be easy enough for you to fix. Doing that you'll learn to understand Scala code written by others (languages with high level of abstraction like Scala tend to be difficult in this regard) and you'll see on real-world, non-contrived, examples how well various features work out in terms of readability and maintainability. You'll also be discussing your changes with the other people on the project and hopefully getting some useful mentoring that way.

When you start your own project, you'll have a period of writing the foundations when you won't have anything working to show and nobody will be using your work and if you won't have much time, you may never see how it fares in practice. By joining an existing project you can skip that phase and you can make a practical difference even if you find yourself with not so much time for it.


答:
Sometimes it can be hard to start a project or contribute to open-source projects when you have little experience.  My suggestion would be to find a framework that uses Scala and start working with that.  I know the Play Framework uses Scala and there are plenty of tutorials and videos out there for that framework.

Just start by building a simple site that does some CRUD operations using the Play Framework.  That will get you a little experience without having to build everything from scratch.

Title: How do you move beyond code examples without a project?

Body:
I am currently learning Scala and I find a mental blog of how to proceed to a degree where I can use Scala daily beyond the normal examples. I just do not have a particular project in mind of what I can do.

This is not really Scala specific in mind, just generally how do you get yourself proficient in a language via self learning without doing / having a project in your hand?


答:
The advantage of using constructors is that they make it easier to ensure that you will never have an invalid object.

A constructor gives you the opportunity to set all member variables of the object to a valid state. When you then ensure that no mutator method can change the object to an invalid state, you will never have an invalid object, which will save you from a lot of bugs.

But when a new object is created in an invalid state and you must call some setters to put it into a valid state in which it can be used, you are risking that a consumer of the class forgets to call these setters or calls them incorrectly and you end up with an invalid object.

A workaround could be to create objects only through a factory-method which checks every object it creates for validity before returning it to the caller.

Title: Can we live without constructors?

Body:
Let's say in some reason all objects are created this way $obj = CLASS::getInstance(). Then we inject dependencies using setters and perform starting initialization using $obj->initInstance(); Are there any real troubles or situations, which can't be solved, if we won't use constructors at all?

P.s. the reason to create object this way, is that we can replace class inside getInstance() according to some rules.

I'm working in PHP, if that matter


问:
Commit projects individually or whole solution?
I am working (alone) on an application that is a music portal where you can search for artists, songs etc ...

The C# solution consists of:

a class library that contains all the stuff to access the web service

the application itself

I've recently started using Git and figured out the benefits it does provide to a project but there's something I couldn't figure out, on Visual Studio there is the option to commit a solution which leads me to the following question :

Should I commit each project individually or the whole solution ?

答:
A Visual Studio solution is a whole entity. The source control providers work on the solution level. The solution is something that you can compile in itself, for a single project it may not be the case. There can be commits when you need to touch multiple projects at once so that the solution compiles after each atomic commit (especially in your case where there is a breaking change between the two layers). So I'd say it should be the one that you commit.

Although, your project (in a human sense, not VS sense) doesn't have to consist of a single solution. It is not uncommon that you develop a library that can be used by anyone, and you want to publish that as one product in itself. And you also develop an application which uses that library, and publish that as a separate product. From the aspect of the application, your library is not part of the solution, it is an external 3rd party library.


答:
Everyone else has already covered the general case:

Formal Validation (/Proven Code): Not feasible for real world programs, though there is a 4000 line OS kernal, that was formally proven, It took many many Russian CS PhD Students many months (please comment if remember the name of this project)

CI Testing << Automated Testing << Testing : make sure you use a coverage tool to check your test cases have 100% coverage.

For your specific case of leaving debug code in production,
I have 2 options, both of which require the source code to be recomplied as part of the deployment to a new (Staging/Final Testing) environment.

Remove it at compile time. Wrap debug code in structures like C# and C #ifdef DEBUG to check the build target, (Either Debug or Release) and to automatically remove them at compile time.

Flag it at Deploy time. Put a comment near code that must not be run in the real enviroment. Eg //TODO: Remove This Before Deployment, Then when it is migrated (deployed) to Staging, before compiling the code, run it through a simple script that checks to make sure there are no Flag comments (eg  //TODO:) left in the source code.

I suggest the former for if it is longterm and you will want it again (Eg verbose logging mode), and the later if it is a quick hack while you were debugging (Eg various printfs scattered through your code)

Body:
Recently I made a program. I forget to delete 2 line of codes. That mistake cost me $800 per day every day.

I was programming with PHP. If a visitor uses proxy it redirect somewhere else. Using debugger was impossible because some code contains ioncube. Because the program simply redirect somewhere else no matter what, it's hard to see which part of the code is executed.

So I put a bunch debugging info everywhere. I thought I'll delete them latter anyway.

The most natural way to debug is of course to put debugging info into a file. The problem is I often use proxy. So after I change the program, I often have to download the text file with filezilla. Often the text file does not show what I think it should show. Finally I decided to just display error on the web.

I considered having debugging mode. However, I am afraid I will forget to delete debugging info.

I considered having debugging mode if user do ?debuggingmode=1 for example. However, I was paranoid that somehow my competitor can guess the secret keyword.

I deleted most debugging info. I forget to delete one and that one only show up if users use proxy from the right country. Turns out I do not have proxy from the right country and didn't realize that. After the program works for 24 hours, I uploaded that to my main domain.

My competitor, using proxy, see the debugging code. He copy the idea and that's how I lost $800 per day.

In retrospect, I really have a hard time seeing where I went wrong. I have been super careful. Yet it happened.

How should one debug a PHP web application securely without exposing secrets to competitors?


答:
2 advantages to constructors:

Constructors allow for the an object's construction steps to be done atomically.

I could avoid a constructor and use setters for everything, but what about mandatory properties as Joachim Sauer suggested?  With a constructor, an object owns its own construction logic so as to ensure that there are no invalid instances of such class.

If creating an instance of Foo requires 3 properties to be set, the constructor could take a reference to all 3, validate them and throw an exception if they are invalid.

Encapsulation

By relying solely on setters, the burden is on the consumer of an object to build it properly.  There could be different combinations of properties that are valid.

For example, every Foo instance needs either an instance of Bar as property bar or an instance of BarFinder as property barFinder.  It can use either one.  You can create a constructor for every valid set of parameters and enforce the conventions that way.

The logic and semantics for the objects live within the object itself.  It's good encapsulation.

Title: Can we live without constructors?


答:
TL;DR: As long as it meets your needs, yes.

I've been doing Acceptance Test Driven Development (ATDD) development for many years now.  It can be very successful.  There are a few things to be aware of.

Unit tests really do help enforce IOC. Without unit tests the onus is on the developers to make sure they meet the requirements of well written code (in so far as unit tests drive well written code)

They can be slower and have false failures if you are actually using resources that are typically mocked.

The test do not pinpoint the specific problem as unit tests would.  You need to do more investigation to fix test failures.

Now the benefits

Much better test coverage, covers integration points.

Ensures the system as a whole meets the acceptance criteria, which is the whole point of software development.

Makes large refactors much easier, faster, and cheaper.

As always it's up to you to do the analysis and figure out if this practice is appropriate for your situation. Unlike many people I don't think there is an idealized right answer. It will depend on your needs and requirements.


答:
Yes, you can live without constructors.

Sure, you may end up with a lot of duplicated boiler plate code.  And if your application is of any scale, you'll likely spend a lot of time trying to locate the source of a problem when that boilerplate code isnt used consistently across the application.

But no, you don't strictly 'need' your own constructors.  Of course, you don't strictly 'need' classes and objects, either.

Now if your goal is to use some sort of factory pattern for object creation, that isnt mutually exclusive to using constructors when initializing your objects.

Title: Can we live without constructors?


答:
Sometimes you do need to debug a live system.  Yes, you should have a development or staging copy.  But there's always going to be differences.  This is especially true if the code is running out in the wild on customer hardware.  Or potentially, many different customer installations.

I've used the &debugging=1 technique in the past.  I suspect most PHP developers have.  That flipped a switch in the code that enabled more verbose debugging in the application.  That info would usually be dumped to a log file - generally the apache log (using error_log()).  But, you can also output it.  Our profiler, for example, would gather up information and then output the various benchmarks at the bottom of the page.  You can also output the debugging information as an HTML comment, or in a hidden element thats viewable only if you view the page source.

If your site has 'users', you can limit debugging to only a particular user.  This way if someone does try to enable debugging, it still wont function unless they are logged in as that user.

Now, you mentioned you were using FileZilla to connect to the server.  A developer really should have SSH access to the server.  That will make debugging much easier for you.  For example, if you were to output your debugging statements to the Apache error log, for example, you could then easily grep that file for your IP address, and see the debugging information generated by your last page request.

Title: How should one debug a PHP web application securely without exposing secrets to competitors?


问:
Can you apply the same lexer rules to all programming languages?
I'm trying to understand the theory behind a lexer with the purpose of building one  (just for my own fun and experience and to compensate for not taking proper CS courses :)).

What I have yet to understand is if lexer theory is the same no matter what language you are analyzing? Is it just about splitting white space then try to figure out what each text represents or is it more than that?

In other words, does the generation of tokens depend on the language being analyzed or is it just about white space? Can you apply the same lexer rules to all programming languages? For example if I have a lexer that tokenizes Java code can I use it for Python or not, since whitespace in Python has other meaning?

For example, I found a nice Python project (Pygments) which seems to provide a working core that allows you to later plugin rules for each of your favorite language (what are the keywords, the comments etc).

答:
Sure you can: split on whitespace and call it a day!

Now, that is technically a universal lexer, in that you can work through any document and create a processed, tokenized result. Which is is really all a lexer has to do...it just isn't a very useful implementation!

A lexer is all about tokenization, and the rules that apply. And you can certainly write a lexer that simply allows you to plug in new rules to modify it's functioning!

Ultimately what you are trying to do is decouple the rules from their implementation, which is a perfectly reasonable sort of thing to do. You might find it works better, if you are working from scratch, to have that idea in mind but first just get it to work with some simple rules. Then, once it works at a basic level, wrap your head around how to pull out the rules themselves and allow them to be defined elsewhere, yet still be loaded into the program and executed.

Just remember: general-use software is always, always harder to make than specialized software. The more general you want it (do you want a lexer that supports natural language processing?), the less assumptions you can make and the more if() and switch statements you are going to have all over the place, and every optimization might break some needed edge-case feature. And it gets more arduous and time-consuming to test with every generality.

Between the lexer and the parser, the lexer is the easier one to do precisely because it is pretty much context free. It doesn't care if you are missing an end parens on an if statement, for instance, because it doesn't matter to it.

But yes, lexer theory itself is ultimately the same, its just the specific language rules that are different. For instance, in English text you can assume "iscrewedup" is supposed to be one word, and when you can't find that word in a dictionary you can assume something is not right - because written English words split on spaces. But not all language is so clean, and indeed programming langauges usually aren't, because if () and if() are equally valid in most languages.

And in Python indentation means something, while most languages don't care, but at a lexer level it just means a series of spaces or tabs gets tokenized as something like "IncreaseIndent" or "DecreaseIndent", and the parser figures out what that means later on. The theory, however, ultimately remains precisely the same.


问:
How to simulate a REST API?
I am working on a new project which will query data from a 3rd party REST API. This is for a real time sports data feed, so the feed only works when a game is actually taking place.

Although the 3rd party provides good documentation (XSD, etc), they have no way to simulate a game happening, and so to test code I have written against this API I would have to wait for an actual game to be happening.

My only recourse is to write code to simulate a game on my own, but it seems like a lot of work. How would you approach this?

答:
Considering that probably the bookmaker provides some sample data (and this can be saved during the integration phase), my advice is to organize those feeds in this way:

List of events

Updates for scheduled events

Odds updates

Results

Probably the provider offers 2 types of updates: Push (POST) and Pull (GET).

At this point you should

Create a simple server that just handles GET requests, so that your programmers can elaborate algorithms.

Create an automation to manage submissions of the same information and can thus stressing your system.

Manage the development and testing

Without going into the details of technology to be used, you get a mini-server, which responds only to 4 URLs (or those necessary depending on what the provider offers), and a mini-push service.

A very good thing to keep in mind when working with the "mini-server", are the handlers of the HTTP protocol. Create a server on port 80 is very simple, and solves the problem. You have to be sure to inject all the information in the responses GET as the provider makes (this will avoid problems when put into production).

Personally I would do a simple Perl server or the same but with Nodejs. With regard to the injection of data, will be sufficient a timer, which invokes an offline browser (CURL, WGET)

Title: How to simulate a REST API?


答:
$obj = CLASS::getInstance(). Then we inject dependencies using setters and perform starting initialization using $obj->initInstance();

I think you're making this more difficult than it needs to be.  We can inject dependencies just fine through the constructor - and if you have a lot of them, just use a dictionary-like structure so you can specify what ones you want to use:

```<code>$obj = new CLASS(array(
    'Frobnicator' => (),
    'Foonicator' => (),
));
</code>```

And within the constructor, you can ensure consistency like so:

```<code>if (!array_key_exists('Frobnicator', $args)) {
    throw new Exception('Frobnicator required');
}
if (!array_key_exists('Foonicator', $args)) {
    $args['Foonicator'] = new DefaultFoonicator();
}
</code>```

$args can then be used to set private members as necessary.

When done entirely within the constructor like so, there will never be an intermediate state where $obj exists but is not initialized, as there would be in the system described in the question.  It's better to avoid such intermediate states, because you can't guarantee the object is always going to be used correctly.

Title: Can we live without constructors?

Body:
$obj = CLASS::getInstance(). Then we inject dependencies using setters and perform starting initialization using $obj->initInstance();

I think you're making this more difficult than it needs to be.  We can inject dependencies just fine through the constructor - and if you have a lot of them, just use a dictionary-like structure so you can specify what ones you want to use:

$obj = new CLASS(array(
    'Frobnicator' => (),
    'Foonicator' => (),
));

And within the constructor, you can ensure consistency like so:

if (!array_key_exists('Frobnicator', $args)) {
    throw new Exception('Frobnicator required');
}
if (!array_key_exists('Foonicator', $args)) {
    $args['Foonicator'] = new DefaultFoonicator();
}

$args can then be used to set private members as necessary.

When done entirely within the constructor like so, there will never be an intermediate state where $obj exists but is not initialized, as there would be in the system described in the question.  It's better to avoid such intermediate states, because you can't guarantee the object is always going to be used correctly.


答:
I simulated REST API by using combination of cucumberjs, phantomjs with setting proxy server to 127.0.0.1 and hooking a node.js process with http-proxy and nock there. CucumberJS is not the important part, you can write test scenario any way, the rest is the key to the simulation. It is able to mock simply by match-request-return-data, but you can as well filter by patterns and hook callback function to produce a reply, so you can simulate to any level of granularity that you need (in extreme ending with a full demo server, but you can do it incrementally).

It works nicely:

Phantomjs request an URI.

Request goes to proxy server on 127.0.0.1:port.

Your node.js process proxies it transparently forward using http-proxy. So any "normal" loading (pages, images) works.

If you choose to intercept some requests (API, mainly) you use nock for it.

In my scenario, I combined it with cucumber js tests in the same process, so it went as:

Test runs.

It sets up nock HTTP mocking for scenario it tests.

It loads a page in phantomjs via Selenium protocol.

The rest is as shown earlier in this paragraph (that is, it is a bit of a cycle, I as test runner instruct phantomjs to load a page, which forward all requests back to me, and I forward them to the net; or intercept them if it is the tested API).

Title: How to simulate a REST API?

Body:
I am working on a new project which will query data from a 3rd party REST API. This is for a real time sports data feed, so the feed only works when a game is actually taking place.

Although the 3rd party provides good documentation (XSD, etc), they have no way to simulate a game happening, and so to test code I have written against this API I would have to wait for an actual game to be happening.

My only recourse is to write code to simulate a game on my own, but it seems like a lot of work. How would you approach this?


答:
Instantiate an object with a type depending on the requirements it is absolutely possible. It could be the object itself, using global variables of the system to return a specific type.

However, have a class in the code that can be "All" is the concept of dynamic type. I personally believe this approach create inconsistency in your code, make the test complexes*, and "the future becomes uncertain" with respect to the flow of the proposed work.

*I am referring to the fact that the tests must consider first the type, second the result you want to achieve. Then you are creating large nested test.

Title: Can we live without constructors?


答:
I was actually thinking about similar things.

The question I asked was "What constructor does, and is it possible to do it differently?" I reached those conclusions:

It ensures some properties are initialized. By accepting them as parameters and setting them. But this could easily be enforced by compiler. By simply annotating the fields or properties as "required" the compiler would check during creation of the instance if everything is properly set. The call to create the instance would probably be same, there just wouldn't be any constructor method.

Ensures the properties are valid. This could be easily achieved by assert condition. Again you would just annotate the properties with correct conditions. Some languages already do this.

Some more complex construction logic. Modern patterns don't recommend to do that in constructor, but propose using specialized factory methods or classes. So the use of constructors in this case is minimal.

So to answer your question: Yes, I believe it is possible. But it would require some big changes in language design.

And I just noticed my answer is pretty OT.

Title: Can we live without constructors?


问:
how complex a constructor should be
I am having a discussion with my co-worker on how much work a constructor can do. I have a class, B that internally requires another object A. Object A is one of a few members that class B needs to do its job.
All of its public methods depends on the internal object A. Information about object A is stored in the DB so I try to validate and get it by looking it up on the DB in the constructor. My co-worker pointed out that the constructor should not do much work other than capture the constructor parameters. Since all of public methods would fail anyway if object A is not found using the inputs to the constructor, I argued that instead of allowing an instance to be created and later fail, it is actually better to throw early in constructor. Not all classes do this but i found that StreamWriter constructor also throws if it has problem opening a file and doesn't delay the validation until the first call to Write.

What others think? I am using C# if that makes any difference.

Reading Is there ever a reason to do all an object's work in a constructor? i wonder fetching object A by going to DB is part of "any other initialization necessary to make the object ready to use" because if user passed in wrong values to the constructor, i wouldn't be able to use any of its public methods.

Constructors should instantiate the fields of an object and do any
  other initialization necessary to make the object ready to use. This
  is generally means constructors are small, but there are scenarios
  where this would be a substantial amount of work.

答:
Your question is composed from two completely separate parts:

Should I throw exception from constructor, or should I have method fail?

This is clearly application of Fail-fast principle. Making constructor fail is much easier to debug compared to having to find why the method is failing. For example, you might get the instance already created from some other part of code and you get errors when calling methods. Is it obvious the object is created wrong? No.

As for the "wrap the call in try/catch" problem. Exceptions are meant to be exceptional. If you know some code will throw an exception, you do not wrap the code in try/catch, but you validate parameters of that code before you execute the code that can throw an exception. Exceptions are only meant as way to ensure the system doesn't get into invalid state. If you know some input parameters can lead to invalid state, you make sure those parameters never happen. This way, you only have to do try/catch in places, where you can logically handle the exception, which is usually on system's boundary.

Can I access "other parts of the system, like DB" from constructor.

I think this goes against principle of least astonishment. Not many people would expect constructor to access a DB. So no, you should not do that.

Title: how complex a constructor should be


答:
Ugh.

A constructor should do as little as possible - the issue being that exception behavior in constructors is awkward. Very few programmers know what the proper behavior is (including inheritence scenarios), and forcing your users to try/catch every single instantiation is... painful at best.

There's two parts to this, in the constructor and using the constructor. It's awkward in the constructor because you can't do much there when an exception occurs. You can't return a different type. You can't return null. You basically can rethrow the exception, return a broken object (bad constuctor), or (best case) replace some internal part with a sane default. Using the constructor is awkward because then your instantiations (and the instantiations of all derived types!) can throw. Then you can't use them in member initializers. You end up using exceptions for logic to see "did my creation succeed?", beyond the readability (and fragility) caused by try/catch everywhere.

If your constructor is doing non-trivial things, or things that can reasonably be expected to fail, consider a static Create method (with a non-public constructor) instead. It's much more usable, easier to debug, and still gets you a fully constructed instance when successful.

Title: how complex a constructor should be

Body:
I am having a discussion with my co-worker on how much work a constructor can do. I have a class, B that internally requires another object A. Object A is one of a few members that class B needs to do its job.
All of its public methods depends on the internal object A. Information about object A is stored in the DB so I try to validate and get it by looking it up on the DB in the constructor. My co-worker pointed out that the constructor should not do much work other than capture the constructor parameters. Since all of public methods would fail anyway if object A is not found using the inputs to the constructor, I argued that instead of allowing an instance to be created and later fail, it is actually better to throw early in constructor. Not all classes do this but i found that StreamWriter constructor also throws if it has problem opening a file and doesn't delay the validation until the first call to Write.

What others think? I am using C# if that makes any difference.

Reading Is there ever a reason to do all an object's work in a constructor? i wonder fetching object A by going to DB is part of "any other initialization necessary to make the object ready to use" because if user passed in wrong values to the constructor, i wouldn't be able to use any of its public methods.

Constructors should instantiate the fields of an object and do any
  other initialization necessary to make the object ready to use. This
  is generally means constructors are small, but there are scenarios
  where this would be a substantial amount of work.


答:
No you can't. Here is a nonsense snippet of Lisp:

```<code>(*foo-bar* 'baz 14)
</code>```

What are the tokens in this snippet? The answer is something like

```<code>LPAREN
SYMBOL  "*foo-bar*"
QUOTE
SYMBOL  "baz"
INTEGER "14"
RPAREN
</code>```

Lisps have very liberal rules what can be inside an identifer: hyphens -, asterisks * and many other characters are allowed. Expressions can be quoted which prevents their evaluation, in many dialects this is done by prepending a ' to that expression.

A lexer needs to be aware of the language that it's parsing. If we would have used a C language lexer on the above code, we would get an error because ' introduces a character literal which also requires a closing ' – none is present here. Our C tokenizer might produce:

```<code>LPAREN
OP_STAR
IDENTIFIER "foo"
OP_MINUS
IDENTIFIER "bar"
OP_STAR
ERROR character literal isn't terminated: expected »'« after »'b«
</code>```

For each language we want to lex, we have to write special rules. Every language is unique, and many languages do have subtle differences. Here, the identifiers are so very different that the token streams have lost any resemblance of each other. However, some languages inherit syntax from each other. For a very simple snippet like foo.bar(baz), a lexer written for C++ and one for Python might produce comparable results.

But why do we actually use Lexers?

Formally, lexers are not needed. We can describe a language without them just fine. Lexers are a performance optimization. Lexers are basically very restricted preprocessors for a parser that can match the input very efficiently (e.g. implemented as a state machine). The lexer then emits tokens, which are larger building blocks (a token is a pairing of a type or ID with a string). It is then the job of the parser to combine these tokens in a hierarchical structure (generally, an abstract syntax tree). This frees the parser from doing character-level operations, which makes it more efficient and easier to maintain (I have written parser without this separation. It works, but is annoying).

And here we have another problem: A lexer is written for a specific parser. The two work in tandem and cannot be recombined willy-nilly with other lexers or parsers. In the above token streams I have called the "(" operator LPAREN. But a different grammar might require a OP_LP symbol instead.

So for a variety of reasons, it's impossible to write one lexer to rule them all.

Each language needs it's own lexer. But we can take shortcuts and use programs that generate specialized lexers for us from some specification. Often, tools like lex are used for this. If performance is not an issue, I use the regular expressions library from the host language to cobble together a simple lexer, e.g. in Perl:

# a primitive Lisp lexer
my %tokens = (
  LPAREN => qr/[(]/,
  RPAREN => qr/[)]/,
  SYMBOL => qr/[^\s()']+/,
  QUOTE  => qr/[']/,
  INTEGER => qr/[1-9][0-9]*/,
);
my $space = qr/\s+/;

my $input = "(*foo-bar* 'baz 14)";
my $pos = 0;
my $length = length $input;

POSITION:
while ($pos < $length) {
  pos($input) = $pos;
  $pos += length $1 and next if $input =~ /\G($space)/gc;

  for my $name (keys %tokens) {
    if ($input =~ /\G($tokens{$name})/gc) {
      print "$name -- $1\n";
      $pos += length $1;
      next POSITION;
    }
  }

  die "No token matched, just before:\n", (substr $input, $pos, 20), "\n";
}
```

<p>Output:</p>

```LPAREN -- (
SYMBOL -- *foo-bar*
QUOTE -- '
SYMBOL -- baz
SYMBOL -- 14
RPAREN -- )
```

<p>But we can easily change the token definitions:</p>

<pre class="lang-perl prettyprint-override"><code># an incomplete C lexer
my %tokens = (
  LPAREN => qr/[(]/,
  RPAREN => qr/[)]/,
  IDENTIFIER => qr/[a-zA-Z_][a-zA-Z0-9_]*/,
  CHARACTER  => qr/['](?:[^'\\]|\\.)[']/,
  INTEGER => qr/[1-9][0-9]*/,
  OP_STAR => qr/[*]/,
  OP_MINUS => qr/[-]/,
);
my $space = qr/\s+/;
</code>```

which changes the output to:

```<code>LPAREN -- (
OP_STAR -- *
IDENTIFIER -- foo
OP_MINUS -- -
IDENTIFIER -- bar
OP_STAR -- *
No token matched, just before:
'baz 14)
</code>```

We didn't write a new lexer, we just updated the token definitions.

What to do now:

As a preparation, understand and implement the Shunting-Yard Algorithm. This will teach you about a simple stack machine.

Read up on grammars and languages in computer science. Learn what a rule is.

Read up on Extended Backus-Naur Form notation, even if you don't immediately understand it. This is a way to write down grammars, and grammars are a way to describe languages (e.g. programming languages).

Understand the implications of the Chomsky Hierarchy. Here are the three important levels:

Regular Languages can be matched very efficiently. Lexers usually operate on this level.

Context-Free Languages are the basis for the description of many programming languages. Various parsing strategies can match various subsets. You will want to read up on LL, LR, and PEG at least.

Context-Sensitive Languages are even more general, but they are vastly more difficult to parse. Note that many regex libraries like PCRE have context-sensitive features.

Note that real programming languages are not context-free – semantic whitespace as in Python, here-docs as in Bash, and optional end tags in HTML are there to mess up most elegant descriptions (but tricks exist to fake a context-free grammar even then).

Write a simple recursive-descent parser yourself that can evaluate simple arithmetics like 1 + 2 * 3 and manages operator precedence correctly. Using a lexer is not necessary for this. Add parens to your language, then some functions like abs or sin. Post your solution on codereview to get tips on how to do it better.

Now that you've learned how to parse stuff yourself, you may enjoy helping tools like parser generators. As an exercise, pick a simple language like JSON and write a parser for it with your tool of choice. Return to codereview for criticism.

If you have any problems on the way, ask here on programmers or over on stackoverflow, depending on whether the question is conceptual or implementation-related.

Body:
I'm trying to understand the theory behind a lexer with the purpose of building one  (just for my own fun and experience and to compensate for not taking proper CS courses :)).

What I have yet to understand is if lexer theory is the same no matter what language you are analyzing? Is it just about splitting white space then try to figure out what each text represents or is it more than that?

In other words, does the generation of tokens depend on the language being analyzed or is it just about white space? Can you apply the same lexer rules to all programming languages? For example if I have a lexer that tokenizes Java code can I use it for Python or not, since whitespace in Python has other meaning?

For example, I found a nice Python project (Pygments) which seems to provide a working core that allows you to later plugin rules for each of your favorite language (what are the keywords, the comments etc).

Body:
No you can't. Here is a nonsense snippet of Lisp:

(*foo-bar* 'baz 14)

What are the tokens in this snippet? The answer is something like

LPAREN
SYMBOL  "*foo-bar*"
QUOTE
SYMBOL  "baz"
INTEGER "14"
RPAREN

Lisps have very liberal rules what can be inside an identifer: hyphens -, asterisks * and many other characters are allowed. Expressions can be quoted which prevents their evaluation, in many dialects this is done by prepending a ' to that expression.

A lexer needs to be aware of the language that it's parsing. If we would have used a C language lexer on the above code, we would get an error because ' introduces a character literal which also requires a closing ' – none is present here. Our C tokenizer might produce:

LPAREN
OP_STAR
IDENTIFIER "foo"
OP_MINUS
IDENTIFIER "bar"
OP_STAR
ERROR character literal isn't terminated: expected »'« after »'b«

For each language we want to lex, we have to write special rules. Every language is unique, and many languages do have subtle differences. Here, the identifiers are so very different that the token streams have lost any resemblance of each other. However, some languages inherit syntax from each other. For a very simple snippet like foo.bar(baz), a lexer written for C++ and one for Python might produce comparable results.

But why do we actually use Lexers?

Formally, lexers are not needed. We can describe a language without them just fine. Lexers are a performance optimization. Lexers are basically very restricted preprocessors for a parser that can match the input very efficiently (e.g. implemented as a state machine). The lexer then emits tokens, which are larger building blocks (a token is a pairing of a type or ID with a string). It is then the job of the parser to combine these tokens in a hierarchical structure (generally, an abstract syntax tree). This frees the parser from doing character-level operations, which makes it more efficient and easier to maintain (I have written parser without this separation. It works, but is annoying).

And here we have another problem: A lexer is written for a specific parser. The two work in tandem and cannot be recombined willy-nilly with other lexers or parsers. In the above token streams I have called the "(" operator LPAREN. But a different grammar might require a OP_LP symbol instead.

So for a variety of reasons, it's impossible to write one lexer to rule them all.

Each language needs it's own lexer. But we can take shortcuts and use programs that generate specialized lexers for us from some specification. Often, tools like lex are used for this. If performance is not an issue, I use the regular expressions library from the host language to cobble together a simple lexer, e.g. in Perl:

# a primitive Lisp lexer
my %tokens = (
  LPAREN => qr/[(]/,
  RPAREN => qr/[)]/,
  SYMBOL => qr/[^\s()']+/,
  QUOTE  => qr/[']/,
  INTEGER => qr/[1-9][0-9]*/,
);
my $space = qr/\s+/;

my $input = "(*foo-bar* 'baz 14)";
my $pos = 0;
my $length = length $input;

POSITION:
while ($pos < $length) {
  pos($input) = $pos;
  $pos += length $1 and next if $input =~ /\G($space)/gc;

  for my $name (keys %tokens) {
    if ($input =~ /\G($tokens{$name})/gc) {
      print "$name -- $1\n";
      $pos += length $1;
      next POSITION;
    }
  }

  die "No token matched, just before:\n", (substr $input, $pos, 20), "\n";
}

Output:

LPAREN -- (
SYMBOL -- *foo-bar*
QUOTE -- '
SYMBOL -- baz
SYMBOL -- 14
RPAREN -- )

But we can easily change the token definitions:

# an incomplete C lexer
my %tokens = (
  LPAREN => qr/[(]/,
  RPAREN => qr/[)]/,
  IDENTIFIER => qr/[a-zA-Z_][a-zA-Z0-9_]*/,
  CHARACTER  => qr/['](?:[^'\\]|\\.)[']/,
  INTEGER => qr/[1-9][0-9]*/,
  OP_STAR => qr/[*]/,
  OP_MINUS => qr/[-]/,
);
my $space = qr/\s+/;

which changes the output to:

LPAREN -- (
OP_STAR -- *
IDENTIFIER -- foo
OP_MINUS -- -
IDENTIFIER -- bar
OP_STAR -- *
No token matched, just before:
'baz 14)

We didn't write a new lexer, we just updated the token definitions.

What to do now:

As a preparation, understand and implement the Shunting-Yard Algorithm. This will teach you about a simple stack machine.

Read up on grammars and languages in computer science. Learn what a rule is.

Read up on Extended Backus-Naur Form notation, even if you don't immediately understand it. This is a way to write down grammars, and grammars are a way to describe languages (e.g. programming languages).

Understand the implications of the Chomsky Hierarchy. Here are the three important levels:

Regular Languages can be matched very efficiently. Lexers usually operate on this level.

Context-Free Languages are the basis for the description of many programming languages. Various parsing strategies can match various subsets. You will want to read up on LL, LR, and PEG at least.

Context-Sensitive Languages are even more general, but they are vastly more difficult to parse. Note that many regex libraries like PCRE have context-sensitive features.

Note that real programming languages are not context-free – semantic whitespace as in Python, here-docs as in Bash, and optional end tags in HTML are there to mess up most elegant descriptions (but tricks exist to fake a context-free grammar even then).

Write a simple recursive-descent parser yourself that can evaluate simple arithmetics like 1 + 2 * 3 and manages operator precedence correctly. Using a lexer is not necessary for this. Add parens to your language, then some functions like abs or sin. Post your solution on codereview to get tips on how to do it better.

Now that you've learned how to parse stuff yourself, you may enjoy helping tools like parser generators. As an exercise, pick a simple language like JSON and write a parser for it with your tool of choice. Return to codereview for criticism.

If you have any problems on the way, ask here on programmers or over on stackoverflow, depending on whether the question is conceptual or implementation-related.


问:
Visualizing a complex software application

Question

What is a good way to go about visualizing a complex software application?

Are recommended software applications that can be used for this purpose?

Background

About 3 years ago, I started building a web data mining application. Started out as just me, but has since grown into a project with 5 developers.

I used to be able to keep track of all the parts of the application in my mind, but now it has grown in complexity such that I'm feeling the need for some sort of visual documentation of the application's structure.

I'm not really sure where to go from here. I'm thinking something that looks kind of like a flow chart. But I don't have any background, experience, or formal training in software development on this scale. I have also never served on another team where I could observe someone else architecting a complex application or managing a team. Any pointers in the right direction such as books or resources on the subject would be much appreciated!

答:
UML is probably the better-standardized and commonly used tool for this.  Some of the diagrams and documents that can be generated in UML can be exceedingly large or complex when used to document bigger systems; however, some of them could be useful if you wish to reach a value/effort balance (i.e. document enough so that you have a good reference point without crossing the line of the documentation becoming more hindrance than help).

I really like the concept of the 4+1 Architectural View Model, which breaks down an architecture into different "views" or perspectives.

Especially for internal documentation purposes, you can determine a granularity and level of detail for the views on which you want to focus and for how specifically you want to document a certain part of your system.  I'll try to elaborate more on the different considerations I believe should be kept in mind.

Documentation for different levels

In my opinion, the best approach tends to be to use higher-level documentation for the whole system, and drilling down with more detailed and specific documents when needed.

You might want to look at System Architecture (or Communication) diagrams for a high-level overview of the components (and using good labelling, this can actually become really useful).

Also, to look at static structure of the project, Package diagrams are useful (they tell you how your code is laid out).  These diagrams, I think, will help you find interactions easily, while reducing the amount of clutter if you have large systems.

Getting more specific, you might want to generate Activity Diagrams (which are really a lot like flow charts), to specify the different processes in your system.  I would recommend doing this only for specific processes in which you need to have a very clear understanding of what is going on.  Also, ideally, the processes should not change much after they have been designed - so you can avoid the documentation synchronicity problem.

Finally, for complex designs, you could look at Class and/or Component Diagrams or a variation of them, where you can really map out the interaction between different pieces of code.  Again, unless you have some form of automated generation of the diagram, it tends to be time-consuming to synchronize the code and the documentation, in my opinion.

Think about what you need

This does not mean "don't do it because it means more work" it means "don't be stupid and do it when you don't need it; it could be painful later on".  Wasting time creating documentation that you will not maintain and whose benefits you won't really harness is not what you want.

Sometimes, what helps most is to draw (I do it on paper, on the desk right next to my computer) simple diagrams that specify how things "communicate".  Just creating containers and seeing communication logic can be useful - and this is, in essence what Communication Diagrams do.  I would advise to KISS (Keep It Stupid Simple), and focus only on the essential parts when you deem it necessary.


问:
What are the advantages of dynamically binding a method to class instance?
I came across Instagram's API client written in Python.

In their class InstagramAPI, they bind the methods to a function in bind.py. When called, the function returns an instance of the class InstagramAPIMethod and execute the request call.

What are the advantages of doing it this way? (over directly creating instances of InstagramAPIMethod in InstagramAPI)?

What will happen if the methods in InstagramAPI are called numerous times? Will it create new a instance every call?

Note, the only advantages I thought of are (probably I'm off track):

The class doesn't/shouldn't care what the implementing class is.

If a particular method is not called, we will never create an instance.

答:
One of the tags on this question gives you an idea of what the answer may be. This is a common design pattern, particularly for services, and very common for web services.

Basically, they're hiding the instantiation of the InstagramAPIMethod and keeping it all in one spot. This allows for flexibility internally so they can change how things work under the hood while ensuring bind_method keeps working the same way.

In addition, this makes it easy to change and update to new URLs, new methods, and so on. This is why it gets used so widely with web services - the cost of updates and changes is very minimal.


问:
Continuous Delivery: Kanban, SCRUM, or other?
I was wondering if there was an SDLC (software development lifecycle) or methodology (Kanban, SCRUM, waterfall, otherwise, etc.) that was particularly well-suited for continuous delivery systems, and why?

I'm sure each methodology has pros/cons that make it suited for certain components of CD, but there must be one that incorporates principles/values that make it better geared for CD...

答:
Frankly, I think you should look at them all. Scrum because it heavily emphasizes iterative and incremental development. XP because it gives a lot of advice on the technical side of development. Kanban because it emphasizes WIP limits and flow.

That's how I've come to know them anyway; I've noticed they've all influenced each other heavily over the years. In either case, no methodology has all the answers.

For me, a very important core idea for everything "continuous" (both continuous delivery and continuous deployment) is making things as small as possible: make the stories smaller, so they're finished sooner, which makes you focus on iterative, emergent development with quick feedback. But also make the components in your application itself smaller and more decoupled.

I.e. if you focus on small services that communicate with each other through some form of messaging, the services become easier to understand, easier to test, and there will be less chance of your changes inadvertently rippling through to other parts of your code.

For a more elaborate albeit more "extreme" explanation on the latter, here are 2 very interesting videos: https://vimeo.com/79866979, https://vimeo.com/74452550

ContentLicense: CC BY-SA 4.0


问:
Coding convention question about AS3 duplicate variable definition
AS3's got some awkward rules about variable scope, due to its use of hoisting.  I don't like pointlessly leaving a bunch of compiler warnings lying around, but it's more important to me for my code to readable and properly written, regardless.  This produces a couple of duplicate variable definition warnings:

```<code>    private function arrangeElementsLine(pElementSize:Dimensions):void
    {
        if (m_eOrientation == HORIZONTAL)
        {
            for (var i:uint = 0; i < target.numElements; i++)
            {
                var layoutElement:ILayoutElement = target.getElementAt(i);
                layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);
                layoutElement.setLayoutBoundsPosition(pElementSize.x * i, 0);
            }
        }
        else
        {
            for (var i:uint = 0; i < target.numElements; i++)
            {
                var layoutElement:ILayoutElement = target.getElementAt(i);
                layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);
                layoutElement.setLayoutBoundsPosition(0, pElementSize.y * i);
            }
        }
    }
</code>```

Is it generally considered to be better and more conventional to remove the redundant var and :<type> syntax for i and layoutElement in the second for loop, or is it more proper to just leave them in there (due to the way their usage is isolated to those two for loops)?  Thanks!

EDIT

This was asked a while back, but when I asked this, part of what I was working on was making something run more efficiently; so I put if outside of any for statements and avoided method calls inside the for statements.

答:
Personally, I prefer reuse the sames variables when they are exactly the same. As the content is the same and the different loop don't stuck each other by overriding the variables, reusing the variables will resolve your problem of warning without making the code less readable, and, in case of pure optimization, it will take less memory (even if 4 bytes is nothing, it's 4 bytes lighter anyway).
So, personally, I prefer using a function like that:</p>

```<code>private function arrangeElementsLine(pElementSize:Dimensions):void
{
    var i:uint;
    var layoutElement:ILayoutElement;

    if (m_eOrientation == HORIZONTAL)
    {
        for (i = 0; i < target.numElements; i++)
        {
            layoutElement = target.getElementAt(i);
            layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);
            layoutElement.setLayoutBoundsPosition(pElementSize.x * i, 0);
        }
    }
    else
    {
        for (i = 0; i < target.numElements; i++)
        {
            layoutElement = target.getElementAt(i);
            layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);
            layoutElement.setLayoutBoundsPosition(0, pElementSize.y * i);
        }
    }
}
</code>```

Body:
Personally, I prefer reuse the sames variables when they are exactly the same. As the content is the same and the different loop don't stuck each other by overriding the variables, reusing the variables will resolve your problem of warning without making the code less readable, and, in case of pure optimization, it will take less memory (even if 4 bytes is nothing, it's 4 bytes lighter anyway).
So, personally, I prefer using a function like that:

private function arrangeElementsLine(pElementSize:Dimensions):void
{
    var i:uint;
    var layoutElement:ILayoutElement;

    if (m_eOrientation == HORIZONTAL)
    {
        for (i = 0; i < target.numElements; i++)
        {
            layoutElement = target.getElementAt(i);
            layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);
            layoutElement.setLayoutBoundsPosition(pElementSize.x * i, 0);
        }
    }
    else
    {
        for (i = 0; i < target.numElements; i++)
        {
            layoutElement = target.getElementAt(i);
            layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);
            layoutElement.setLayoutBoundsPosition(0, pElementSize.y * i);
        }
    }
}


问:
Dynamic initialization, how does it work?
I  have a question regarding dynamic initialization.

Example code

```<code>void main()
{
int a = 100;
//Statement1
//Statement2
...
float b = 6.32987; //StatementA
...
return;
}
</code>```

The StatementA allocates memory at the middle execution of program. How does process takes place and where does space gets allocated for variable b (stack  or heap)?

答:
You tagged this as C, but in another comment mention C++ and Java.  I'll try to cover all of them.

C:

From the latest online C standard:

6.2.4 Storage durations of objects

...

5 An object whose identiﬁer is declared with no linkage and without the storage-class
speciﬁer static has automatic storage duration, as do some compound literals. The
result of attempting to indirectly access an object with automatic storage duration from a
thread other than the one with which the object is associated is implementation-deﬁned.

6 For such an object that does not have a variable length array type, its lifetime extends
from entry into the block with which it is associated until execution of that block ends in
any way. (Entering an enclosed block or calling a function suspends, but does not end,
execution of the current block.) If the block is entered recursively, a new instance of the
object is created each time. The initial value of the object is indeterminate. If an
initialization is speciﬁed for the object, it is performed each time the declaration or
compound literal is reached in the execution of the block; otherwise, the value becomes
indeterminate each time the declaration is reached.

Neither a nor b are declared static, nor are they declared with any explicit linkage, so they have auto storage duration; they only exist for the lifetime of their enclosing scope (logically speaking).  In practice, the storage for both a and b will (usually) come from the runtime stack, which will (usually) be set aside at function entry and (usually) released at function exit.  However, that's an implementation detail; as long as the behavior conforms to the standard, the exact nature of the storage (stack, heap, or otherwise) doesn't really matter.

As far as storage is concerned, it doesn't matter when b is declared within the function; after the source code has been translated to machine code, storage will be set aside at function entry.

C++:

From the online C++ standard:

3.7.2 Automatic storage duration [basic.stc.auto]

1 Local objects explicitly declared auto or register or not explicitly declared static or extern have automatic storage
duration. The storage for these objects lasts until the block in which they are created exits.

2 [Note: these objects are initialized and destroyed as described in 6.7. — end note ]

3 If a named automatic object has initialization or a destructor with side effects, it shall not be destroyed before the end
of its block, nor shall it be eliminated as an optimization even if it appears to be unused, except that a class object or its
copy may be eliminated as speciﬁed in 12.8.

For primitive types, the behavior is almost identical to C; storage is (usually) allocated from the runtime stack at function entry, and (usually) released at function exit.  For instances of class types, it gets a little more complicated.

Java:

From Section 2.6 of the Java Virtual Machine Specification:

2.6. Frames

...

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes, whether that completion is normal or abrupt (it throws an uncaught exception). Frames are allocated from the Java Virtual Machine stack (§2.5.2) of the thread creating the frame. Each frame has its own array of local variables (§2.6.1), its own operand stack (§2.6.2), and a reference to the run-time constant pool (§2.5.5) of the class of the current method.

...

2.6.1. Local Variables

Each frame (§2.6) contains an array of variables known as its local variables. The length of the local variable array of a frame is determined at compile-time and supplied in the binary representation of a class or interface along with the code for the method associated with the frame (§4.7.3).

...

In all three cases, the behavior will be the same (allowing for differences in how main is defined; the posted snippet isn't 100% correct for any of C, C++, or Java).


问:
How to conceptually consider and implement user interface rules for numerous controls and data inputs?
I have a user interface with numerous controls and data inputs on it. Buttons, text fields, and checkboxes, etc. Imagine the following "rules" exist for a sample UI with 2 of those controls:

B2 cannot be used until TF1 and TF2 both have values

TF2 cannot be entered until TF1 has a value

CB2 cannot be checked unless TF1 has a value

CB2 cannot be checked unless CB1 is checked

These rules are arbitrary here, but I have a variety of business rules which will ultimately govern the UI functionality.

I would like to implement logic for this in my UI code to enforce these rules. However, I am having a hard time determining a good way to do so. I can think of two primary ways but I'm not really a fan of either.

Method 1 - adding logic to each control callback

One way to do this would be to add the logical check(s) to each method callback. So for the first rule, in the code associated with B2, include hard coded checks like if TF1 == "" and if TF2 == "". I am not a fan of this idea because I'm going to scatter any sequencing/logic everywhere in my UI and it seems inevitable sometime this process will result in obscure and impossible to track down bugs. Also seems like maintenance will be impossibly complex.

Method 2 - build collection of all rules

The way I'm leaning towards is building a collection of rules. The first step would be defining a set of rules for "passing" for each type of control and its associated lookups, such as:

For checkboxes, "passes" check for true, "fails" if false

For textboxes, "passes" if not empty, "fails" if = ""

I can then create a collection of all the prerequisite pass/fail checks for each UI component and its associated components. This can be abstracted into a single check method called in each UI action like:

myChecker(mControlName)

where myChecker is a method which iterates through the list of all matching rules, checks them, and returns true/false based on whether the rules pass. This method could be called from each UI control before any control-specific logic takes place.

This is nice, but it seems creating the rules and not forgetting any might be even more complex than the first method. Additionally, all control types have to have a "pass/fail" criteria or the myChecker method might become ridiculously complex with lots of hard to read if statements.

Am I missing something? There has to be a more clearly defined pattern or some better strategy for incorporating these sorts of validation/rules into a UI.

答:
If there are only few rules, they are only on one screen and don't change much, then I would go with first method.

If there are many rules, across many screens and can change over time, then the added complexity of second method will return back in better maintainability and thus faster development.