答:
The usual approach is to allow the compiler to track whether or not a function is pure through the entire call graph, and reject code that declares functions as pure that do impure things (where "calling an impure function" is also an impure thing).

Haskell does this by making everything pure in the language itself; anything impure runs in the runtime, not the language itself. The language merely constructs IO actions using pure functions. The runtime then finds the pure function called main from the designated Main module, evaluates it, and executes the resulting (impure) action.

Other languages are more pragmatic about it; a common approach is to add syntax for marking functions 'pure', and forbidding any impure actions (variable updates, calling impure functions, I/O constructs) inside such functions.

In your example, currentDateTime is an impure function (or something that behaves like one), so calling it inside a pure block is forbidden and would cause a compiler error. In Haskell, your function would look something like this:

```<code>f :: Int -> Int -> IO Int
f a b = do
    ct <- getCurrentTime
    return (a + b + timeSeconds ct)
</code>```

If you tried to do this in a non-IO function, like this:

```<code>f :: Int -> Int -> Int
f a b =
    let ct = getCurrentTime
    in a + b + timeSeconds ct
</code>```

...then the compiler would tell you that your types don't check out - getCurrentTime is of type IO Time, not Time, but timeSeconds expects Time. In other words, Haskell leverages its type system to model (and enforce) purity.

Title: How is referential transparency enforced?

Body:
The usual approach is to allow the compiler to track whether or not a function is pure through the entire call graph, and reject code that declares functions as pure that do impure things (where "calling an impure function" is also an impure thing).

Haskell does this by making everything pure in the language itself; anything impure runs in the runtime, not the language itself. The language merely constructs IO actions using pure functions. The runtime then finds the pure function called main from the designated Main module, evaluates it, and executes the resulting (impure) action.

Other languages are more pragmatic about it; a common approach is to add syntax for marking functions 'pure', and forbidding any impure actions (variable updates, calling impure functions, I/O constructs) inside such functions.

In your example, currentDateTime is an impure function (or something that behaves like one), so calling it inside a pure block is forbidden and would cause a compiler error. In Haskell, your function would look something like this:

f :: Int -> Int -> IO Int
f a b = do
    ct <- getCurrentTime
    return (a + b + timeSeconds ct)

If you tried to do this in a non-IO function, like this:

f :: Int -> Int -> Int
f a b =
    let ct = getCurrentTime
    in a + b + timeSeconds ct

...then the compiler would tell you that your types don't check out - getCurrentTime is of type IO Time, not Time, but timeSeconds expects Time. In other words, Haskell leverages its type system to model (and enforce) purity.


问:
Implementing non-fixed length array support in a compiler
I'm thinking of building a language for PIC microcontrollers. I want to be able to use non-fixed size arrays, like this:

Declare the variable as int[]

Wait for input from serial connection

Make the variable input long

I think such a feature would be useful, but don't know how I should go about implementing this in a compiler which compiles to assembly. I want the arrays to be stored on consecutive register addresses, of course. Since I'm working with PICs, this has to be very memory efficient.

When someone writes int[], I don't think it's a good idea to reserve memory space for the variable yet, is it? Then the array would have a fixed maximum size. For example, when the array gets reserved memory address 5-100, and other variables get 4 and 101, the array has fixed borders and can't grow any bigger than 96 registers. Also, when I'd reserve memory from the start, let's say x bytes, and I in the end only need y bytes, I'm wasting x - y bytes. I don't want that.

That means the only option I see is initializing the array and reserving space in the microcontroller, on the fly. This will take up some memory and execution time, of course. I thought of a system like this:

Initialize an array int[x] = {int, int} which holds pointers to the start and end of arrays that are not initialized from the beginning - x would be the maximum amount of arrays (this is a concession, but is better than a maximum length for all arrays)

Store a variable c = 0 to indicate the number of arrays used

Store the borders of the initialized (reserved) memory in a variable somewhere

When an array gets a length:

Put pointers to the start (the current border) and end (the current border + the length) in the array from the first point at index c

Increment c

I think this would work (wouldn't it?), but there a few cons, mainly concerning memory: I need to store the array, c and the current memory borders as overhead.

Would there be a better way to implement non-fixed size arrays in a language for PIC microcontrollers? My requirements are:

Low memory overhead

The array length does not have to be changed on the fly

With the system I thought up, one cannot store values in arrays that haven't been initialized yet. If there would be a system that can store values in an array of undefined length, that would be an advantage

Faster systems (at runtime, compile time doesn't matter) are preferable

答:
Variable-length arrays in C99 are still fixed-size; you just don't know the size until runtime.  They're not dynamic, so you can't declare int foo[] and start accessing elements.  There's no way to know how much space to allocate for it and there's no magic that goes on behind the scenes that rearranges everything as the array grows.

In earlier versions of C, the compiler did a single move of the stack pointer at the start of scope because all of the variables were declared up front:

```<code>{
  int foo;
  int bar;
  // Stack pointer gets nudged 2 * sizeof(int)
  ... Code ...
}
</code>```

What makes VLAs possible was a change in C99 that allowed declaration of variables anywhere in the code instead of just at the top of scope:

```<code>{
  int foo;  // Stack pointer gets nudged sizeof(int)
   ... Code ...
  int bar;  // Stack pointer gets nudged another sizeof(int)
}
</code>```

Being able to do this means that to create a VLA, all that has to be done is evaluate the expression in the brackets (which can use previously-declared variables because the compiler knows where to find them), multiply the result by the size of the array type and nudge the stack pointer by that much:

```<code>{
  size_t size;  // Stack pointer gets nudged sizeof(size_t)
  size = get_number_of_ints_in_input();
   ... Code ...
  int data[size];  // Stack pointer gets nudged size * sizeof(int)
   ... Code ...
}
</code>```

As long as you keep track of how much the stack pointer has been moved, you can pull it back where it should be anytime you go out of scope.

ContentLicense: CC BY-SA 3.0

Body:
Variable-length arrays in C99 are still fixed-size; you just don't know the size until runtime.  They're not dynamic, so you can't declare int foo[] and start accessing elements.  There's no way to know how much space to allocate for it and there's no magic that goes on behind the scenes that rearranges everything as the array grows.

In earlier versions of C, the compiler did a single move of the stack pointer at the start of scope because all of the variables were declared up front:

{
  int foo;
  int bar;
  // Stack pointer gets nudged 2 * sizeof(int)
  ... Code ...
}

What makes VLAs possible was a change in C99 that allowed declaration of variables anywhere in the code instead of just at the top of scope:

{
  int foo;  // Stack pointer gets nudged sizeof(int)
   ... Code ...
  int bar;  // Stack pointer gets nudged another sizeof(int)
}

Being able to do this means that to create a VLA, all that has to be done is evaluate the expression in the brackets (which can use previously-declared variables because the compiler knows where to find them), multiply the result by the size of the array type and nudge the stack pointer by that much:

{
  size_t size;  // Stack pointer gets nudged sizeof(size_t)
  size = get_number_of_ints_in_input();
   ... Code ...
  int data[size];  // Stack pointer gets nudged size * sizeof(int)
   ... Code ...
}

As long as you keep track of how much the stack pointer has been moved, you can pull it back where it should be anytime you go out of scope.


问:
Why is there no 'finally' construct in C++?
Exception handling in C++ is limited to try/throw/catch. Unlike Object Pascal, Java, C# and Python, even in C++ 11, the finally construct has not been implemented.

I have seen an awful lot of C++ literature discussing "exception safe code". Lippman writes that exception safe code is an important but advanced, difficult topic, beyond the scope of his Primer - which seems to imply that safe code is not fundamental to C++. Herb Sutter devotes 10 chapters to the topic in his Exceptional C++ !

Yet it seems to me that many of the problems encountered when attempting to write "exception safe code" could be quite well solved if the finally construct was implemented, allowing the programmer to ensure that even in the event of an exception, the program can be restored to a safe, stable, leak-free state, close to the point of allocation of resources and potentially problematic code. As a very experienced Delphi and C# programmer I use try.. finally blocks quite extensively in my code, as do most programmers in these languages.

Considering all the 'bells and whistles' implemented in C++ 11, I was astonished to find that 'finally' was still not there.

So, why has the finally construct never been implemented in C++? It's really not a very difficult or advanced concept to grasp and goes a long ways towards helping the programmer to write 'exception safe code'.

答:
From Why doesn't C++ provide a "finally" construct? in Bjarne Stroustrup's C++ Style and Technique FAQ:

Because C++ supports an alternative that is almost always better: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object's destructor will release the resource. That way, the programmer cannot forget to release the resource.


答:
The reason that C++ does not have finally is because it is not needed in C++.
finally is used to execute some code regardless of whether an exception has occurred or not, which almost always is some kind of cleanup code. In C++, this cleanup code should be in the destructor of the relevant class and the destructor will always be called, just like a finally block.
The idiom of using the destructor for your cleanup is called RAII.

Within the C++ community there might be more talk about 'exception safe' code, but it is almost equally important in other languages that have exceptions. The whole point of 'exception safe' code is that you think about in what state your code gets left if an exception occurs in any of the functions/methods that you call.

In C++, 'exception safe' code is slightly more important, because C++ does not have automatic garbage collection that takes care of objects that are left orphaned due to an exception.

The reason the exception safety is discussed more in the C++ community probably also stems from the fact that in C++ you have to be more aware of what can go wrong, because there are fewer default safety nets in the language.

Title: Why is there no 'finally' construct in C++?

Body:
Exception handling in C++ is limited to try/throw/catch. Unlike Object Pascal, Java, C# and Python, even in C++ 11, the finally construct has not been implemented.

I have seen an awful lot of C++ literature discussing "exception safe code". Lippman writes that exception safe code is an important but advanced, difficult topic, beyond the scope of his Primer - which seems to imply that safe code is not fundamental to C++. Herb Sutter devotes 10 chapters to the topic in his Exceptional C++ !

Yet it seems to me that many of the problems encountered when attempting to write "exception safe code" could be quite well solved if the finally construct was implemented, allowing the programmer to ensure that even in the event of an exception, the program can be restored to a safe, stable, leak-free state, close to the point of allocation of resources and potentially problematic code. As a very experienced Delphi and C# programmer I use try.. finally blocks quite extensively in my code, as do most programmers in these languages.

Considering all the 'bells and whistles' implemented in C++ 11, I was astonished to find that 'finally' was still not there.

So, why has the finally construct never been implemented in C++? It's really not a very difficult or advanced concept to grasp and goes a long ways towards helping the programmer to write 'exception safe code'.


答:
It's really just a matter of understanding the philosophy and idioms of C++.  Take your example of an operation that opens a database connection on a persistent class and has to make sure that it closes that connection if an exception is thrown.  This is a matter of exception safety and applies to any language with exceptions (C++, C#, Delphi...).

In a language that uses try / finally, the code might look something like this:

```<code>database.Open();
try {
    database.DoRiskyOperation();
} finally {
    database.Close();
}
</code>```

Simple and straightforward.  There are, however, a few disadvantages:

If the language doesn't have deterministic destructors, I always have to write the finally block, otherwise I leak resources.

If DoRiskyOperation is more than a single method call - if I have some processing to do in the try block - then the Close operation can end up being a decent bit away from the Open operation.  I can't write my cleanup right next to my acquisition.

If I have several resources that need to be acquired then freed in an exception-safe manner, I can end up with several layers deep of try / finally blocks.

The C++ approach would look like this:

```<code>ScopedDatabaseConnection scoped_connection(database);
database.DoRiskyOperation();
</code>```

This completely solves all of the disadvantages of the finally approach.  It has a couple of disadvantages of its own, but they're relatively minor:

There's a good chance you need to write the ScopedDatabaseConnection class yourself.  However, it's a very simple implementation - only 4 or 5 lines of code.

It involves creating an extra local variable - which you're apparently not a fan of, based on your comment about "constantly creating and destroying classes to rely on their destructors to clean up your mess is very poor" - but a good compiler will optimize out any of the extra work that an extra local variable involves.  Good C++ design relies a lot on these sorts of optimizations.

Personally, considering these advantages and disadvantages, I find RAII (Resource Acquisition Is Initialization) a much preferable technique to finally.  Your mileage may vary.

Finally, because RAII is such a well-established idiom in C++, and to relieve developers of some of the burden of writing numerous Scoped... classes, there are libraries like ScopeGuard and Boost.ScopeExit that facilitate this sort of deterministic cleanup.

Body:
It's really just a matter of understanding the philosophy and idioms of C++.  Take your example of an operation that opens a database connection on a persistent class and has to make sure that it closes that connection if an exception is thrown.  This is a matter of exception safety and applies to any language with exceptions (C++, C#, Delphi...).

In a language that uses try / finally, the code might look something like this:

database.Open();
try {
    database.DoRiskyOperation();
} finally {
    database.Close();
}

Simple and straightforward.  There are, however, a few disadvantages:

If the language doesn't have deterministic destructors, I always have to write the finally block, otherwise I leak resources.

If DoRiskyOperation is more than a single method call - if I have some processing to do in the try block - then the Close operation can end up being a decent bit away from the Open operation.  I can't write my cleanup right next to my acquisition.

If I have several resources that need to be acquired then freed in an exception-safe manner, I can end up with several layers deep of try / finally blocks.

The C++ approach would look like this:

ScopedDatabaseConnection scoped_connection(database);
database.DoRiskyOperation();

This completely solves all of the disadvantages of the finally approach.  It has a couple of disadvantages of its own, but they're relatively minor:

There's a good chance you need to write the ScopedDatabaseConnection class yourself.  However, it's a very simple implementation - only 4 or 5 lines of code.

It involves creating an extra local variable - which you're apparently not a fan of, based on your comment about "constantly creating and destroying classes to rely on their destructors to clean up your mess is very poor" - but a good compiler will optimize out any of the extra work that an extra local variable involves.  Good C++ design relies a lot on these sorts of optimizations.

Personally, considering these advantages and disadvantages, I find RAII (Resource Acquisition Is Initialization) a much preferable technique to finally.  Your mileage may vary.

Finally, because RAII is such a well-established idiom in C++, and to relieve developers of some of the burden of writing numerous Scoped... classes, there are libraries like ScopeGuard and Boost.ScopeExit that facilitate this sort of deterministic cleanup.

ContentLicense: CC BY-SA 4.0


问:
What does Uncle Bob mean by 'noun phrase names'?
I am reading Clean Code by Uncle Bob. Because I am not a native-English speaker, I couldn't understand following statement:

Classes and objects should have noun or noun phrase names like
  Customer, WikiPage, Account, and AddressParser. Avoid words like
  Manager, Processor, Data, or Info in the name of a class. A class name
  should not be a verb.

As I know, none of the Manager, Processor, Data, and Info is a verb, isn't it? What is the actual point he want to emphasize?

答:
He's trying to draw a distinction between things (nouns) and actions (verbs). In conventional objected-oriented design, we think of classes as things, and their methods as the actions those things can perform. To manage is to take care of or coordinate, while manager is a person or thing that manages.

Introductory books usually boil this down to the simplest and most obvious terms possible like a class named Dog, with methods Bark and Bite. In real world classes, the distinction is often a little more subtle, but it's still there. I believe the point Uncle Bob is making, however, is that while manager is a noun, but it puts a lot of attention on the what the manager does, and not what it is-it's too vague of a word for describing exactly what is being managed or how.


答:
The three points are separate:

Class names should be nouns or noun phrases. This means that the name of the class should be something that would be the subject of a verb. In the case of object-oriented design, methods would be the verbs that take place on the thing that the class is a representation of.

Some words should be avoided. Manager indicates a possible god class. Info and Data may indicate a dummy data container. Words like this may indicate poor modeling of the problem space.

Verbs should never be class names. See the first point - classes model things, methods model actions.

Title: What does Uncle Bob mean by 'noun phrase names'?

Body:
I am reading Clean Code by Uncle Bob. Because I am not a native-English speaker, I couldn't understand following statement:

Classes and objects should have noun or noun phrase names like
  Customer, WikiPage, Account, and AddressParser. Avoid words like
  Manager, Processor, Data, or Info in the name of a class. A class name
  should not be a verb.

As I know, none of the Manager, Processor, Data, and Info is a verb, isn't it? What is the actual point he want to emphasize?


问:
Python reading from stdin while doing other tasks
I am trying to write a system log parser. It will receive messages from the FreeBsd syslog daemon through stdin.

It will use those messages to determine if an ip should be banned or not.
The problem I have is that after x seconds the ban should be removed, but if I won't get any input from stdin, my program will just block waiting for it. So in the mean time I can't do anything.

I fixed it using threads, but isn't there a better way to do it?

For example something like this:

```<code>while true:
    while <data in stdin>:
        handleData

    doSomeStuff()
</code>```

So as long nothing comes in from stdin I want to execute doSomeStuff, and if there is data handle it.

答:
This is a perfect example to use multithreading.

Create a 'worker' thread and another thread, which waits for user input.
When the 'input' thread receives input, it can add an item to a 'todo' list (with some sort of locking to exclude race conditions).

Then, the worker thread can fetch the topmost element and execute it. In your case it should also add another item for 'unbanning' the IP later, which means each task should have a 'time' tag of some sort.

A reasonable structure to implement this is a red-black tree or a binary heap with sorting by the 'time' value.

Then, your worker thread checks if the time has come to execute the top object in the 'todo' list, executes it and sleeps some reasonable amount of time (say 100 ms).

On the other hand, the input thread waits for input, and when presented with it, adds a task with the current time (which guarantees it would be almost immediately picked up by the worker thread).


答:
You can use a "trap" pattern - even if you don't want to use try/catch block.

Put a simple object in the required scope. In this object's destructor put your "finaly" logic. No matter what, when the stack is unwound, object's destructor will be called and you'll get your candy.


答:
Others have discussed RAII as the solution. It's a perfectly good solution. But that doesn't really address why they didn't add finally as well since it's a widely desired thing. The answer to that is more fundamental to the design and development of C++: throughout the development of C++ those involved have strongly resisted the introduction of design features that can be achieved using other features without a huge amount of fuss and especially where this requires the introduction of new keywords that could render older code incompatible. Since RAII provides a highly functional alternative to finally and you can actually roll your own finally in C++11 anyway, there was little call for it.

All you need to do is create a class Finally that calls the function passed to it's constructor in it's destructor. Then you can do this:

```<code>try
{
    Finally atEnd([&] () { database.close(); });

    database.doRisky();
}
</code>```

Most native C++ programmers will, in general, prefer cleanly designed RAII objects however.

Body:
Others have discussed RAII as the solution. It's a perfectly good solution. But that doesn't really address why they didn't add finally as well since it's a widely desired thing. The answer to that is more fundamental to the design and development of C++: throughout the development of C++ those involved have strongly resisted the introduction of design features that can be achieved using other features without a huge amount of fuss and especially where this requires the introduction of new keywords that could render older code incompatible. Since RAII provides a highly functional alternative to finally and you can actually roll your own finally in C++11 anyway, there was little call for it.

All you need to do is create a class Finally that calls the function passed to it's constructor in it's destructor. Then you can do this:

try
{
    Finally atEnd([&] () { database.close(); });

    database.doRisky();
}

Most native C++ programmers will, in general, prefer cleanly designed RAII objects however.


问:
Duplication of view access control logic in database queries and application component
Our web application has a complex access control system which incorporates role-based and object-level privileges.

In the business logic layer, this is implemented by a component that obtains (and caches) all the necessary data with a batch query and computes the user's type and level of access to any object in the system. (A future optimization would be conditional batching based on the data we need for a particular request.)

However, the view privilege logic in this component is duplicated elsewhere in database queries. (We need to hide data in listing screens that the user does not have privilege to view.)

How can we reduce or eliminate this duplication of logic between the application access control component and our database queries?

Two approaches come to mind. I'm sure there are others.

Check view privilege in the application for each row that comes back from the server via queries from listing screens.

Move more of the access control logic into a stored function that can be called from the queries as well as the application code.

Answers should defend the merits of the proposed method over other methods. For example, if my second suggested approach is desirable, why? If you have suggested a third approach, why does it win over both my approaches?

答:
I'm struggling with some of these issues currently, and was looking for other people's approaches when I came across this question.  I thought I'd toss some thoughts up here just in case they help someone coming down this route later.

The approach I've decided upon has the following:

The model layer has no access control logic in it, with the exception that model objects respond to a method that takes a current user as a parameter and returns an access control object.

The access control layer objects contain references to the model object and the current user object and responds to messages such as can_show? (yup, this is in Ruby), can_edit?, can_destroy?, can_show_some_attribute_name?, can_modify_some_attribute_name?, etc.  Note that this means that there is field level access control.

There is a decorator layer for the model that is used for the views.  Decoration requires that a current user be supplied.  The decorators intercept all attribute accessor methods and check them against the access control object before permitting the operation.  Read operations return nil if the access is forbidden and write operations raise an error in the same situation.  To simplify use, the decorators delegate all methods starting with can_ to the access control object.

I'm currently attacking the problem of implementing a query system.  For instance, if a user chooses to hide their phone number from public users, then a query to find users with a given phone number shouldn't return that record.  Similarly, if one requests that the results be sorted by phone number, one shouldn't be able to deduce that a given phone number must be between those for adjacent records.  For now I've decided to simplify implementation by assuming that the SQL queries will be done without respect to access control (which should return a super set of results) and then the query system will filter the results (including ensuring all conditionals are met and re-doing the sort) using the access control object to check access.  So the query system uses the Builder pattern to both store the query logic for its own implementation and to pass it along to the ORM.

The query part seems to be the most difficult.  I'd like to be able to translate the record level access control directly into SQL queries for performance reasons, even if I'm unsuccessful in also translating the field level access control.


答: Threads are fine, and there's really nothing wrong with using them here. For completeness sake, there's also select(), which allows you to do a blocking check for pending input on a file descriptor, with a timeout. If you use this function in a loop, interspersed with the timed activity, you'll get roughly the same concurrent behavior, but implemented on a single thread. This is the python binding for select() and its friends, btw.

Title: Python reading from stdin while doing other tasks

Body:
I am trying to write a system log parser. It will receive messages from the FreeBsd syslog daemon through stdin.

It will use those messages to determine if an ip should be banned or not.
The problem I have is that after x seconds the ban should be removed, but if I won't get any input from stdin, my program will just block waiting for it. So in the mean time I can't do anything.

I fixed it using threads, but isn't there a better way to do it?

For example something like this:

```<code>while true:
    while <data in stdin>:
        handleData

    doSomeStuff()
</code>```

So as long nothing comes in from stdin I want to execute doSomeStuff, and if there is data handle it.


问:
Code Base with awful code conventions, follow them?
With no time to refactor, when you are working on legacy code, with the most awful conventions, what is the best practice?

Will trying to follow better coding style would improve readability or actually hurt it?

For example, in java method names are usually camel cased:

myGoodNamedMethod

But in the repository there are code with methods like this (not all, but the majority)

my_c_style_method_that_looks_off_in_java

答:
No matter how odd you find the existing conventions, FOLLOW THEM. Having some conventions, even if you don't like them, is FAR FAR better than not having any.

Obviously that's not always true (some conventions are outright hostile to getting work done, like limiting all names to 8 characters for no good reason), but except in the most extreme cases, just follow what's there.


答:
Follow the existing standards.  Maybe they're outdated/odd/wrong/unpleasent. (as long as they're not being hostile as @Michael Kohne mentioned).  </p>

<p>There could be reasons outside of the language standards to be using the naming style.  I have heard of people running 3rd party applications over the code base to pull out names for use later.  Eg test names as requirements or auto building api documentation.   </p>

Title: Code Base with awful code conventions, follow them?

Body:
With no time to refactor, when you are working on legacy code, with the most awful conventions, what is the best practice?

Will trying to follow better coding style would improve readability or actually hurt it?

For example, in java method names are usually camel cased:

myGoodNamedMethod

But in the repository there are code with methods like this (not all, but the majority)

my_c_style_method_that_looks_off_in_java

Body:
Follow the existing standards.  Maybe they're outdated/odd/wrong/unpleasent. (as long as they're not being hostile as @Michael Kohne mentioned).

There could be reasons outside of the language standards to be using the naming style.  I have heard of people running 3rd party applications over the code base to pull out names for use later.  Eg test names as requirements or auto building api documentation.


问:
subclass of immutable object not immutable, can this work?
So I'm finishing up refactoring some code to remove a number of previously-mutable objects and add a better generic processing for all the classes in the domain.  Just as I thought I was finishing I eralized that there is one sub-class that has some additional state.

The additional state is a link to other classes that are used as part of the logic for knowing when new domain objects will be created, deleted, or modified.  However, this sub-class is only created at bootup, or when someone runs a command to re-read and update to new configuration files.  I know that this object will always be created before any of the other objects in my domain that are dependent on it are, such that anyone pointing to this object are all gaurenteed to point to the same instance.  I effectively have the Memorization pattern by an accident of how the structure is created.

I could refactor away the mutability; but it would require a bit of work modifying bootup logic that I would prefer to avoid.  Or I could change the has and equals methods to ignore this one set of mutable values so my model will treat this object exactly like it's immutable parent and trust that my knowledge of the method it is constructed prevent me from aliasing issues when I do try to use it's mutable traits.

So how 'wrong' is it to bend my contract for thie class this way be?

答:
There's nothing inherently wrong with mutable subclasses provided you don't make assumptions about mutability in other parts of your code.

As an example, the Foundation framework that's part of Cocoa and Cocoa Touch frameworks (MacOS X and iOS respectively) has a number of immutable data containers that have mutable subclasses. NSMutableArray is a mutable subclass of the immutable  NSArray, NSMutableDictionary is a mutable subclass of the immutable NSDictionary, etc.

This works fine if you think of mutability as an added feature rather than something that needs to be removed from the superclass. Most importantly, client code should never try to make changes to an object that's advertised as immutable, even if the object happens to be an instance of a mutable subclass.

So, if a method returns a NSArray, you might actually get back an instance of NSMutableArray, but you should always treat it as immutable anyway.


问:
Best way to auto login in web application
This question could be titled "Place password hash and salt in query string?" as well to be less subjective, but the point remains the same:

I want to create kind of a launcher application for my web application, which should allow the user to specify his credentials to auto login into my web application.

Now since plaintext is almost always awful, I thought about passing the password hash and salt as a querystring to my application to perform an auto login. Something like:
http://myapp.com/login/?autologin=true&passwordhash=foo&salt=bar

But I wonder if there is any better or more secure way instead of doing this?

答:
Don't send even hashed passwords in plaintext and especially not in the URL. A time-limited token is much less valuable to an attacker.

Use a cryptographically secure random generator to create a unique token for each user. You'll need to work out how to issue new tokens when the old ones expire. This is how most email-login links work.


答: Just do a HTTPS POST in your launcher application, passing through the username+password normally. That's how your web browser does it.</p>

Title: Best way to auto login in web application

Body:
This question could be titled "Place password hash and salt in query string?" as well to be less subjective, but the point remains the same:

I want to create kind of a launcher application for my web application, which should allow the user to specify his credentials to auto login into my web application.

Now since plaintext is almost always awful, I thought about passing the password hash and salt as a querystring to my application to perform an auto login. Something like:
http://myapp.com/login/?autologin=true&passwordhash=foo&salt=bar

But I wonder if there is any better or more secure way instead of doing this?


答:
Even hashing the password and sending it via GET or POST is a serious breach if you only send it via HTTP - anyone can intercept the plaintext request and use that hashed value to access from anywhere else as that user.

If you're going to do this kind of thing, you absolutely should be using HTTPS - with a proper certificate from a recognised authority. That way, the information is encrypted and much harder to intercept (SSL can still be decrypted by third parties, but a decent key length and configuration should make this a very expensive operation).


问:
Who should support and maintain development infrastructure?
I am interested to know what other peoples' experiences are with managing development infrastructure are.  I am talking about things like the build server, the central git repo etc etc.  Any infrastructure which end users would probably not even know existed, but which are essential for the development team.

Do your dev/devops/ops teams consider them to be as important as 'true' production systems?

What happens when one goes down (both in terms of ramifications and recovery processes)?

Who should be responsible for managing them?

Note: to complicate things (especially (3) above, our "teams" are small, about five or six devs and only the one sys admin.  Hence, there is a lot of crossover of us devs in to ops, especially with the advent of the "devops" movement and technologies.

Disclaimer - I am the author of this blog post about the subject.

答:
That's a good question. At companies that I've worked at they are not quite considered a "true" production system - after all they are not used by customers and they're not externally facing. But, if they go down, it will bring all IT development to a halt, so they realise that these boxes are important. Bug fixes are impossible, developing new features is impossible. It would be the same as a data entry team losing access to their data import application. They are as important as any other internal system.

So to answer your questions:

No. They do not have fail-overs. If they stop working for 30 mins or go down overnight it's not the end of the world. But they need to be working for the majority of the time.

Everybody in the IT dev department walks over to the ops guys and pokes them in the back until they are back up.

The best approach I've found is that the tech lead has full admin rights to the box, but the underlying hardware is still managed by ops. If the tech lead does something stupid and kills the box it's up to him/her to fix it :)

It sounds like what you need to do is a bit of education with your sysadmin over why Source Code Control and CI tools are vital to development.


答:
Follow the existing standard.

However, if there's a genuine need to fix it (it's becoming a major problem), take a deep breath, man up and refactor the entire code base to follow a new standard. But only do this if it's truly necessary, have everyone's approval and if you have the time. It probably won't take as long as you might think, but do your research first.


问:
Why would I use Angular?
From the basic Angular tutorial, it seems like all it does is fetch some JSON from an API and display it. Also, there's its double binding magic.

But why would I use it instead of a backend solution (like Rails) that builds the view in the backend and serves it to the user, with everything in place already? What are the use cases?

答:
It is about making more responsive user interfaces. The double binding, dependency injection and so on makes it possible to create dynamic pages quite easily. You can write directives in Angular which gives you a declarative way to construct a view.

As an example, in a current project we have a view that uses several hundred lines of JavaScript code in order to make a responsive user experience. Even so the page is a bit buggy and very difficult to maintain. We started looking around for a better option and looked at backbone.js and knockout.js. Eventually we tried Angular. We were able to create a much more responsive and maintainable page with just a few lines of code. Gone was all the DOM manipulation code. Gone was all the clunky backend view creations that had to be fetched and inserted at the right places. Gone was all the code that was written to keep the model and the view in sync. With that experience the decision to move to Angular became easier and so far we have not regretted it.

Title: Why would I use Angular?


答:
TLDR;

Angular helps you deal with the complexity inherent in rich user interfaces. As UI complexity increases, the traditional model of generating pages on the server gets much more complex. Angular lets you decompose your UI into manageable chunks, and allows you to separate the UI from the implementation. This makes server-side page generation a great deal easier, but Angular really comes into its own when you make the move to pure javascript-based applications. A good example of such an application is Trello.

The long story

Angular isn't really targeted at sites that you can comfortably implement by generating everything on the server, and sending it across. Furthermore, whilst that is a perfectly good approach that works for many sites and applications around the internet, it becomes increasingly complex (thus difficult) to keep that approach working as you try to increase the level of interactivity in your site.

Ultimately the way you solve this is by pushing your UI more and more into the Javascript side of the equation. Angular lets you break your UI up into components, giving you clear separation between the look-and-feel, and the how-it-works. You can then build fairly simple pages on the server, and the JS front end is used to create a rich UI that makes separate calls back to your server for the data they need.

There comes a point, though, where all you want to do is server a stub page that loads a completely javascript-based application. Probably the most well known example of the sort of use-case where Angular really shines is Trello (it uses Backbone, not Angular, but it is the same use-case). There is a site http://builtwith.angularjs.org/ which has more example sites that use Angular.

So the short answer? Angular makes it easier to create rich, highly interactive user interfaces by letting you decompose your UI into components, and ultimately go completely javascript.

Title: Why would I use Angular?

Body:
From the basic Angular tutorial, it seems like all it does is fetch some JSON from an API and display it. Also, there's its double binding magic.

But why would I use it instead of a backend solution (like Rails) that builds the view in the backend and serves it to the user, with everything in place already? What are the use cases?


问:
Complex Mutual Exclusion Validation Logic
I need to validate some form inputs in complex way. E.g.

```<code><select id="options" multiple="multiple">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
</code>```

For example, if user selects A and B, user should be given an error if user also selects D.

Note, I'm trying to keep this business rule in a separate layer from this UI code, which could be an entirely different form, e.g. checkboxes, drag-and-drop, add/delete options with possibly accompanying fields.

I'm looking for a framework, design pattern, or other elegant way to code this logic, preferably ultimately through validation attributes in a model.

答: Approaching the question from a different angle: Why not disable D if the user selects A and B? When I have this kind of question I start to think about reviewing my UI flow.</p>


问:
Running entire frontend of a system on a flatfile cache
I'm in the middle of moving away from PyroCMS to a custom solution built on Laravel. Wont go into the details as to why here, but it is a necessity.

I'm toying with the idea of caching things like pages and posts into flatfile once they are created, and then loading them (if they exist) and falling back to the mysql database if the cache isnt found.

It got me thinking. Is there a problem with essentially running the entire 'frontend' of your system or site on flatfile, pre-rendered cached files? Surely the cache only needs dropping/replacing when a post or page is modified, so a cache could essentially be kept for the lifetime of the site.

Unless I'm missing something, surely this is something that should be done a lot more, should it not? Even if it was just storing serialised or json data from the database tables, it's got to be faster than opening up a mysql connection hasn't it?

答:
As per comments, before doing optimisations, you have to know which parts need to be optimised (measure). For static files, you can use reverse proxy. If latency is your problem, then moving files to a CDN might help with geographically distant clients. These optimisations will free you from programming, less code and even faster because they're done even before php run.

Then for the dynamic parts you can cache as needed. One thing with using files is if in the future you want add more servers, accessing the cache files won't be as ideal as using memcache, for example. Still worth doing on frontend, e.g. for showing data as user types.


问:
Seeking advice on design of application protocol
UPDATE 1 as requested by Brendan.

We are developing a Unix batch application for storing millions of customer records into a relational database.  In order to allow multiple batch jobs to run in parallel, and to achieve a certain amount of concurrency while processing an input record, we've distributed the work across nine server daemons, all within the same LAN as the client, each of which is responsible for an isolated task (e.g. store the name in the name table, store the address in the address table, etc.).

Each daemon will be able to accept connections and requests (concurrently) from multiple clients.

Finally, whatever communication protocol we design (or adopt) must be extensible to accommodate different kinds of connections - for instance, we'd like for a monitor tool to be able to connect to a daemon, over the same port as the clients, and request statistics or send commands.  There will also eventually be different kinds of clients that require different functions to be performed by the daemons.  In other words, a client connecting to a daemon will have to be able to declare "I want to post customer records," or "I want to apply a batch of changes-of-address to the database" or "I want to send you a few commands."

I think it's a foregone conclusion that the underlying transport of these connections be TCP.

Finally, apart from the "command session", these will be multi-million record batch jobs, and performance is critical.  The processing is iterative, and every record has the same layout (so wrapping each one in XML, say, would be unnecessary and highly wasteful).

I've no idea if this is enough information for someone to suggest some formats and protocols to use, but I'll gladly try to clarify or supply additional details if asked.

END OF UPDATE 1

(Below is the original post, which may or may not be of any value.)

I'm in charge of designing an application protocol for a set of in-house, batch-oriented, client-server applications.  I'm familiar with IBM LU 6.2 (a.k.a. "Advanced Program-to-Program Communication"), and for the past 15 years have worked in Unix environments.

The client is a batch job that connects to a server process — which, in turn, connects to nine other "sub-server" processes.  The client passes a customer transaction record to the server, which distributes different portions of the record to the sub-servers.  Each sub-server processes its portion independently and concurrently, and passes some results back to the server which then passes them back to the client.

These are TCP connections, and we decided that, first of all, we'd use newline-terminated ASCII strings (we call these lines) as our Protocol Data Unit.  A record is a line that is subdivided into tab-separated fields, and since each process will have its own data requirements, field#1 of every record will contain a record type.  This is used as a key into a metadata store to find the field names, in the order they’re expected to appear in the record, in order to know how to interpret the record.  For example:

```<code>Metadata: NAME=(prefix, first_name, middle_name, last_name, personal_suffix, professional_suffix)
Record:   NAME||CHAP||HARRISON|JR|CTO#
</code>```

(Here I use '|' to represent the tab character, and '#' to represent newline character)

Very straightforward so far, I think.

But then, new twists arose.  The first was that, instead of sending all the data about one transaction in a single [large] record, we'd like to possibly use several records: a NAME record, an ADDRESS record, an EMAIL record, etc.  So we invented the block - a series of records, preceded by a “special” BB record and followed by an EB record.  The BB record’s first field is, of course, 'BB', and the second field holds the block type.  Block type, like record type, is a key into metadata listing the record types (required, or optional) in this block type.

Understandably, each of these ten or so processes, having its own unique data requirements, has led to its own set of record types, enclosed in their own set of block types.  That's a lot of metadata, but it isn't really a showstopper.

The next thing requirement that emerged was a special "context-setting" message, to transmit certain configuration variables that would remain constant from transaction to transaction.  This gave rise to a new record and block type, as well as a new column in the block metadata that indicated this kind of block was somehow "special".

Then, envisioning circumstances where the "context" could change during the runtime of the client, we lifted the rule that stipulated there could be only one "context" message, at the beginning of a connection.  At the same time, we realized there was still a need for a true "initialization" message that could only come once, at the beginning, conveying "session-global" parameters.  Thus the INIT block was born, and now there were three flavors of block: session-initialization, context-switching, and normal application data.

Then, how about a connection that isn't for transaction-posting at all, but rather a control session for querying the health of the server, retrieving statistics, changing operational settings?  The INIT block’s role became more general, declaring the "mode" of the session, which could now be either "posting", or "control."

We've been trying to wedge all of this into a single-layered application protocol, and it's getting out of hand.  Just defining a "special" BB record should have raised a red flag - it's constructed from application-level objects and metadata, but it is not application data - rather, it frames the application data.

I think what has evolved is a 2-layer architecture atop TCP: one layer that simply provides typed containers (blocks and records), and a higher layer that uses those containers for a specific purpose, be it posting, or control, or something else - the true application protocols. However, I'm not well-versed enough in the design of protocols to recognize "patterns" that might be obvious to the pros.  I'd appreciate any feedback on how to approach this.

It also seems possible that someone may have written a guide to designing protocols, that addresses these very concerns.  I just haven't found it.

And my apologies for the length of this post.  I hope none of it was immaterial.  My deep thanks for your patience!

Chap

答:
First, break the problem into "requests" and "replies". A request (from server to sub-server) should begin with some sort of request type identifier, and all of the other data in the request should depend on the request type identifier (e.g. if you have a "set name" request, then you don't include irrelevant data like "number of cats" in that request). The type of request also determines the type/s of reply the sub-server might send back (e.g. if you send a "set name" request then you might get a "name set" reply or an "error reason" reply; but won't get a "number of cats" reply).

Second; avoid having modes/contexts if at all possible. For example, rather than having a "set mode to foo" request and a "get name" request, just have a "get name using mode foo" request. This reduces the amount of state in the sub-servers and makes code cleaner; and it can also be important for things like fault tolerance and scalability later on.

Third; allow groups of requests (and groups of replies) to be sent across the network in the same packet. The only reason for this is that small packets waste bandwidth which can become a bottleneck under load. Basically you'd have a "send_request()" function that tries to add the request to the current packet (and sends the packet and starts a new one if the request won't fit). You will also need timing to avoid latency problems under light load. For example, when you add the first request to a new packet, set a timer for about 2 ms, and when that timer expires send the packet regardless of whether it's been filled or not.

Fourth; I personally dislike sending data that isn't text as text. Some people think it makes it easier for debugging (and it can a little bit if you're unable to work with hex dumps or write a simple decoder); but this doesn't justify the unnecessary increase in bloat. For a simple example, sending a signed 32-bit integer would mean converting to ASCII, sending up to 11 bytes of data, then converting from ASCII back into an integer; rather than sending 4 bytes of data with no conversions (other than serialisation for endianness that would be almost always optimised to nothing). Sadly, there's a lot of people using scripting languages for more than just scripting now, so "doing it right(tm)" might be impractical and avoiding bloat may be impossible (e.g. a lot of scripting languages store integers as strings internally).

Fifth; document the protocol well. You should write a "formal-ish" specification that describes each individual request (what its intended for, its "request ID", which fields in which format, which replies are possible, etc) and describes each individual reply. It should also mention if there's any special requirements (e.g. a "lock entry" request needs to be followed by one or more "modify entry" requests and then an "unlock entry request").

Sixth; examine how the data is used. Typically (for databases) finding the right row/s takes most of the time and it doesn't matter how many columns are in that row; and typically you need multiple pieces of data from a row at the same time. It's likely that having one sub-server for "name", one for "address", one for "age", etc is going to give bad performance, because if you want the name, address and age at the same time then you end up with 3 sub-servers trying to find the right rows (with triple the overhead). Normally there's some sort of unique key involved (e.g. a user ID) and it's far better for the server to use this to determine which sub-server is responsible (e.g. for 9 sub-servers, the server would do "sub_server_number = user_ID % 9" to determine which sub-server to talk to for all transactions involving that user ID). Note that this may also be important for fault tolerance - e.g. if the sub-server for "name" explodes then the entire system will probably fail; but if the sub-server for every nth unique key explodes then all transactions involving other unique keys can continue uninterrupted.


问:
Writing a Compiler Compiler - Insight on Use and Features

This is part of a series of questions which focuses on the sister project to the Abstraction Project, which aims to abstract the concepts used in language design in the form of a framework.  The sister project is called OILexer, which aims to construct a parser from grammar files, without the use of code injection on matches.

Some other pages associated to these questions, related to structural typing, can be viewed here, and ease of use, found here.  The meta-topic associated to an inquiry about the framework and the proper place to post can be found here.

I'm getting to the point where I'm about to start extracting the parse tree out of a given grammar, followed by a Recursive Descent parser which uses DFA to discern forward paths (similar to ANTLR 4's LL(*)), so I figured I'd open it up to get insight.

In a parser compiler, what kinds of features are ideal?

So far here is a brief overview of what's implemented:

Templates

Look ahead prediction, knowing what's valid at a given point.

Rule 'Deliteralization' taking the literals within rules and resolving which token they're from.

Nondeterministic Automata

Deterministic Automata

Simple lexical state machine for token recognition

Token automation methods:

Scan - useful for comments: Comment := "/*" Scan("*/");

Subtract - Useful for Identifiers: Identifier := Subtract(IdentifierBody, Keywords);

Ensures the identifier doesn't accept keywords.

Encode - Encodes an automation as a series X count of base N transitions.

UnicodeEscape := "\\u" BaseEncode(IdentifierCharNoEscape, 16, 4);

Makes a unicode escape in hexadecimal, with hex 4-transitions.  The difference between this and: [0-9A-Fa-f]{4} is the resulted automation with Encode limits the allowed set of hexadecimal values to the scope of IdentifierCharNoEscape.  So if you give it \u005c, the encode version will not accept the value.  Things like this have a serious caveat: Use sparingly.  The resulted automation could be quite complex.

What isn't implemented is CST generation, I need to adjust the Deterministic automations to carry over the proper context to get this working.

For anyone interested, I've uploaded a pretty printed of the original form of the T*y♯ project.  Each file should link to every other file, I started to link in the individual rules to follow them, but it would've taken far too long (would've been simpler to automate!)

If more context is needed, please post accordingly.

Edit 5-14-2013:
I've written code to create GraphViz graphs for the state machines within a given language.  Here is a GraphViz digraph of the AssemblyPart.  The members linked in the language description should have a rulename.txt in their relative folder with the digraph for that rule.  Some of the language description has changed since I posted the example, this is due to simplifying things about the grammar.  Here's an interesting graphviz image.

答:
I'm not experienced in language design, but I've had a go at writing a parser once, when I was creating and IDE for a game engine.

Something that is important to your ultimate end users, in my opinion, is error messages that make sense. Not a particularly earth-shattering point, I know, but following it backwards, one of the key implications of this is that you need to be able to avoid false positives. Where do the false positives come from? They come from the parser falling over at the first error and never quite recovering. C/C++ is notorious for this (although the newer compilers are a bit smarter).

So what do you need instead? I think that rather than just know what is/isn't valid at a point, you need to know how take what isn't valid and make a minimal change to make it valid - so that you can continue parsing without generating false errors relating to your recursive descent getting confused. Being able to build a parser that can generate this information not only gives you a very robust parser, but it opens up some fantastic features for the software that consumes the parser.

I realize that I may be suggesting something really difficult, or stupidly obvious, sorry if this is the case. If this is not the sort of thing you're looking for, I'll happily delete my answer.


问:
Good public API for use in demos and documentation?
I have created a utility library and open sourced it on Github, and I'd like to document the HTTP utilities.  I created this around some apps I've developed, but none of the APIs I use are for public consumption.  I want to use a well known public API in my documentation so that code samples will work and be really easy to understand for the user, but I don't work with any such API so I'm not familiar with any...looking for suggestions.</p>

答:
Programmable Web has a list of popular public web APIs sorted by the number of mashups which use it: http://www.programmableweb.com/apis/directory/1?sort=mashups

The top 10 from that list:

Google Maps

Twitter

YouTube

Flickr

Amazon

Facebook

Twilio

Last.fm

eBay

Google Search


答:
In a large organization that does best practice software development the development infrastructure is the domain of IT - as it should be. These servers are usually locked down just like any other server, and developers do not have root access to these machines. (Would you give the Office Admin root access to the corporate email server) IT will have an SLA with development that covers availability, backup, performance etc. The IT guys provide support for the raw Software development tools - GIT/Jenkins/Redmine/Clearcase etc  - security, license and user management, software updates etc. There is usually a tools team who specializes in building and customizing the tools on the servers and ensuring the developers have the tools needed to get the job done. The tools team often reports to the development manager, but works very closely with the IT team, and are usually software developers in their own right -the nature of the beast is the two teams are very closely tied - but there clear lines of responsibility.  The tool team may be part of IT, but not all IT have the skills.

Few companies work this way. IT does not 'get' software development and software development doesn't 'get' IT. IT likes stability, security and continuity of service. SD wants the latest - they want it all, and they want it now. As a result, in virtually every organization I have worked for, SD puts in some 'backyard' servers 'off the radar' of IT. IT tolerates them - as long as they don't cause problems - but wash their hands of them completely. The backups are often lacking, and SLA - heck, if it breaks, "we built it, we'll just fix it".  Tools are often few hacked-up scripts that kinda work most of the time, and there is no real budgets for the system. It doesn't really matter when it breaks - because no one really knows what software developers do all day, so it gets fixed and the time is put against "feature XYZ" of what every product has a project budget big enough.....

So to answer your question: Development servers are usually no considered, so they have no idea of their relative importance. The correct solution is they are considered in the business planning.

Usually what happens when one fails, as I have said - it gets fixed, manager run around asking why, promise to fix it, and it all goes back to how it was when the cost out doing it properly.......

Managing development infrastructure - that is IT (OPs I think you called them) - production people. Software developers should not be allowed near development infrastructure except as users.

In small house, IT and SD are often the same people, in this case, its important for them to understand the difference in the rolls and learn to put on and take off "hats".

In response to your blog ....
You are both right. The production server is more important, its failure will create an instant outage, but that does not make the dev Infra. unimportant. If dev systems go down (unrecoverable), so does the business. Somewhere, there is a cost benefit ratio between cost to protect and cost of failure. The business has to decide how much it is willing to invest is disaster resilience. Who is best qualifies to quantify that? Hint: it's not a software development

Title: Who should support and maintain development infrastructure?

Body:
I am interested to know what other peoples' experiences are with managing development infrastructure are.  I am talking about things like the build server, the central git repo etc etc.  Any infrastructure which end users would probably not even know existed, but which are essential for the development team.

Do your dev/devops/ops teams consider them to be as important as 'true' production systems?

What happens when one goes down (both in terms of ramifications and recovery processes)?

Who should be responsible for managing them?

Note: to complicate things (especially (3) above, our "teams" are small, about five or six devs and only the one sys admin.  Hence, there is a lot of crossover of us devs in to ops, especially with the advent of the "devops" movement and technologies.

Disclaimer - I am the author of this blog post about the subject.


问:
What is the best way to construct your CSS documents?
Normally I start a project working on a site, I'd do the basic html skeleton and then start tweaking the styles using CSS. Slowly I'd just add one CSS rule after another with no "organized structure" or groupings in the CSS rules.

And at the end of the project I look at the CSS document and the abomination I have created. Often spending quite some time trying to search for the spot in the document where I added a certain style.

Is there some type of 'rule-of-thumb' that one can use in laying out and getting more organized in your CSS documents? And I'm not just talking about adding comments...

答:
Independently if you're using a CSS Framework, Sass/Compass, Less, etc. or not, you should definitely take a look at SMACSS:

SMACSS (pronounced “smacks”) is more style guide than rigid framework. There is no library within here for you to download or install. SMACSS is a way to examine your design process and as a way to fit those rigid frameworks into a flexible thought process. It is an attempt to document a consistent approach to site development when using CSS.


答: I believe  a development team has to look after the entire infrastructure. Development team should be experienced and the entire software development of any IT Company should be taken care by the development team. However, it is also important that the marketing team give full cooperation to the development team. </p>


问:
How to model/structure data that contains parent/child relationships for the same entity?
I think it is just my thinking that is off here. Suppose I have two entities: question and choice. A question can be a parent or child, or both (in relation to other questions). It seems that this model is too simple and is an unresolved many-to-many, but I think my thinking is the problem here so this is more of a conceptual question. What is the best way to design/model this? Please explain why it is or isn't a many-to-many relationship, and whether or not it needs to be resolved and why. See below:

A question can be a parent or a child, or both (potentially multiple times). Programming logic would prevent the child from being its own parent and vice versa. It seems I'm missing a linking solution of some sort here, or I'm just not wrapping my brain around this.

答:
If a child can only have 1 parent it's not a many-to-many relationship, it's just 1 to many.

You could do this by simply adding a parent_id to the question:

Question:
- id
- parent_id (Contains the id of a parent if this is a child)
- title
- text

This is all you need, to get all childs to a parent just query for all questiong which have that specific parent_id. To get a parent from a child just use the parent_id column.


问:
PHP function types
I am trying to find a way of classifying different types of PHP functions. For example that fopen, fwrite, fclose and so on are all part of IO, and the MySQL functions and MySQLi class is all for mysql related things but something more automatic was wondering if there is some sort of function class mapping in PHP</p>

答:
In many languages, classes/methods/functions are organized into namespaces, which may be presented as a tree (namespace A.B and namespace A.C are logically grouped, while B.D is not not).

PHP recently introduced namespaces for custom code, but the PHP core set of functions was always a mess, and will stay a mess: it won't be organized into namespaces, because it would break all existent PHP code. Don't expect any organization from a language where functions are totally inconsistent when it comes to their names or the order of arguments.

On the other hand, PHP documentation is excellent, and it helps you understanding how functions are grouped. For example, if I take the two groups you quoted in your question, you'll find the functions related to strings on a dedicated page, and MySQL functions on another one. Those are conveniently organized into a tree: MySQL-related documentation is inside Vendor Specific Database Extensions section, which is in turn inside Database Extensions.

Note: be careful! The list of functions tell you what functions are in the same group, but doesn't tell the relations with other groups. For example, it won't tell that when manipulating strings such as user input, you should use Unicode variants, and it won't tell that instead of accessing the MySQL database directly, you should use PDO.

Title: PHP function types


问:
Necessity to learn haskell language extension for production
Haskell core language is really simple. Coming from an OO background, the main difficulty is to adapt to the pure functional paradigm.

While learning "basic" Haskell, I have always considered language extensions as toys for CS people or as experiments for future versions of the language (like from future import ??? in python).

However when I began to look at web frameworks such as Yesod, I find that a lot of source files require between 3 & 4 extensions. Some look quite simple (StringOverload). Other are really intimidating (GADT, Type Famillies, Template Haskell). Their documentation links to research papers, which is scary for someone expecting to learn "just" a new library.

Is it necessary to learn GHC language extensions to be productive in Haskell? If you were to hire a Haskell developer for a production application, would you ask for such knowledge?

答:
Is it necessary to learn GHC language extensions to be productive in Haskell?

Yes. And that is true for any language/tool. With the core/basic knowledge you can solve the online contest problems, may be small university project, but definitely not real world application.

If you were to hire a haskell developper for a production application, would you ask for such knowledge?

That now depends on do you have some person with you which can share this knowledge. If yes, then that person can ramp up the new employee. If not then you must get such person with knowledge first. And again this is true for new technologies.

Off-course you could also try to hire peoples having such deep knowledge in Haskell. But Haskell being relatively new into industry and considering very few commercial projects have been done around it, finding such person will be hard. The effective way to build a team of professionals in Haskell, will be to hire people who knew basic and willing to work in Haskell, and then educate them.


问:
Storing the EOF (End of File) character in a char type
I read in the Dennis Ritchie's The C Programming Language book that int must be used for a variable to hold EOF – to make it sufficiently large so that it can hold EOF value – not char. But following code works fine:

```<code>#include<stdio.h>

main()  {
  char c;
  c=getchar();
  while(c!=EOF)  {
    putchar(c);
    c=getchar();
  }
}
</code>```

When there is no more input, getchar returns EOF. And in the above program, the variable c, with char type, is able to hold it successfully.

Why does this work? As per the explanation in the book above mentioned, the code should not work.

答:
Your code seems to work, because the implicit type conversions accidentally happen to do the right thing.

getchar() returns an int with a value that either fits the range of unsigned char or is EOF (which must be negative, usually it is -1). Note that EOF itself is not a character, but a signal that there are no more characters available.

When storing the result from getchar() in c, there are two possibilities. Either the type char can represent the value, in which case that is the value of c. Or the type char can not represent the value. In that case, it is not defined what will happen. Intel processors just chop off the high bits that don't fit in the new type (effectively reducing the value modulo 256 for char), but you should not rely on that.

The next step is to compare c with EOF. As EOF is an int, c will be converted to an int as well, preserving the value stored in c. If c could store the value of EOF, then the comparison will succeed, but if c could not store the value, then the comparison will fail, because there has been an irrecoverable loss of information while converting EOF to type char.

It seems your compiler chose to make the char type signed and the value of EOF small enough to fit in char. If char were unsigned (or if you had used unsigned char), your test would have failed, because unsigned char can't hold the value of EOF.

Also note that there is a second problem with your code. As EOF is not a character itself, but you force it into a char type, there is very likely a character out there that gets misinterpreted as being EOF and for half the possible characters it is undefined if they will be processed correctly.


问:
How to make big chunk of hardcoded menuitems in a programmable way
So in the javascript app, we have a lot of repeated chunk of menu items with the specific settings: URL, Name, Title, etc etc (these settings sometimes can be optional). Here is the gist of the menuItem and we have tons of them.

The client pushes new changes every month or twice per month on these items, either the menu item should be named differently or the url is outdated or whatever.

Instead of going and changing each URL everytime, I thought about:

Creating a web-service, with a complete CRUD on menuitems, whatever comes in there, goes dirrectly via JSON, to the app

Well, I would like to hear if you have some thoughts on this idea of configuring the application rather than hardcoding the app each time when the CR comes.

Here is the gist of the menuItem and we have tons of them.

All help will be appreciated

答:
why not create some xml file which contains the structure of the menu items, including against each item the caption, url etc.?

Write some js to load and parse this file?

All you'd have to do then is update the xml file as and when the client changes things.


问:
Agile User Stories and acceptance criteria
I am writing some agile user stories and acceptance stories for the first time, and was hoping for some feedback from an experienced product manager or developer.

I only need to capture the main points in the acceptance criteria.

User Story

AS A registered jobseeker, I WANT TO create and edit my CV on the user interface on my mobile device SO THAT employers and recruiters can view my career summary and contact details

Acceptance Criteria

The user must sign into a registered account to create a CV

The user cannot save a CV unless all the mandatory fields on the form are complete

The user should be able to edit and delete the form at any time

Data from the saved form is stored in the CV database

Only registered Recruiters and Employers can view the users CV and contact details

The jobseekers user account is linked and synchronised on both mobile and desktop versions

Does this acceptance criteria sounds suitable for the given user story? Is there any way they can be more focused, and if so how?

答:
This is excellent. Your story makes sense, and you had a first shot at the acceptance criteria. Now, instead of checking it with this forum, check it with your team. Stimulate them to ask questions and extend the A.C. accordingly.

But since you specifically ask:

The Story:

I would omit the "in the interface" from my user story.

The story is potentially large. You could anticipate a split: (editing existing CV, creating new CV, viewing by recruiter).

The Acceptance criteria: If I were a team member at the planning meeting, I would ask more clarity about the following:

It is not clear to me how the recruiters will view the CV. Is this also on a mobile device? Does this already exist? Otherwise the team will need more details about this.

Which fields need to be implemented? Was this form already implemented in a web/desktop app? If so, then you can explicitly mention in your acceptance criteria that the mobile app should offer the exact same fields.

Any data validation on these fields (eg. can I just enter "X" day of birth)


答:
The story itself looks good and the first four acceptance criteria as well. They all relate directly to what the user is trying to accomplish with this story.

The last two acceptance criteria, I have my doubts about. They seem to belong to different stories (a story for Recruiters/Employers accessing the CV database and a story for using the service from both mobile and desktop environment).

Title: Agile User Stories and acceptance criteria

Body:
I am writing some agile user stories and acceptance stories for the first time, and was hoping for some feedback from an experienced product manager or developer.

I only need to capture the main points in the acceptance criteria.

User Story

AS A registered jobseeker, I WANT TO create and edit my CV on the user interface on my mobile device SO THAT employers and recruiters can view my career summary and contact details

Acceptance Criteria

The user must sign into a registered account to create a CV

The user cannot save a CV unless all the mandatory fields on the form are complete

The user should be able to edit and delete the form at any time

Data from the saved form is stored in the CV database

Only registered Recruiters and Employers can view the users CV and contact details

The jobseekers user account is linked and synchronised on both mobile and desktop versions

Does this acceptance criteria sounds suitable for the given user story? Is there any way they can be more focused, and if so how?


问:
What are the most popular IDEs per language?
This has nothing to do with having a favourite editor or anything like that. I was just wondering, per language, what are the most popular Integrated Development Environments? Maybe a top 2-3 if there is some contention. (Perceived popularity is enough)

Thus Far:

C# - Visual Studio, SharpDevelop

Java - Eclipse, NetBeans, IDEA

Objective-C - Xcode

Delphi - RAD Studio

Object Pascal - Delphi, Lazarus

C, C++ - Visual Studio, Vim

PL/SQL - RapidSQL, Oracle SQLDeveloper

PHP - Eclipse, NetBeans, Nusphere PHPed

Actionscript (AS2, AS3) - FlashDevelop

Flex - Flash Builder 4

Python - Eclipse, IDLE

Perl - Padre

Common Lisp - Lispworks, Emacs

Ruby - TextMate

Haskell - Vim

Fortran - Vim

Visual Basic - Visual Studio

答:
Smalltalk - your own image.

So Squeak uses Squeak, Pharo uses Pharo, ...

I think only Gnu Smalltalk doesn't, where I suspect they use Emacs or Vim.

ContentLicense: CC BY-SA 2.5


问:
What principle of OOAD is this pattern breaking?
I'm trying to make a case for not putting the structure in the parent BaseModule class I've shown below.  I'm more for a Strategy Pattern, and minimizing inheritance in favor of has-a relationships, but I am not really sure of what principle of OOAD this pattern is breaking.

What principle of OOAD is this pattern breaking?

Potential Pattern:

```<code>public interface IStringRenderer
{
    string Render();
}

public class BaseModel : IRequestor
{
    public abstract void  Init();
    public abstract void Load();
}

public class BaseModule<TModel> : IStringRenderer where TModel : BaseModel
{
    public TModel Model { get; set; }

    public override string Render()
    {
        return
        string.Join(
            "",
            new string[]
            {
                "<header/>",
                "<main-container>",
                    "<side-nav>",
                        "<side-navigation/>",
                    "</side-nav>",
                    "<main-content>",
                        RenderMainContent(),
                    "</main-content>"
            });
    }

    public abstract string RenderMainContent();
}

public class MyModuleModel : BaseModel
{
    public List<int> Ints { get; set; }

            ...
}

public class MyModule : BaseModule<MyModuleModel>
{
    public override string RenderMainContent()
    {
        return
        string.Join(",", Model.Ints.Select(s => s.ToString()).ToArray());
    }
}
</code>```

Preferred Pattern (duplicated some code to be clear):

```<code>public interface IStringRenderer
{
    string Render();
}

public class BaseModel : IRequestor
{
    public abstract void Init();
    public abstract void Load();
}

public class MyModuleModel : BaseModel
{
    public List<int> Ints { get; set; }

    ...
}

public class MyModule : IStringRenderer
{
    public MyModuleModel Model { get; set; }

    public MyModule(MyModuleModel model)
    {
        this.Model = model;
    }

    public override string Render()
    {
        return
        string.Join(
            "",
            new string[]
            {
                "<header/>",
                "<main-container>",
                    "<side-nav>",
                        "<side-navigation/>",
                    "</side-nav>",
                    "<main-content>",
                        RenderMainContent(),
                    "</main-content>"
            });
    }

    public string RenderMainContent()
    {
        return
        string.Join(",", Model.Ints.Select(s => s.ToString()).ToArray());
    }
}
</code>```

There are parts of this pattern that I'm not trying to focus on, but instead I am thinking about where the 'structure', or the 'tags' are living.  In the first example they live in the parent, but in the second example they have been pushed into the derived class.

Right now, the examples are pretty simple, but something like 'side-nav' could potentially get complicated, and may need to be controlled by the child anyway.

I feel the principle here is that I don't feel like the 'tag' structure shouldn't be in the parent class as in the first example.  There are other things I've removed in my 'preferred version' -- namely the generics.  (Any suggested reading on good/bad for that choice is welcome).  Proponents of the first example's embedded structure like the fact that they can wield changes to large amounts of child classes.  I feel offering the flexibility to derived classes is the way to go, and if there needs to be a parent that parent only offers functionality and cross-cutting features, but does not bottle up canned structure.

答:
You can have the best of both worlds. In the BaseModule<TModel> class, when you implement (you typed override there, which is not correct) the Render() method, you can flag it as virtual. This way, child classes that need a basic set of tags can simply use the base class Render(), while child classes with more peculiar needs may override it.

About the generics, you are not using them in the BaseModule<>... unless you are using it in a constructor (not shown) that initializes the Model property for all derived class maybe? In that case they have their use here, since they constrain the type you can pass in and they un-burden the derived classes from having to initialize it themselves. This is more like a "framework" approach, where an abstract base class is used only to provide common but overridable functionality to derived concrete classes.


问:
"Is" prefix and "On" suffix as reasonable exceptions to a "non-hungarian" naming standard?
First, I believe I've seen this question discussed here before, but I cannot find it. My apologies if you do find it.

I'm starting a new project, and trying to figure out why IsResolved and/or ResolvedOn make more sense to me than Resolved. Obviously, when something is named "CompanyName" (for example), I'm fairly confident I'll test it as a string. However, when I see "Resolved", and I know the object it describes may not have a valid value for a resolution date, it bothers me that I have to inspect the type to determine how to test it: for undefined/null/etc. (as a date), or as a boolean value.

Is it reasonable to claim that Is and On typically do more than declare the variable type; they declare the intent? Or perhaps simply that it makes the code clearer for some other reason I'm not quite able to codify?

Arguing the other side, if I look at the type of Resolved, and see that it is a boolean, I will have my answer. Perhaps this is no different than knowing that I'll need to inspect a "Feasibility" variable to determine if it is an int, enum, or something else. (Although perhaps just that means "Feasbility" would be a sub-optimal name also.) And regardless, in the case of "ResolvedOn", I still have to inspect whether it is nullable to determine if I additionally need to inspect an "IsResolved" value. What is the point of the verbosity, encoding a second time in the variable name that which can be deduced from the type?

Please give me a hand understanding why Is[Property] and [Property]On make sense to me, although Hungarian in general does not. Or, explain why an exception like this wouldn't make sense?

Note: I primarily work with SQL, C#, and JavaScript.

答:
I'd say that Resolved is a boolean, as well as IsResolved. ResolvedOn could be a date.

However, one simply cannot depend on notation or name of a variable to determine its type, especially if one is going through someone else's code. Imagine variables named in different language (we had an exchange student from Mexico, and she named all of her variables in Spanish). Also, there is a variable CompanyCode, for example. Can you tell whether it's a string or an int?


答:
First of all, most of the allergic reactions to Hungarian notation stems from the fact that consistent application tends to result in very unnatural looking names. Occasional uses of prefixes or suffixes that suggest a certain type should not be considered to be Hungarian notation unless the name looks very forced.

What you are doing by using "IsResolved" or "ResolvedOn" instead of "Resolved" is disambiguating what information is conveyed by the name (i.e. what is represented by a class or object of that name, what does a thus-named function return).

To take a few more examples:

Company

CompanyName

Resolved

IsResolved

ResolvedOn

When reading code, "Resolved" would be the only one where I don't have an idea what it would represent and I would need to look it up. Context makes a difference and I am not claiming I am always correct, but "Resolved" is the only name in that list where I would not be able to tell at a glance if it looks to be used correctly.

Title: "Is" prefix and "On" suffix as reasonable exceptions to a "non-hungarian" naming standard?

Body:
First, I believe I've seen this question discussed here before, but I cannot find it. My apologies if you do find it.

I'm starting a new project, and trying to figure out why IsResolved and/or ResolvedOn make more sense to me than Resolved. Obviously, when something is named "CompanyName" (for example), I'm fairly confident I'll test it as a string. However, when I see "Resolved", and I know the object it describes may not have a valid value for a resolution date, it bothers me that I have to inspect the type to determine how to test it: for undefined/null/etc. (as a date), or as a boolean value.

Is it reasonable to claim that Is and On typically do more than declare the variable type; they declare the intent? Or perhaps simply that it makes the code clearer for some other reason I'm not quite able to codify?

Arguing the other side, if I look at the type of Resolved, and see that it is a boolean, I will have my answer. Perhaps this is no different than knowing that I'll need to inspect a "Feasibility" variable to determine if it is an int, enum, or something else. (Although perhaps just that means "Feasbility" would be a sub-optimal name also.) And regardless, in the case of "ResolvedOn", I still have to inspect whether it is nullable to determine if I additionally need to inspect an "IsResolved" value. What is the point of the verbosity, encoding a second time in the variable name that which can be deduced from the type?

Please give me a hand understanding why Is[Property] and [Property]On make sense to me, although Hungarian in general does not. Or, explain why an exception like this wouldn't make sense?

Note: I primarily work with SQL, C#, and JavaScript.


问:
Project life cycle management - Maven vs 'manual' approach
I have a question concerning the life cycle management of a/multiple project(s), more specific to the advantages/disadvantages of using technologies such as Maven.

Currently we work in a continuous-integration environment but lots of things still need to be manually performed (dependency management, deploying, setting up documentation, generating stats, ...). My impression is that this approach often leads to errors, miscommunications or things just are forgotten.

I know and have used Maven in the past but in smaller environments and I was always really enthusiastic about it. But I was wondering if someone could share some insights, experiences, pros, contras, ... about the use of Maven (or similar technology) in larger environments and for multiple projects.

I would like to use the suggestions made here to start the debate about moving to the next level in project management!

答:
If your application is tightly bound to something like an Apache Ant then you would need to do a lot of changes w.r.t. to the way you manage, build, deploy or even run test cases, though not necessarily all. With Maven you have a well defined life-cycle.

It is true that you would have to do things the way Maven asks you to do but there are sometimes ways around it (e.g overriding the standard project structure).

But once you have everything in place working with Maven, life would definitely be a lot simpler and manageable.

Maven comes with IDE support and many plugins so you can choose the plugins you need.

The only problem is the documentation. As it is still growing, it isn't the very best.

Hope this useful link helps. Maven, an Introduction and Comparison with Apache Ant.


答:
I believe the reason you think Is[Xxxxxxx] makes sense to you is due to your proficiency with SQL. Microsoft SQL has several IsXxxxxxxxx functions that makes life very easy for its users.

Your exposure to Microsoft SQL's IsXxxxxxxx type programming has shaped your thought process and you tend to lean toward using it outside of SQL. Why, because it does make sense. You probably question why other languages do not have similar built-in functions and you also probalby look to build similar IsXxxxxx functions when they are missing from the other languages you use.

I'm only speculating but your [Xxxxxxxx]On is probably just a natural progression of a similar thought to simplify properties that can either be On or Off.


问:
Models structure in PHP/MVC
I have some classes that are composed with ORM generated Models.

example1:
For example the Report.php (Model) is using a Document.php Model generated with ORM. Based on the document object a report is created.

I would like to know some name suggestions for the Report.php folder path.
It clearly belongs to the /Model folder but in what subfolder?

example2:
The CustomTagFilter.php will remove some html tags from a html string.

I wish to find a clear path name for this kind of Models. Any suggestions ?

```<code>/Models/[SUGGESTION]
</code>```

答:
I'd go with Transformers if I was in a whimsical mood:

/Models/Transformers/Reports.php
/Models/Transformers/CustomTagFilter.php
```

<p>or <code>Translators</code> if I was feeling more business-like:</p>

<pre class="lang-none prettyprint-override"><code>/Models/Translators/Reports.php
/Models/Translators/CustomTagFilter.php
</code>```

Title: Models structure in PHP/MVC

Body:
I'd go with Transformers if I was in a whimsical mood:

/Models/Transformers/Reports.php
/Models/Transformers/CustomTagFilter.php

or Translators if I was feeling more business-like:

/Models/Translators/Reports.php
/Models/Translators/CustomTagFilter.php


问:
How should I behave as a developer in a project that's headed for failure?
I am a developer in a 5-member team and I believe our project is headed for disaster. I'll describe why in a moment, but my question is: how should I behave?

The deadline is in 1.5 months, and I feel no matter what we do, this project will fail. I'm of the opinion that we should just terminate the project and stop wasting our time, but politically I think it's impossible for our manager to do that.

What should I do in this case? Should I put in extra effort, or should I just take it easy? And what should I say to the manager?

Reasons this project is headed for failure:

With deadline approaching many of the must-have features are not finished

Application is unstable and very difficult to use

System is very convoluted, code very hard to understand, very difficult to change - Data model is too driven by a complex relational database (100+ tables)

Unclear leadership; the manager responds to new information with major changes

Almost no automated tests or unit test

Heavily depends on other systems, but no integration tests yet

In fact, we actually just inherited this project (along with the mess) around 1-2 months ago from another dev team under the same manager, who has worked on it for a few months.

答:
Since your manager knows it will probably fail, you're better off than most. I would consider working with the manager and see if there are any parts/features of the app that can be excluded.

Too often we think every client request is a 'deal killer' and go out of our way to promise the delivery. Until someone works with the client and probes deeper, you may not be able to make these decisions. If you're not able to do this, still try to deliver what you think is most important. Sometimes it's easier to ask for forgiveness than permission.


答:
Communicate your concerns in the most concise and non-confrontational way possible up the management ladder. Summarize the risks, but do not impose your conclusion on them.

Management must always have the choice of what to do, but it is your job to assess and communicate the situation. Use email, so as to leave a paper trail when things go south.

Having done that, keep working on the project in good faith.

Keep in mind, you may not know everything there is to know about the project, its backers, and financial decisions behind it. Management decisions that seem stupid to you might actually be based on smart reasoning that isn't visible to you.

Title: How should I behave as a developer in a project that's headed for failure?

Body:
I am a developer in a 5-member team and I believe our project is headed for disaster. I'll describe why in a moment, but my question is: how should I behave?

The deadline is in 1.5 months, and I feel no matter what we do, this project will fail. I'm of the opinion that we should just terminate the project and stop wasting our time, but politically I think it's impossible for our manager to do that.

What should I do in this case? Should I put in extra effort, or should I just take it easy? And what should I say to the manager?

Reasons this project is headed for failure:

With deadline approaching many of the must-have features are not finished

Application is unstable and very difficult to use

System is very convoluted, code very hard to understand, very difficult to change - Data model is too driven by a complex relational database (100+ tables)

Unclear leadership; the manager responds to new information with major changes

Almost no automated tests or unit test

Heavily depends on other systems, but no integration tests yet

In fact, we actually just inherited this project (along with the mess) around 1-2 months ago from another dev team under the same manager, who has worked on it for a few months.


答:
Keep a paper trail (e.g. diary, saved emails, etc).  Only include facts and objective observations.  Leave all conclusions up to whomever (if anyone) reads what you've written.

As a developer, if you're not viewed as an obstacle to the project you're likely to come out fine from the finger-pointing that will no doubt happen.  Your manager may not be so lucky, but that's not relevant here.

Just on general principles, update your resume and make sure you occasionally meet with other devs outside your company.  If you're not part of any local developer groups, go join 2 or 3.  It takes years to build up a network of friends and acquaintances but in the long run it's worth it.  Be sure to look on it as a 2-way street - if you can help fill an opening in your company with someone capable, that's just as good as someone helping you find a job.


问:
Exclude the zero in the given data in Haskell
I have a list of integers.
Also, I have a function which returns True when the element is non-zero, and returns False when the element is zero (let's call it FUNCTION1).

So, how to define another function (using FUNCTION1), which will give us a new list and only include the non-empty elements?

For example, we have [1,2,3,0,6,0], and we want [1,2,3,6]

答:
What you're looking for is the filter function.

To filter out 0 from a list, you would say:

```<code>filter (\x -> not (x==0)) [1,2,3,0,6,0]
-- or better yet
filter (not . (==0)) [1,2,3,0,6,0]
-- or best of all
filter (/=0) [1,2,3,0,6,0]
</code>```

If you want, you can substitute the anonymous function with your named function. It should work the same:

```<code>filter Function1 [1,2,3,0,6,0]
</code>```

Body:
What you're looking for is the filter function.

To filter out 0 from a list, you would say:

filter (\x -> not (x==0)) [1,2,3,0,6,0]
-- or better yet
filter (not . (==0)) [1,2,3,0,6,0]
-- or best of all
filter (/=0) [1,2,3,0,6,0]

If you want, you can substitute the anonymous function with your named function. It should work the same:

filter Function1 [1,2,3,0,6,0]