答:
Consider two options.

Validate everything on the server, at all times. Suppose you pay for 2 extra weeks of developer time (e.g. $10k), and e.g. $100/mo extra for more computing power. Nothing interesting happens.

Do not validate input and save the money and time. Then someone mischievous steals a secret, finds out that the server side allows to do anything, and wreaks havoc costing you $N. To prevent this in the future, you belatedly implement option 1.

If $N is sufficiently small, it may be rational to go with option 2. But I greatly doubt that for a project that hires ~200 developers this might be true.


问:
Shuffle/Randomize a collection without knowing the number of items?
Let's say I have a sequence of items of unknown length, n. I want to randomize the order of this sequence without having to go through the entire sequence. Are there any algorithms that can do this?

Example:

I have 10 items in my sequence: A B C D E F G H I J (though I don't know that I have 10). At the end of my randomization it would have ended up as E G F B A I C D J H.

If I only wanted to know the first 3 random elements, I would get E G F, and since G is the furthest element in the original sequence, I would never have to read the sequence past G.

My algorithm would, somehow, look at A and realize that it randomly belongs past the first 3 requested elements, it would then look at B and realize the same, ..., it would look at E and realize that it needs to randomly be the first element so it adds it to a return buffer as element 1, then F randomly should be the third element, so it adds it to a return buffer as element 3, then it hits G and adds that to the return buffer as element 2 and it completes. It never even looks at where H, I, or J should go.

答:
A common way to read data coming into the computer is to buffer it from a stream.

Streams sometimes have an undefined length.  All we know for sure is we can "get next character from stream".

Normally we'd add the character from the stream to the end of the buffer (think FIFO queue).

The size of the buffer doesn't necessarily have to be the size of the stream, IF we are simultaneously emptying the buffer (i.e., reading from it to pass the data somewhere else) at the same time.  Your stream might produce a single character at a time, but you might want to "buffer them up" until you have a complete line.  You could pass a 100MB text file through a 1KB buffer as long as no single line in the file was over 1,024 characters long.

Here's the clever bit

What if, instead of appending the next character from the stream to the end of the buffer, we instead randomly insert it anywhere in the buffer?

An important limitation

No item can be displaced from its original location by more than the buffer size.  If you have a buffer size of 200 and you have 1,000 elements, you will never "randomly" pick the 999th element first.  Having a really big buffer would help.

Ideally, having a buffer bigger than your input stream would reduce this to a much simpler problem.

ContentLicense: CC BY-SA 3.0


问:
Where should i put the WebAPI
I've just started the project and I have this sort of parts in my solution

MyApp.Web MVC Web Application

MyApp.Data Class Library

MyApp.Domain Class Library

MyApp.Service Class Library

MyApp.Utility Class Library

So I wanted to have webapi in my application, and my question is where should I put the webapi codes.
in separate part like MyApp.API or in Data or Service part.

thank you.

答:
You should absolute not put it in the data layer. That would be weird because none of the dependencies you need for web api are, and should not be, present in the data layer.

It is fairly common to have mixed mvc and web api into the same assembly and it has the advantage that deployment is easier.

If you want a more clean approach. Clean in the sense that we keep the number of unrelated dependencies to a minimum in each project, you can introduce a seperate assembly with web api only. This will sligtly minimize the risk of running into dll hell but complicate deployment slightly.

Title: Where should i put the WebAPI


问:
How to better define SRP and "wholesome" objects?
Assume you have a class. It can really be any class that defines a domain concept like an employee, a product on an e-commerce site, or a car. One of those examples that are oldies but goodies. According to the SRP, that object should be responsible all of "its" things.

I would consider an employee taking a lunch, a product going on sale, or a car accelerating all examples of things that "belong" to those examples. This can include other categorical areas of concern such as affecting the database, firing an event, or changing a simulation while the source object is still responsible for the overall outcome.

The struggle I see there is you either have very flat architectures where an object can (potentially) touch anything or you have rather verbose layers of abstraction that the objects can reasonably rely on. However, the latter feels more like giving up responsibility the more layers there are between a thing and what it's trying to do.

I really don't know where I stand on this, personally. I'd quite likely compromise by splitting the baby, as it were, in most of those scenarios which feels some kind of wrong no matter what I do. Being the middle of 2015, has there been any development toward these kinds of problems that give good guides on where one should be?

I understand the composition over inheritance advice in object construction but when you're formulating ideas and not building objects yet, is there a clear "good" way to go about this?

Edit: So, with the potential duplication of Is SRP (Single Responsibility Principle) objective?, I don't think that's the case. I'm not implying it is or even should be objective. I'm curious if there have been improvements in schools of thought around this subject. I get it's subjective. To illustrate: I don't think anyone would say writing software has one, objectively correct method, but SOLID is often given as a guide to write "good" software. Similarly, given SOLID, where is the thought-space around the SRP and object ownership?

答:
I think we've learned a lot since SRP was introduced, but in a more indirect and general way due to the changes in the way software development projects are managed. SRP is a principle that wasn't intended to have a set of strict rules that could be blindly applied to all situations. It depends. There are some general rules that experience has taught us that code written with SRP in mind, tends to be easier to work with. Anything can be taken too far. Programming life would be so much easier if we just put every method in it's own class every single time no matter what. Bad idea.

The notion that if SOLID principles are applied correctly, then two different developers would probably solve the same problem the same way, detracts from the purpose-more robust code. I think they'll be very close, but there should never be an expectation of being a perfect match. What should happen, is an average developer should be able to look at both solutions that applied the SOLID principles "correctly" and be able to understand what the code is doing to the extent that she can alter and extend it as needed.

I would also argue that if two developers worked with the same user/client, for the same length of time, going through all the iterations and steps in an identical project, they would probably end up with similar designs. We not only would expect a novice developer to fail to produce a similar application as a senior developer, but we would be able to tell the difference very easily. We also would know which one is easier to work with - isn't that what it's all about?

It's the requirements that should drive the level of complexity and abstraction and not solely based on a given developer's application of the SOLID principles. If I build a car driving simulator and base acceleration purely on the specs/averages provided by some car rating service that uses identical conditions to do their testing, I wouldn't need a lot of abstractions for this functionality. However, if my simulator's requirements need to involve changing road conditions, elevation, weather conditions and possibly wear and tear on the tires, most developers would suggest not putting all this code in the Car class. If you did and decided to have different types of cars, tracks, seasons, etc., they would see it as a big mess that has now violated SRP. Not because of how they individually build things, but mainly because of the change in requirements.


问:
How to manage tailored/branded web tools?
We produce a number of analysis tools which we re-brand and customise for other businesses to include in their websites.

The tools are typically product comparison, data/trend analysis and report production (in a very particular sector). At present these tools run as a single instance in house, our clients redirect there traffic to us with a URL param specifying the client for branding and customisation.

Up until now we've been using an MVC approach with XSLT views. If a customer wants customisation we add switches in the MVC and/or imports&override in the XSLT. This was manageable for a while but now we have so many versions and customisations for sooo many clients, getting stable builds out the door is becoming a nightmare

We are looking to move to MS asp.mvc3 with using Razor for our views but before this I am wondering are there any standard practices or patterns for developing and managing the kind of mess we are sliding towards?

Cheers,
T

答:
This may not be the answer you're looking for, but are you sure you are attacking the root cause of your problem? It sounds a bit like you are trying to solve a symptom. I get the feeling there is a much deeper issue.

I would suggest investing half an hour with your team into the 5 Whys to get closer to the root cause. The results are often revealing and surprising, and allow you to better solve the problem instead of just the symptom.

Once you know what the real root cause of your issue is, you can look, with the team, at ways to solve it. Nobody is better at tracing the problem and thinking about fixes than the team, as they experience and work with this all the time. It can be hard to find the right solution - try your best and always retrospect to see whether you can do better.

(That said, there's obviously nothing wrong with looking for inspiration for solutions outside the team.)

ContentLicense: CC BY-SA 2.5


答:
tl;dr Your decisions on how much to abstract should be dependent upon your business problem to choose how much of the baby to split.

Understanding relationships and how to define them properly without creating 'god' objects is a common problem when architecting solutions.  Your idea on compromise is spot on when you are trying to accomplish something and the problem then becomes, what, when, and why do I compromise.  First you need to get a good feel for defining relationships properly, SOLID design as it were.

For example, you stated an employee "owns" his lunch break, a product "owns" its sale, and a car "owns" its acceleration, but are these accurate for your business problem.  An employee might need to request that he can take his lunch break from a BreakManagement system, while a product might get told its on sale from a CampaignMarketing system, or a Car might accelerate the wheels, but not its acceleration relative to the ground without the help of the a Traction calculation.  Really, you need to be able to see the purpose of the system you are trying to build and what entities are required and the relationships between those entities.

Its easy to see that an employee might need to rely on a break management system and that dependency for a system for managing employees, but that might be an invalid relationship for a system that simply keeps track of an employee's hours.

Title: How to better define SRP and "wholesome" objects?

Body:
Assume you have a class. It can really be any class that defines a domain concept like an employee, a product on an e-commerce site, or a car. One of those examples that are oldies but goodies. According to the SRP, that object should be responsible all of "its" things.

I would consider an employee taking a lunch, a product going on sale, or a car accelerating all examples of things that "belong" to those examples. This can include other categorical areas of concern such as affecting the database, firing an event, or changing a simulation while the source object is still responsible for the overall outcome.

The struggle I see there is you either have very flat architectures where an object can (potentially) touch anything or you have rather verbose layers of abstraction that the objects can reasonably rely on. However, the latter feels more like giving up responsibility the more layers there are between a thing and what it's trying to do.

I really don't know where I stand on this, personally. I'd quite likely compromise by splitting the baby, as it were, in most of those scenarios which feels some kind of wrong no matter what I do. Being the middle of 2015, has there been any development toward these kinds of problems that give good guides on where one should be?

I understand the composition over inheritance advice in object construction but when you're formulating ideas and not building objects yet, is there a clear "good" way to go about this?

Edit: So, with the potential duplication of Is SRP (Single Responsibility Principle) objective?, I don't think that's the case. I'm not implying it is or even should be objective. I'm curious if there have been improvements in schools of thought around this subject. I get it's subjective. To illustrate: I don't think anyone would say writing software has one, objectively correct method, but SOLID is often given as a guide to write "good" software. Similarly, given SOLID, where is the thought-space around the SRP and object ownership?


问:
Why does Objective-C store objects on the heap instead of on the stack?
I have a basic understanding of what a "stack" and "heap" are. You use a stack to store items in memory that should be read and/or removed in a last-in-first-read/removed manner. To steal another example from someone else's Website, you use it to perform arithmetic operations involving PEMDAS. You also use a stack to store return addresses for functions. Like a heap, the CPU uses a pointer to find the item to be read and/or removed.

You use a heap when you don't need the computer to store objects in a sequential order in memory.

My question is, what's the deal with the * pointer in Objective-C? Local variables in a method are going to get deallocated when the method's done anyway, so why not just use the stack instead?

I'm going to go out on a limb here and say that the short answer is that because stacks have a limited memory, Objective-C wants to keep its stack usage to a minimum.

答:
The main reason is that just because you're done with a local reference to an object doesn't mean you're finished with the object itself.

For example, if your function creates an object and adds it to a pre-existing collection that belongs to a broader scope, then the object has to be on the heap; anything on the stack gets trashed after the function returns, but the collection (and all the objects it contains) is still valid.

This is just one of many scenarios where you would need to keep an object around after the function that first created it returns.  (Also consider the case of a function whose return value is a newly-created object, for example...) In all such cases, you need to keep the value in a non-ephemeral portion of memory.

Some compilers can perform a special trick known as escape analysis, where they analyze the object's lifetime and if they can prove that the object will not outlive its function, they rewrite the code that creates it to place it on the stack, making creation and cleanup cheaper.  But this is a pretty advanced (and very difficult) piece of analysis; it's much simpler to just all have objects allocated on the heap by default.


问:
good books to get deep into PHP
I am a PHP developer with ~3 years experience.  I want to get deeper into PHP and really understand more low level constructs/functionality.  I have mainly done frontend web dev and a little php cron jobs.  I want to learn more about stream contexts, closures, process forking, etc.

The book I've found that seems closest to this is  Expert PHP and MySQL (Wrox).  I also found Pro PHP.  I know there has to be more out there but I can't seem to find anything.

Suggestions?

答:
I want to suggest something else entirely: Become accustomed to learning from non-book resources. First of all, the three things you have mentioned in your question that you want to learn more about differ substantially. Stream contexts are part of the core php API, and can be thought of as a "framework feature". Closures are a "language feature" (just another name for anonymous functions, really). Finally, process forking is more of an "OS feature", mostly available in *NIX flavor OS'es.

So what kind of book (with less than 1000s of pages) would include meaningful insights for these topics? I haven't read "Expert PHP and MySQL" but the name suggests that its focus is on something else.

So I want to suggest that you start reading the PHP language reference. It has all the details about all the topics there are. If some general computer science terms are unknown to you, you ask a question on SO or read up on it on wikipedia. If you find a topic in the reference that you don't understand or don't see the point of, you skip it, but make a mental note of the topic's existence so that you can return to it at a later time. The pro's of this approach are that you yourself can choose the focus of your study and do not have to rely on finding a book that covers your immediate interests. Furthermore, online documentation is usually more up-to-date than books, and online docs are also free. Granted, this approach takes a little getting used to and maybe also requires better analytical skills, but in the long run it is a much faster way to learn.

Afterall, in todays market, who has the time to wait for a book to arrive?

Title: good books to get deep into PHP


问:
Should I make my own exceptions, or co-opt similar exceptions for slightly non-standard purposes?
This is a general design question, but I'm focusing on C# and .NET because those are the languages I'm working with right now.

Should I create my own, new exception classes, or co-opt existing framework exceptions for slightly different purposes?

For example, I'm finding myself needing an exception that indicates a member (that is, of a type for example) was expected, but has not been found while reading an assembly using Mono.Cecil. The base class library defines the exception MissingMemberException, which seems to communicate exactly what I want, but the description says:

The exception that is thrown when there is an attempt to dynamically
  access a class member that does not exist.

Which doesn't fit exactly, because I'm not dynamically accessing the member, but rather working with the assembly passively.

答:
In general

Subclassing exceptions is a good idea to group the exceptions into the families or groupings that they belong to. It also allows client code the opportunity to handle exceptions based on specific errors or more generally. I usually divide the tree somewhere near the root between the logical and runtime errors (e.g. in C++ the std::runtime_error vs. std::logic_error).

Being able to differentiate between the system exceptions and your application's exceptions is also a good idea. It would be odd if the client code is watching for an system failure of some sort but catches your (via a base class) code's logical error.

Given this case and C#

C# has a rich and large exception hierarchy - I wouldn't try pick up a base class too deep into it. Following on your example, it sounds like your are throwing a logical error (or at least an application error), so the base class or even just that exception would hint at a system error. The exact exception can be debated, but I think in this case it is not a good choice.

Hierarchy

I would build a hierarchy that allows you to distinguish between system and application errors and then further between runtime and logical errors. Do not be afraid to use inner exceptions - catch the system error and wrap it in something more meaningful given the context in which it is being thrown. Don't go overboard, focus on what would be key exceptions. Exceptions can have unique textual descriptions associated with them - use them to give a user even more detail or hints at what to do to correct the problem.


问:
Are string characters assigned a numerical value in context of how they are assigned in a programming language?
For context I am fairly new to programming after returning back to it after programming a number of years ago... I was reading Bjarne's intro programming with C++ and was wondering if alphabetical string characters are assigned numerical values for the purpose of comparison. For instance in this example from the book Bjarne shows that the strings are compared through analyzing the first letter of the input for the strings. From what I gather the language has been coded to essentially give the string characters a value of what I am assuming is 1-26 corresponding to the standard US alphabet to compare the letters.

For instance:

```<code>int main()
{
    cout << "Please enter two names\n ";
    string first;
    string second;
    cin >> first >> second;
    if (first<second)
        cout << first <<"is alphabetically before"<< second <<'\n ' ;
    return 0;
}
</code>```

答:
It depends on the programming language you use and on the compiler that you are using.

The C and C++ languages define very little. All that you can rely on - from the language definition - is that the digits '0' to '9' have sequential values. You cannot even portably rely on 'a' to 'z' having sequential values, not from the C and C++ language definition alone.

A specific implementation will usually give you more guarantees. For example, most C and C++ implementations guarantee that your character set is a superset of ASCII (google for ASCII for more information). Another example, the compilers shipping with Xcode guarantee that single byte C and C++ strings contain characters in UTF-8 format (again, use google). Languages like Java give much more guarantees as part of the language definition.

But as a note, using the codes is absolutely not enough for meaningful comparison and ordering. Useful ordering is complicated, and you just hope that the operating system supplies code that helps you, because on your own you have little chance. For example, naïve code will sort "Bag" < "Coat" < "anorak", and "Chapter 1" < "Chapter 10" < "Chapter 19" < "Chapter 2". Not what a user will find helpful.


问:
How to make a large codebase easier to understand
Suppose that I am developing a relatively large project. I have already documented all my classes and functions with Doxygen, however, I had an idea to put a "programmer's notes" on each source code file.

The idea behind this is to explain in layman's terms how a specific class works (and not only why as most comments do). In other words, to give fellow programmers an other-view of how a class works.

For example:

```<code>/*
 * PROGRAMMER'S NOTES:
 *
 * As stated in the documentation, the GamepadManager class
 * reads joystick joystick input using SDL and 'parses' SDL events to
 * Qt signals.
 *
 * Most of the code here is about goofing around the joystick mappings.
 * We want to avoid having different joystick behaviours between
 * operating systems to have a more integrated user experience, since
 * we don't want team members to have a bad surprise while
 * driving their robots with different laptops.
 *
 * Unfortunately, we cannot use SDL's GamepadAPI because the robots
 * are interested in getting the button/axes numbers, not the "A" or
 * "X" button.
 *
 * To get around this issue, we created a INI file for the most common
 * controllers that maps each joystick button/axis to the "standard"
 * buttons and axes used by most teams.
 *
 * We choose to use INI files because we can safely use QSettings
 * to read its values and we don't have to worry about having to use
 * third-party tools to read other formats.
 */
</code>```

Would this be a good way to make a large project easier for new programmers/contributors to understand how it works? Aside from maintaining a consistent coding style and 'standard' directory organization, are there any 'standards' or recommendations for these cases?

答:
This is awesome.  I wish more software developers took the time and effort to do this.  It:

States in plain English what the class does (i.e. it's responsibility),

Provides useful supplementary information about the code without repeating verbatim what the code already says,

Outlines some of the design decisions and why they were made, and

Highlights some of the gotchas that might befall the next person reading your code.

Alas, many programmers fall into the camp of "if code is written properly, it shouldn't have to be documented."  Not true.  There are many implied relationships between code classes, methods, modules and other artifacts that are not obvious from just reading the code itself.

An experienced coder can carefully craft a design having clear, easily-understandable architecture that is obvious without documentation.  But how many programs like that have you actually seen?

ContentLicense: CC BY-SA 4.0


答:
In my view custom exceptions make sense only in 2 cases:

1) you're developing an Api

2) you use it in your code to recover from a failure.

In any other scenario, built in exceptions should be sufficient.

In your case you could use InvalidArgumentException

Title: Should I make my own exceptions, or co-opt similar exceptions for slightly non-standard purposes?

Body:
This is a general design question, but I'm focusing on C# and .NET because those are the languages I'm working with right now.

Should I create my own, new exception classes, or co-opt existing framework exceptions for slightly different purposes?

For example, I'm finding myself needing an exception that indicates a member (that is, of a type for example) was expected, but has not been found while reading an assembly using Mono.Cecil. The base class library defines the exception MissingMemberException, which seems to communicate exactly what I want, but the description says:

The exception that is thrown when there is an attempt to dynamically
  access a class member that does not exist.

Which doesn't fit exactly, because I'm not dynamically accessing the member, but rather working with the assembly passively.


问:
Which is better: to include HTML inside PHP code or outside it?
Look at this:

```<code><?php
echo "Hello World";
?>
<br />
<?php
echo "Welcome";
?>
</code>```

And now look at this:

```<code><?php
echo "Hello World";
echo "<br />";
echo "Welcome";
?>
</code>```

Which one of the above examples is considered to better (at least from performance point of view)?.

I know the examples are trivial but I want to follow good practice habits from the beginning so when I have more and more lines they would not affect the performance or whatever in a negative way.

答:
One of the best features of PHP was it is designed to be embedded in HTML. It is usually used in creating templates. It makes your code easier to read and maintain, because it separates the PHP code from HTML.

But if your only printing a static page like "Hello World!" it's a bad idea.


问:
How can I keep browser URL secret when editing data?
Suppose,
There is a user list.

```<code>Edit
Edit
</code>```

When a system user clicked to edit a user info. Then it goes to url to browser like as

http://abc.com/user/5

He can manually replace 5 to 155 and edit(update) the user info. It is a problem to me. How can I remove this problem?

I have an idea: Calling the edit page by ajax. So that the number will be hidden. Is there any good idea?

答: You can't just let your users edit other peoples account. If you are thinking that your problem is in URL, then I think you're wrong. If you have a proper user authentication and session handling this wouldn't occur. Then if you really don't like having readable values in your URL, you could try to hash or encrypt them.</p>

Body:
Suppose,
There is a user list.

```<code><a href="user/5">Edit</a>
<a href="user/6">Edit</a>
</code>```

When a system user clicked to edit a user info. Then it goes to url to browser like as

http://abc.com/user/5

He can manually replace 5 to 155 and edit(update) the user info. It is a problem to me. How can I remove this problem?

I have an idea: Calling the edit page by ajax. So that the number will be hidden. Is there any good idea?


答:
The answer is of course "it depends," but given your use case, I would say no. Here's why:

C# is a wonderful - scratch that, the best - object-oriented language around. It is so good, in fact, that I will sometimes get caught up trying to implement a fanatically purist vision of what began as a simple project. That doesn't happen to me so much when writing JavaScript or Objective-C or PHP code.

When I get in this "mode," this sort of paralysis, one of the symptoms can be an obsession with exception handling and generics and meta-programming. Sometimes all three together. It is far more likely to be an issue when I am working on something new, relatively unknown, or with shoddy specifications and goals. Rather than bogging myself down in the implementation details, I think, why try to create something that can accommodate most of the scenarios I reasonably anticipate? Then, when I get around the getting the details, the foundation will be laid and I will write a bunch of stubby little methods, and so on. Maybe somebody else will work on the UI code, I'll just provide them these nice services and these contracts...

Unfortunately, that has  yet to happen to me. What tends to happen is that I start down this path working on "infrastructure" - things like:

Writing my own IoC container interfaces or otherwise screwing around with Castle.Windsor

Determining how I am going to handle type mapping in the application

Writing control flow logic for abstract base classes that resemble Interceptors and wrapping calls to abstract members with exception handling

Creating abstract base classes for IRepository, IUnitOfWork, IDomainService, ICrossCuttingValidation, etc.

Trying to describe a hierarchical object model for something whose very nature denies such a meta- approach (like IFrameworkException)

When you get hung up on whether an exception's description is precise enough for your tastes, you are really denying some other critical feature from being implemented. The nature of the exception is also telling - it is not an event-driven exception, it occurs evidently far from any input methodology (like a UI or a pipe or something) and is probably deterministic in nature - as in, you can't predict what a user will input, but you can predict which assembly you choose to load or whatnot.

By the way, if the description bothers you so much, can't you write an extension method to override it in the appropriate scope?

So this is really just me kind of projecting my own over-abstraction and analysis paralysis onto you but I think it may be appropriate. I would say that to stay on the safe side, only subclass an Exception when:

You have actually experienced a runtime exception that you are seeking to handle in general

The runtime exception is not something that you could reasonably rule out at design time

The exception is not already well-covered by the huge existing number of Exception subclasses

You actually have an idea in mind of how  you want to handle the exception OR if not, only because it is so complicated that you need to think about it and get back to it

Your idea goes beyond changing its metadata, its scope, its inner exception, etc, and deals more with the underlying object or event producing the exception and/or the means of actually dealing with it

You have already written or are not responsible for the majority of the input-facing side of things like the UI


问:
Javascript Password Security
I am having difficulty with the answer provided here, but I couldn't understand how to implement it. My code is pretty much identical:

```<code><script language="javascript">
  function check(form) {
    if(form.userName.value == "User" && form.userPass.value == "averyobviouspassword") {
      window.open('testok/menu.html')
    }
    else {
      alert("Wrong Password Or Username")
    }
  }
</script>
</code>```

The problem with this is, if you were to Inspect Element on the page, you can plainly see the password. I'm not looking for other solutions like a SQL database, because this is just a test website. The solution I thought might work was this:

```<code>if(hash(enteredPassword) == storedHash)
</code>```

I just don't know how to implement it.

答: Login pages using JavaScript is actually not advisable. It is totally unsecured. Most of login pages are done in server-side using PHP, ASP.NET, Node.Js, etc. and not in client-side which the code is visible for the users.</p>

Title: Javascript Password Security


答:
I prefer this structure:

MyApp.Web // UI

MyApp.Core // Context

MyApp.Domain

MyApp.Service

MyApp.Api // WebAPI

MyApp.Utility // it's depended on your case !, I didn't use this layer so far.

If you use DI in your project, you should use Custom Controller Factory, so I prefer WebAPI as separated layer and create specific Custom Controller Factory, instead of something global that covering MVC Controller too.

Title: Where should i put the WebAPI

Body:
I've just started the project and I have this sort of parts in my solution

MyApp.Web MVC Web Application

MyApp.Data Class Library

MyApp.Domain Class Library

MyApp.Service Class Library

MyApp.Utility Class Library

So I wanted to have webapi in my application, and my question is where should I put the webapi codes.
in separate part like MyApp.API or in Data or Service part.

thank you.


问:
White Boards -- Who Uses Them?
So as both a full-time programmer and hobbyist as well (developing my own things for personal use and maybe to sell one day), I feel that me purchasing a big white board to hang in my room at home or something would be very useful.

Does anyone here have one as well, to use for high level designs (UML, Architecture, etc.) and things like very early UI mockups, etc.?

If you guys do have them, which ones have you bought? I can't seem to pin one that would be good for home use and I'm not sure of the pricing/other things.

Thanks!

答:
I find they are most useful for discussing technical issues with other people. Sometimes it is better to draw a diagram, make a list, etc than to just talk through a problem.

So... installing one at your home may not be much help if its only going to be you that is working at that location. If that is the case you might consider investing in a few notebooks instead. That way it gives you the same benefits of working things out visually, but you can keep track of old notes. Plus, if you are the only person working there, you don't need to draw up big diagrams where everyone can see them.

Title: White Boards -- Who Uses Them?


答:
This can be partly because it is hard for a single programmer to write it, as each individual understands only their part of project.

Sometimes you can get this info from the notes of the project manager , but that is all you will get, as they will rarely rewrite their notes in this format.

Title: How to make a large codebase easier to understand

Body:
Suppose that I am developing a relatively large project. I have already documented all my classes and functions with Doxygen, however, I had an idea to put a "programmer's notes" on each source code file.

The idea behind this is to explain in layman's terms how a specific class works (and not only why as most comments do). In other words, to give fellow programmers an other-view of how a class works.

For example:

```<code>/*
 * PROGRAMMER'S NOTES:
 *
 * As stated in the documentation, the GamepadManager class
 * reads joystick joystick input using SDL and 'parses' SDL events to
 * Qt signals.
 *
 * Most of the code here is about goofing around the joystick mappings.
 * We want to avoid having different joystick behaviours between
 * operating systems to have a more integrated user experience, since
 * we don't want team members to have a bad surprise while
 * driving their robots with different laptops.
 *
 * Unfortunately, we cannot use SDL's GamepadAPI because the robots
 * are interested in getting the button/axes numbers, not the "A" or
 * "X" button.
 *
 * To get around this issue, we created a INI file for the most common
 * controllers that maps each joystick button/axis to the "standard"
 * buttons and axes used by most teams.
 *
 * We choose to use INI files because we can safely use QSettings
 * to read its values and we don't have to worry about having to use
 * third-party tools to read other formats.
 */
</code>```

Would this be a good way to make a large project easier for new programmers/contributors to understand how it works? Aside from maintaining a consistent coding style and 'standard' directory organization, are there any 'standards' or recommendations for these cases?


问:
Avoid data manipulation by user
I have a C# program (could be any programming language) that saves data to a file on a memory (hard disk, USB drive, etc.). The program uses this data for monitoring its operation time, but it could be any purpose.

When the program is started, it reads the data from the file so it knows how long it has been operating before. It updates the data in the file every minute, so there is a failure of maximum 1 minute if the program is not shut down properly.

My problem is a quite general question: How can I prevent the user from manipulating the file?

I want to avoid that someone edits the operation time while the program is not running, or at least I want to be able to detect manipulation.

I though of a checksum first, but I also need to prevent that from manipulation.

The user can replace the current files by backups every time, thus the files themselves are not save if he knows where to look.

Therefore I need to store data at a location that is not easily editable. On a windows system, this could be the registry. Alternatively I could create a hidden system file in a special directory. However, I think the only chance is to hide the file or any information about the data from the user.

The user could replace the whole operating system including all data by an image. Therefore also a hidden location is not safe, but a) I cannot avoid this risk, and b) the user would need special equipment and knowledge, so the system is safe to most users.

Any other ideas how to secure data on a typical computer?

答:
"secure data on a typical computer". From your comments it's clear your victims are not using "typical computers" but are slaves to an irrational IT department which you're a part of.

The only way to do what you want is not to store the data on the computer at all, but to store it on another computer somewhere on the network that your users have no access to. Of course that requires that all their computers are networked to a LAN, but you're going to have that anyway as no doubt you've found out that network admins can remotely start, shut down, and reboot computers and forcibly load and remove software on them and are regularly pestering your victims with that just to annoy them as well as for legitimate reasons (yes, I've worked in companies with such IT departments more than I care to remember, I have experienced it from both sides, though I've never been one of those admins I've worked in the same departments they were part of).

Title: Avoid data manipulation by user


答:
I don't tend to use a white-board when working alone, but as a communication / collaboration tool when working with others.

Some use them as Kanban boards, and for other similar tracking purposes as well.

As such, if I was working in a one-person shop, I would not likely put one up.

Title: White Boards -- Who Uses Them?

Body:
So as both a full-time programmer and hobbyist as well (developing my own things for personal use and maybe to sell one day), I feel that me purchasing a big white board to hang in my room at home or something would be very useful.

Does anyone here have one as well, to use for high level designs (UML, Architecture, etc.) and things like very early UI mockups, etc.?

If you guys do have them, which ones have you bought? I can't seem to pin one that would be good for home use and I'm not sure of the pricing/other things.

Thanks!


问:
Is it safe to directly access superglobals with isset()?
I understand that one should always try to avoid direct access to superglobals to put values from superglobals into variables, eg.:

```<code>$name = filter_input(INPUT_POST, 'name');
//instead of
$name = $_POST['name']; // not safe
</code>```

My question if it is safe to use isset() to test if a superglobal is present, eg:

```<code>if (isset($_POST['name')) {

}
</code>```

I personally do not understand why this would not be good practice, but I am not that advanced in programming.

(Recently I started using Netbeans, and it gives me a tooltip recommending to change this code. Maybe the message is not entirely correct, but I would rather know for sure. I have not found a good answer anywhere else.)

答:
It is safe to use isset function in super globals. It is very effective to trigger events for a specific submit event. It only checks if the global variable is existing and will not trigger any damage such as XSS/Code/SQL injection.

I think the recommendation you received to change the code is that you need to...

```<code>$name = filter_input(INPUT_POST, 'name');
</code>```

then...

```<code>if (isset($name)) {
}
</code>```

Body:
It is safe to use isset function in super globals. It is very effective to trigger events for a specific submit event. It only checks if the global variable is existing and will not trigger any damage such as XSS/Code/SQL injection.

I think the recommendation you received to change the code is that you need to...

$name = filter_input(INPUT_POST, 'name');

then...

if (isset($name)) {
}


答:
I'm personally a fan of a high-level design document - preferably written BEFORE any code - that gives an overview of the design and a list of classes and resources.  A top-down design greatly simplifies things - yours might be "game engine -> hardware -> controllers -> joystick"; thus, a new programmer told "fix the 'a' button on the 'xyz controller" would at least know where to start looking.

Too many modern languages tend to break code into hundreds of tiny files, so just finding the correct file can be a challenge on even a moderate project.


答:
The key to working with a large codebase is not having to read the entire codebase to make a change. To enable a programmer to quickly find the code he is looking for, code should be organized, and the organization apparent. That is, each logical unit in the code, from the executable, the library, the namespace, down to the individual class should have a clearly apparent responsibility. I would therefore not just document source files, but also the directories they reside in.

Your programmer's notes also give background on design decisions. While this can be valuable information, I would separate it from the statement of responsibility (to enable the reader to choose whether he wants to read about the responsibility of the class or its design rationale), and move it as close to the source it describes as possible, to maximize the chance the documentation is updated when the code is (documentation is only useful if we can trust in its accuracy - outdated documentation can be worse than none!).

That said, documentation should remain DRY, i.e. not repeat information that could have been expressed in code or was already described elsewhere (phrases like "as the documentation states" are a warning sign). In particular, future maintainers will be just a proficient in the project's programming language as they are in English; paraphrasing the implementation in comments (which I see altogether too often when people are proud of their documentation) has no benefit, and is likely to diverge from the implementation, in particular if the documentation is not near the code it describes.

Finally, the structure of documentation should be standardized across the project so everyone can find it (it's a royal mess of Peter documents in the bug tracker, Sue in the wiki, Alan in the readme, and John in the source code ...).


问:
Why are Strings in StringPool considered insecure?
Passwords are recommended to be stored in char[] instead of String, as Strings are stored in StringPool.
Read more here

As per this question Strings in StringPool are not available directly.
To obtain Strings in Stringpool, we would need a password-dictionary to check them in StringPool. If we have a password-dictionary, we don't need to worry about StringPool, we can anyhow try directly on password fields.

To prevent Brute-force attack  we are limiting number of re-tries for passwords and checking for any suspicious activities.

If all that is in place still should we not use "String" as a datatype for passwords?

The answer obtained from similar questions is: We can have access to memory dump and get access to Strings in stringpool.

Follow up questions:

How can one access the memory dump?

Can the access be prevented?

If access to memory dump is prevented, Is it safe to use String as a type for passwords?

答:
Memory dumps can be obtained in a variety of ways, depending on what exact type of system your application runs on.  Typically, creating a memory dump would require access to run processes on either the server your application runs on, or if it's a VM it could also be done from the VM host. Blanking passwords is a mitigation measure to reduce the amount of damage a hacker can do if he gets this access.

In general, it is impossible to guarantee that access to create memory dumps has been prevented, because new operating system level vulnerabilities are discovered with relatively high frequency, and therefore you cannot know that no attacker has a working route into your system that you (and potentially the OS vendor) is unaware of. Inside attacks (e.g. by disgruntled employees) may also be mitigated by this approach, so even if you assume you are safe from external attack it is still best practise to zero passwords as soon as you are finished with hashing them.


答:
I would suggest the following implementation.

If the program is initially started create an encrypted and authenticated file containing either a timestamp or counter to have a starting value.
It is important not to use the basic user displayed and changeable time/clock, because otherwise your customer could just set the system time into the past.
When you run the program start a timer or increment the counter to measure the usage and update the encrypted an authenticated file periodically.

The location where the file is stored is unimportant, but you need to use the following things to accomplish reasonable security:

Use existing cryptographic functions, which are well tested and provide both encryption and authentication. To put it simple, encryption protects you from somebody trying to figure out the content, authentication from manipulation

Generate a random key for the encryption, no hard coding. Everything that is hard coded can be found through reverse engineering with more or less effort. Also reusing keys is always a bad idea

Store the key some place save where it can be automatically accessed by your program. This is the tricky part, as you have to trust the OS to properly handle it, as things need to be working without you entering things manually. My suggestion would be using DPAPI (assuming you develop for C# .NET on Windows).
You can easily store your key, and could as well be changing your key once in a while without big hassle.

So if the user either deletes, exchanges the file with an old version or manipulates the file, you are able to recognize it.

I hope this give some ideas how you could do it.

Edit

I was not correct regarding the replay attack, if the user is able to access both files then indeed he would be able to replace both with old versions.

My suggestion regarding your comment would be the following:

Have a file that contains a timestamp, the counter for usage, shutdown flag.

You will need a windows service running on start-up. Set a registry entry on the very first start-up.

The service checks for if the file is existent and if it is the very first time the service runs. If there is registry entry says that it runs for the first time, create the file containing the current timestamp (non-dependend on system clock, if possible), the counter for usage should be zero and shutdown flag false. The file is encrypted and the key encrypted through the DPAPI (use a fixed additional entropy). The registry entry is updated as from now on, all consecutive writes will be updates.

Now the service needs to update the file in a fixed interval, e.g. every 10 minutes. This means unprotecting the key with DPAPI and decrypting the file. Here is where we protect against replay attacks. The timestamp in the file is check and may not deviate more than e.g. 30 minutes (should be more than the update interval in case of failed update). If it does deviate more, manipulation is suspected (or heavy error from the application or hardware or OS). Otherwise, if everything is fine, the timestamp gets updated to the current time. If your service/program was used in the meantime, the usage counter gets updated as well. Generate a new key, encrypt the file and store the key after protecting it with the DPAPI.

When the user shutsdown the computer and starts it later on, you would have the problem, that the timestamp exceeds the allowed limit. That is why the file should contain the shutdown flag. This flag should be set when the user shutsdown the computers. When the service is stopped, it's final action is to update the file, with the shutdown flag set to true.
On a start-up the file is read and if the shutdown flag is true, set it to false and update the timestamp again.

This is how I would do it. It isn't bullet proof but more than enough to protect against fraudulent customers. I wouldn't even go that far and simply use the DPAPI and file combination and store the output of DPAPI in the registry. No normal person is his right mind would spend his time searching the entire registry. After all they are your customers not prisoners. With physical access to the computer there is no way to absolutely secure it.

The Isolated Storage is not very useful either, I just have read about it the first time. The user and also other programs with administrator/system privileges will be able to read these files.

Title: Avoid data manipulation by user

Body:
I have a C# program (could be any programming language) that saves data to a file on a memory (hard disk, USB drive, etc.). The program uses this data for monitoring its operation time, but it could be any purpose.

When the program is started, it reads the data from the file so it knows how long it has been operating before. It updates the data in the file every minute, so there is a failure of maximum 1 minute if the program is not shut down properly.

My problem is a quite general question: How can I prevent the user from manipulating the file?

I want to avoid that someone edits the operation time while the program is not running, or at least I want to be able to detect manipulation.

I though of a checksum first, but I also need to prevent that from manipulation.

The user can replace the current files by backups every time, thus the files themselves are not save if he knows where to look.

Therefore I need to store data at a location that is not easily editable. On a windows system, this could be the registry. Alternatively I could create a hidden system file in a special directory. However, I think the only chance is to hide the file or any information about the data from the user.

The user could replace the whole operating system including all data by an image. Therefore also a hidden location is not safe, but a) I cannot avoid this risk, and b) the user would need special equipment and knowledge, so the system is safe to most users.

Any other ideas how to secure data on a typical computer?


问:
Use application while it is installing
I was installing the Office 2016 Preview yesterday (link for anyone who's interested) and noticed that you can actually use the Office applications provided before the installation is complete.

When running the Office applications while the installer is still running, I sometimes see a message in the bottom right corner explaining that Office is streaming required files. I also noticed that, when running Word somewhat early in the installation (according to the installer) and trying to open the Settings dialogue, Word would hang until it had streamed the files.

How would this installation system actually work? I've never noticed it on any other applications before.

答:
multiplayer games do it more frequently. What happens is basically the following:

a streaming installer gets installed. This is a stub that does all the rest.

the absolute minimum to use the core functionality is installed. For Word (for example) that'd be opening and saving files, and some editing functionality

As you work, more functionality is installed. This is prioritised based on what you're actually using as well as common usage patterns (iow the installer predicts what you're going to need next and installs that first). You will therefore sometimes notice a "please wait" indicator while things are downloading that you're trying to use

eventually everything is installed and the installer stub deactivates. It may for example turn into an automated updater instead.

First time I encountered this was actually close to 10 years ago playing World of Warcraft, which works exactly like this.

Initially only the login and character creation functionality are installed. As you work through account creation, logging in, and character creation it installs the first levels/scenes of the game itself. While you're playing through those it installs ever higher levels, which will take you ever longer to get to so it doesn't matter that they're not available right away.

Title: Use application while it is installing


答:
I would highly discourage you from doing this in JavaScript on client side.

Even if it is only for testing and learning purpose it is very (very) bad practice! What you are trying to do is, is at best client side verification.

Imagine the following scenarios when you are not using server-side code for verification:
Somebody is simple removing this js function when visiting your (test) website. Now all your security is gone. Well it wasn't there in the first place.

Now to your question. If you actually want to use this and not have a plaintext password, you would want to hash it and add salt and pepper. You should use a hashing function which is hard to brute force (here are some examples link)

This is also standard practice for storing passwords in the database.

Here you can see the same problem with your attempt in js. Even if you create the hash and the user could no be figuring the password in reasonable time, there is no security. He can still change the js.

A similar problem occurs when you have the idea of simply sending the hash to the server (without TLS), again bad idea (have a look here link)

So even if it is for testing, for the sake of good practice, just don't.
You won't be learning anything valuable form it.

There are plenty of other topic were JavaScript is an excellent tool for getting things done. This is not one of them.

Title: Javascript Password Security

Body:
I am having difficulty with the answer provided here, but I couldn't understand how to implement it. My code is pretty much identical:

```<code><script language="javascript">
  function check(form) {
    if(form.userName.value == "User" && form.userPass.value == "averyobviouspassword") {
      window.open('testok/menu.html')
    }
    else {
      alert("Wrong Password Or Username")
    }
  }
</script>
</code>```

The problem with this is, if you were to Inspect Element on the page, you can plainly see the password. I'm not looking for other solutions like a SQL database, because this is just a test website. The solution I thought might work was this:

```<code>if(hash(enteredPassword) == storedHash)
</code>```

I just don't know how to implement it.


问:
C# Refactoring Code OOD and SOLID
I’m having some questions regarding improvement of code structure and maintainability, especially regarding SOLID. These questions are specifically for this project, so I would be happy if this doesn’t end up as a duplicate topic post (I am aware there are a lot of posts regarding this topic).

The main question is, if it is useful or even necessary to use SOLID to properly refactor the code.

A short introduction: I’m working as a coding monkey on a C# .NET project for a windows service.
This service has to read text files, which contain data logging information, identify the reading (e.g. voltage) perform some calculations on it and output the data into a text file.
This is a single man job I am doing for my employer. It is currently around 3000 LOC
As you are well aware project like this start small with a nice small set of requirements. Then suddenly new stuff needs to be implemented within the shortest time possible. As a result the structure of the program is not optimal. I have to admit that I am not very experienced as well (currently studying CS at college).

It started with four classes, one the windows service implementation itself with basic function on the data, and three for the big data structure containing all configuration and identification values.

Now there are two problems, the first is we started with just one type of data logger, now there are multiple and the function which performs the operations on read data needs to be split in parts.
Second and main concern, I still just have four classes. Everything is still in the ConverterService class.

I am aware that according to SOLID and OOD things need be separated in different classes, if they are for different concerns. What I can’t really wrap my head around it, if it really needs to be done here.

For instance I have a function for reading XML and function for writing XML. This could be put in a separate class, but I would just have one instance of it anyway.

Now regarding the data calculation function, this if how the structure currently looks like:

```<code>private static void editFile(input the file)
    check the header
    validate that values are really from configured data logger
    check timestamps
    special cases where values registers have certain names do…
    if conditions q
        if data logger x and also a do lots of operations
        else if data logger y and also a do
        else if data logger z and b do
    if condition w
        if data logger x and also a do
        else if data logger y and also a do some other operations
        else if data logger z and b do
    …
</code>```

As you can imagine pretty unpleasant to look at.

Now what I would definitely do is separate the tasks you can see in different functions (like checking the header etc.)
But when it comes to separate the condition operation mix things get a little complicated.
I see two ways doing it.  First the non OOD/SOLID approach:
Keep it in the ConverterService class but create separate functions for the operations.
The function editFile will still contains the condition checks and calls these functions.

Second approach, create a class for each data logger with their own operations. It would also be possible to create an interface that each class of data loggers implement to have it more unified. Problem is though, that the operations are very different so probably not the best idea.
The function editFile will still contains the condition checks and calls these functions.
I don’t see a big improvement because the abstraction doesn’t really simplify anything.

Summarized: 3000 LOC, 37 Functions and one developer

Big question:

What should I do?

All questions:

Should I use SOLID?

Do I need to strongly separate my functions
with classes?

Have I completely misunderstood OOD? (Have
mercy)

Is using a new class the right way, even though I’ll just
use it to call a function (and have on instance)?

How would you refactor this?

How to deal with large parameter lists that you
need when separating it in several functions?

I really hope this large chunk of questions is not out of place.

答:
What should I do?

Whatever you think is best.

You know the requirements. You know the code. You seem to have reasonable views on what is good, what is bad, and what changes might get you.

Should I use SOLID?

Yes. Guidelines exist because they usually will make things better. You shouldn't adhere to it just to be "right" - you should apply the guidelines because you think they'll make your code better.

Do you have unit tests? With code like this, (and being a beginner) you might not. I would suggest writing up some basic ones. They will help point out where your code will be painful to reuse - or where weird coupling points are. That can then help you judge where and how the code should be cleaned up to be better.

Title: C# Refactoring Code OOD and SOLID


问:
Why Java does not have a framework like Rails?
I am a Ruby on Rails developer and I like its simplicity and rapidness. On the other hand we need to use Java for some projects that we develop for our clients.

My question is why (pure) Java does not have a framework like Rails?

I searched and found some alternatives but they have big disadvantages:

Spring-roo: small community, lack of support

Grails: is something like I want but its main language is Groovy. Bad for Java developers

Play: community divided into two by Java-play and Scala-play and Scala is the main language.

Is there any limitation about language (being statically-typed) or is it just from that community does not looking a solution like Rails?

答: Because java it self providing some technologies for servers like JSP, Servlet. but in ruby no such technology exist. It does have Networking capability it up to us how we use it. That what Ruby on rails developers did. Java developers does not require any framework but ruby developers do for FAST Development's And Oracle itself providing support for JSP and Servlet.</p>


问:
What are the ways to avoid duplication of logic between domain classes and SQL queries?
The example below is totally artificial and its only purpose is to get my point across.

Suppose I have an SQL table:

```<code>CREATE TABLE rectangles (
  width int,
  height int
);
</code>```

Domain class:

```<code>public class Rectangle {
  private int width;
  private int height;

  /* My business logic */
  public int area() {
    return width * height;
  }
}
</code>```

Now suppose that I have a requirement to show to the user the total area of all rectangles in the database.
I can do that by fetching all the rows of the table, turning them to objects and iterating over them.
But this looks just stupid, because I have lots and lots of rectangles in my table.

So I do this:

```<code>SELECT sum(r.width * r.height)
FROM rectangles r
</code>```

This is easy, fast and uses the strengths of the database.
However, it introduces duplicated logic, because I have the same calculation in my domain class also.

Of course, for this example the duplication of logic is not fatal at all.
However, I face the same problem with my other domain classes, which are more complex.

答:
As @Machado said, the easiest way to do it is to avoid it and doing all your processing in your main java. However, it is still possible to have to code base with similar code without repeating your self by generating the code for both of code base.

For example using cog enable to generate the three snippets from a common definition

snippet 1:

/*[[[cog
from generate import generate_sql_table
cog.outl(generate_sql_table("rectangle"))
]]]*/
CREATE TABLE rectangles (
    width int,
    height int
);
/*[[[end]]]*/
```

<p>snippet 2:</p>

<pre class="lang-java prettyprint-override"><code>public class Rectangle {
    /*[[[cog
      from generate import generate_domain_attributes,generate_domain_logic
      cog.outl(generate_domain_attributes("rectangle"))
      cog.outl(generate_domain_logic("rectangle"))
      ]]]*/
    private int width;
    private int height;
    public int area {
        return width * heigh;
    }
    /*[[[end]]]*/
}
</code>```

snippet 3:

/*[[[cog
from generate import generate_sql
cog.outl(generate_sql("rectangle","""
                       SELECT sum({area})
                       FROM rectangles r"""))
]]]*/
SELECT sum((r.width * r.heigh))
FROM rectangles r
/*[[[end]]]*/
```

<p>from one reference file    </p>

<pre class="lang-py prettyprint-override"><code>import textwrap
import pprint

# the common definition

types = {"rectangle":
    {"sql_table_name": "rectangles",
     "sql_alias": "r",
     "attributes": [
         ["width", "int"],
         ["height", "int"],
     ],
    "methods": [
        ["area","int","this.width * this.heigh"],
    ]
    }
 }

# the utilities functions

def generate_sql_table(name):
    type = types[name]
    attributes =",\n    ".join("{attr_name} {attr_type}".format(
        attr_name=attr_name,
        attr_type=attr_type)
                   for (attr_name,attr_type)
                   in type["attributes"])
    return """
CREATE TABLE {table_name} (
    {attributes}
);""".format(
    table_name=type["sql_table_name"],
    attributes = attributes
).lstrip("\n")

def generate_method(method_def):
    name,type,value =method_def
    value = value.replace("this.","")
    return textwrap.dedent("""
    public %(type)s %(name)s {
        return %(value)s;
    }""".lstrip("\n"))% {"name":name,"type":type,"value":value}

def generate_sql_method(type,method_def):
    name,_,value =method_def
    value = value.replace("this.",type["sql_alias"]+".")
    return name,"""(%(value)s)"""% {"value":value}

def generate_domain_logic(name):
    type = types[name]
    attributes ="\n".join(generate_method(method_def)
                   for method_def
                   in type["methods"])

    return attributes

def generate_domain_attributes(name):
    type = types[name]
    attributes ="\n".join("private {attr_type} {attr_name};".format(
        attr_name=attr_name,
        attr_type=attr_type)
                   for (attr_name,attr_type)
                   in type["attributes"])

    return attributes

def generate_sql(name,sql):
    type = types[name]
    fields ={name:value
             for name,value in
             (generate_sql_method(type,method_def)
              for method_def in type["methods"])}
    sql=textwrap.dedent(sql.lstrip("\n"))
    print (sql)
    return sql.format(**fields)
</code>```

Body:
As @Machado said, the easiest way to do it is to avoid it and doing all your processing in your main java. However, it is still possible to have to code base with similar code without repeating your self by generating the code for both of code base.

For example using cog enable to generate the three snippets from a common definition

snippet 1:

/*[[[cog
from generate import generate_sql_table
cog.outl(generate_sql_table("rectangle"))
]]]*/
CREATE TABLE rectangles (
    width int,
    height int
);
/*[[[end]]]*/

snippet 2:

public class Rectangle {
    /*[[[cog
      from generate import generate_domain_attributes,generate_domain_logic
      cog.outl(generate_domain_attributes("rectangle"))
      cog.outl(generate_domain_logic("rectangle"))
      ]]]*/
    private int width;
    private int height;
    public int area {
        return width * heigh;
    }
    /*[[[end]]]*/
}

snippet 3:

/*[[[cog
from generate import generate_sql
cog.outl(generate_sql("rectangle","""
                       SELECT sum({area})
                       FROM rectangles r"""))
]]]*/
SELECT sum((r.width * r.heigh))
FROM rectangles r
/*[[[end]]]*/

from one reference file

import textwrap
import pprint

# the common definition

types = {"rectangle":
    {"sql_table_name": "rectangles",
     "sql_alias": "r",
     "attributes": [
         ["width", "int"],
         ["height", "int"],
     ],
    "methods": [
        ["area","int","this.width * this.heigh"],
    ]
    }
 }

# the utilities functions

def generate_sql_table(name):
    type = types[name]
    attributes =",\n    ".join("{attr_name} {attr_type}".format(
        attr_name=attr_name,
        attr_type=attr_type)
                   for (attr_name,attr_type)
                   in type["attributes"])
    return """
CREATE TABLE {table_name} (
    {attributes}
);""".format(
    table_name=type["sql_table_name"],
    attributes = attributes
).lstrip("\n")

def generate_method(method_def):
    name,type,value =method_def
    value = value.replace("this.","")
    return textwrap.dedent("""
    public %(type)s %(name)s {
        return %(value)s;
    }""".lstrip("\n"))% {"name":name,"type":type,"value":value}

def generate_sql_method(type,method_def):
    name,_,value =method_def
    value = value.replace("this.",type["sql_alias"]+".")
    return name,"""(%(value)s)"""% {"value":value}

def generate_domain_logic(name):
    type = types[name]
    attributes ="\n".join(generate_method(method_def)
                   for method_def
                   in type["methods"])

    return attributes

def generate_domain_attributes(name):
    type = types[name]
    attributes ="\n".join("private {attr_type} {attr_name};".format(
        attr_name=attr_name,
        attr_type=attr_type)
                   for (attr_name,attr_type)
                   in type["attributes"])

    return attributes

def generate_sql(name,sql):
    type = types[name]
    fields ={name:value
             for name,value in
             (generate_sql_method(type,method_def)
              for method_def in type["methods"])}
    sql=textwrap.dedent(sql.lstrip("\n"))
    print (sql)
    return sql.format(**fields)


答:
The short answer is that Java web developers, as a whole, seem to be happy with the tools/frameworks they currently have, and do not prefer the Rails way of working enough to make such an effort worthwhile. Feel free to start a project if you think it would help.

The Java platform has many frameworks for doing web development, some provided by Sun/Oracle, and others developed independently. The Java platform also supports several languages, which can be used for web development. Groovy/Grails, for example, was invented to provide a Ruby/Rails-like environment on the Java platform.

The reason a Rails-like environment hasn't taken the Java platform like it did for Ruby is largely a matter of preference and momentum for the teams developing the applications. The existing Java technologies work well (not implying that others don't) and have evolved in a different way, largely because the developers already had certain infrastructure in place (Servlets, JSP, JEE). Java developers seem to prefer the Java way of architecting applications. They may not prefer working in a Rails-like environment. If Groovy were an option for them, and they wanted to develop an application using the Groovy language, they could easily do so, using Grails. (It should be noted that you could develop a Grails app using only Java code, but it would be an uphill battle.)

The best thing about the Java ecosystem is that it was created by people trying to meet a need. If you feel there is enough need, and you'd like to help out, feel free to start a Rails-like project for the Java language. Maybe it will catch on :)

Title: Why Java does not have a framework like Rails?

Body:
I am a Ruby on Rails developer and I like its simplicity and rapidness. On the other hand we need to use Java for some projects that we develop for our clients.

My question is why (pure) Java does not have a framework like Rails?

I searched and found some alternatives but they have big disadvantages:

Spring-roo: small community, lack of support

Grails: is something like I want but its main language is Groovy. Bad for Java developers

Play: community divided into two by Java-play and Scala-play and Scala is the main language.

Is there any limitation about language (being statically-typed) or is it just from that community does not looking a solution like Rails?


答:
I definitely make use of a whiteboard at home and at work. I don't know brand names specifically but at work we tend to have rather large boards (6 feet wide by about 4 feet tall) and they cost several hundred dollars. At home I have a smaller board (4 x 3 feet) that I picked up at my local office supply store for about $30-$40.

I've been told you can use a product called "showerboard" from a local hardware store. It comes in large sheets but I'm not sure how good it is with the markers.

Another option you could use is a piece of glass (ex: in the move "A beautiful mind"). You could paint the glass white on one side. I actually did this on a small scale for a gaming table I built, works very well.

As for uses ... I use my whiteboard at home as a design station for home/side projects, I write reminders to myself and little notes. The whiteboard at work is used primarily as a design studio. When we gather as a team to go over a project we lay our designs out on the whitebaord and we can easily tweak them without going through alot of trouble. When we're all done we take a picture with a digital camera and save/print it.

If you had a "smartboard" you could print whatever you wrote on it but smartboards cost a pretty penny more so they're not practical at home and are only generally affordable by companies of a decent size.

Title: White Boards -- Who Uses Them?


问:
A real-world use case for triple dispatch
A few times in my career I've encountered design problems that couldn't be elegantly solved with single dispatch and required double dispatch (which I implemented using visitors). However, I've never encountered a problem that required triple dispatch.

They must be exceedingly rare, but that doesn't mean they don't exist. Has anyone actually had a real-life (not textbook/academic) design problem that could optimally be solved with triple dispatch?

答:
Consider a repository of citation information. containing books, articles, journals, edited books, and conference papers. Your task is to format the contents of the repository for consumption.

Let's take two approaches to formatting. National Library of Medicine (derived from the Vancouver Project) specifies citations in a particular way, mostly affecting how author names are laid out. NLM differs from American Psychological Association (APA) formatting. Your task is to provide a general approach to formatting citations using at least these two formatting standards. The visitor pattern is a good fit.

Now, you have to publish these citations and your choice of outputs are: plain text, PDF, HTML, RTF and MS Word (OOXML) or ODF. Some of these items require different layout strategies, depending on the type of the format (APA indents following lines, NLM doesn't).

"Double visitor" doesn't work so well. You really need something equivalent to "triple dispatch".

Now, that is not to say that there aren't approaches that get around the triple dispatch. For the above example, I ended up creating mixins and helper classes to provide the final publication version. These mixins and helpers are really where the 3rd dispatch occurred. I also evaluated publishing in a common denominator output and post-processing it to get the right output format, but that was ... bulky.


问:
Time attendance module design
I am working on time attendance module and I managed to read the data from the timing machine in the following format:

```<code>Id      CheckIn            Type Status
0000142 5/15/2015 6:00 PM   2   OK
0000142 5/15/2015 2:00 PM   1   OK
0000142 5/15/2015 6:00 AM   1   OK
0000142 5/15/2015 3:00 PM   2   OK
</code>```

where Type [ 1 - stamped in , 2 - stamped out ]

I should design a table to store these entries taking into consideration the following

Each employee should punch in first and then punch out

Some employees have 2 shifts per day ex: 09 AM - 01 PM then 05 PM - 09 PM

Some employees have night duties ex: 09 PM - 09 AM ( duty starts yesterday night)

what I am planning and need your kind advise is the following:

To create table EmployeeCheckIn[ Id,CheckIn,Type,Status]

To create another table ManipulatedEmployeeCheckIn[Id,FirstIn,FirstOut,SecondIn,SecondOut] where FirstIn and FirstOut is In and Out for first shift and SecondIn and SecondOut are In and Out for the second shift.

my questions

Am I breaking the normalization by adding the second table?

The second table will contain many NULL values, is this a bad designing?

How to eliminate the multiple entries for example, some employees will sign in twice and sign out 3 times so how to remove the duplication in entries but with different timing?

Last question which is the nightmare of me, the schedules that starts tonight and ends tomorrow morning, how to control them since i cannot control them by the CheckIn datepart

If you need more explanation, I am ready.
Than you in advance

答:
Yes if ManipulatedEmployeeCheckIn[Id,FirstIn,FirstOut,SecondIn,SecondOut] contains redundant data which is also in EmployeeCheckIn[ Id,CheckIn,Type,Status]

Yes in general NULL values should be avoided if possible

This depends on your intention which seems to be contradicting your question.
If you want to use EmployeeCheckIn[ Id,CheckIn,Type,Status] as a history as you wrote in your comment, then you should keep them in as these events occured and need to be logged.

If I correctly understood, you simply need to search for the employee id and search for the next entry with this id. Then you can check the CheckIn and Type part to see if the entry is valid.

I would have the following suggestions to avoid the null data. Just use one table for logging the check-ins EmployeeCheckIn[ Id,CheckIn,Type,Status,Valid] where Valid marks if the entry satisfies your rules. So once you have another entry going into the table you check if everything is fine and set Valid. Then you can easily operate on the table by filtering all that have Valid=0 (if 0 means invalid) and you have the data which you originally wanted to put into ManipulatedEmployeeCheckIn[Id,FirstIn,FirstOut,SecondIn,SecondOut]

I would do the validation in a Trigger which is activated when values are inserted.

Title: Time attendance module design


问:
Abstract/encapsulating session superglobal usage inside common accessor class
I am in the process of removing direct dependencies from an existing project. I have now come to removing the direct use of $_SESSION inside scripts. This is to make the same scripts available for an environment other than a web server such as PHP CLI.

The code base I am working on consist primarily of classes, so I have thought of making a generic interface declaring common methods such as fetch($key), exists($key), delete($key) and so on. Any class requiring access to the session would then implement this interface, thus making testing easier (which is almost impossible at the moment).

So the questions are:

Do you guys think this is a good approach

Are there other ways to achieve the same abstraction

I am open to suggestions of all kind as I am also using this as a learning opportunity. If you link me to a library doing this I would prefer if you could also write a few words about why you chose it.

答:
It's quite common in large MVC frameworks to see the session superglobal wrapped in an object, and the idea of being able to inject something else in its place in a CLI context is a good one.

Try looking into components other people hand already built, as well. The Symfony HttpFoundation component and Zend Diactoros might be of interest, if you're using the $_SESSION superglobal to work out details of the HTTP request.

EDIT

In case it wasn't clear from the above, I was suggesting having a single class that handles session interaction; I think a compositional approach like this would lead to cleaner architecture than the use of inheritance proposed by the title of your question. It kind of depends on the specifics of your code, but I think that this approach combined with the use of mock objects in unit testing will probably improve the testability issue you've identified with inline access to global state.


问:
Giving variables default values vs. treating accessing an undefined variable as an error
Having messed around with several scripting languages and being a bit of a linguist, there seems to be a way to divide dynamically typed languages into two groups: languages that give variables a default value, and languages that treat accessing an up-to-now unused variable an error.

For instance, consider this code:

```<code>print(hi)
</code>```

In Lua, it prints nil

In PHP (with a semicolon and $), it prints nothing

In Perl (with a semicolon and $), it prints nothing (but using say yields an error)

However,

In Python it throws a NameError

In Ruby, it throws a NameError (looks like Ruby ripped off Python's name for it)

In Javascript, it throws a ReferenceError

In Lisp, some type of error occurs that takes me to a debugger (I'm just learning Lisp now so I don't know what to call it)

Additionally, these languages behave differently when indexing an hash map, a similar operation, and they again fall into two camps (and when I say 'nothing' I mean that language's representation of nothing):

Lua returns nothing

PHP returns nothing

Ruby returns nothing

Perl returns nothing

Lisp returns nothing

Javascript returns nothing

But

Python throws a KeyError

So I am wondering what the comparative advantages and disadvantages are for a language to make accessing an undefined variable an error or just return a default value, and also what decisions would lead a language designer to choose one path or the other.

答:
If you are trying to decide what you should do in a language you are designing, I would suggest providing syntactical forms programmers can use to indicate various expectations.  As a hypothetical example (borrowing concepts from a few languages):

let x = someValue;

Create a new read-only identifier x, and expect that any code which can ever see the new identifier will never be able to see any identifier that previously existed.  It should be acceptable for x to already exist as a name, even in the current scope, provided that anything which can see the new definition will always do so.

declare x: someType;

Create a new variable called x, which must be written to before it can be used.  The identifier must not be declared anywhere else in the same scope.

def x: someType;

Create a new variable called x and assign to it the default value associated with someType.  The identifier must not be declared anywhere else in the same scope.

def x: someType = initialValue;

Create a new variable called x and assign to it the specified initial value.  The identifier must not be declared anywhere else in the same scope.

x = someValue;

Changes the value associated with a variable created using declare or def.

For languages which allow code to create and manipulate variables in outer execution contexts (the examples below assume such variables are loosely typed):

create x = someValue;

Requires that no variable x exists in the outer scope, and creates a new one.  Should trap if the variable already exists.

import x (default = someValue)

Indicates that within the present scope, x should refer to an outer-scope identifier; if none exists, create one with the indicated default value.

import x
Indicates that within the present scope, x should refer to an outer-scope identifier, which must already exist (trap if it doesn't).

variableName!
Yields the value of a variable in an outer scope with the indicated name, without having to make that name "directly" accessible throughout the present scope; traps if no such outer-scope name exists.

variableName ?| defaultValue
Yields the value of an outer-scope variable if it exists, or the indicated default value if not.  Neither creates nor otherwise affects the variable in any case.

While that's a pretty big number of syntactical forms, use of such forms can help make a programmer's intentions clear.  If a number of places within a method each use let q=something; but the usages of q are all cleanly distinct, that can be easier to read than having code use a different name for each q, or having a single declaration for q up top (but then not knowing whether it's supposed to be possible for execution to skip over code that assigns q's value and then read the previous value q held.  Having separate syntax for let, declare, and def should make program intentions clearer.


问:
Why do we have to tell printf() the type of data in C?
Let's consider this C code:

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

main()
{
  int x=5;
  printf("x is ");
  printf("%d",5);
}
</code>```

In this, when we wrote int x=5; we told the computer that x is an integer. The computer must remember that x is an integer. But when we output the value of x in printf() we have to again tell the computer that x is an integer. Why is that?

Why does the computer forget that x was an integer?

答:
The designers of C wanted to make the compiler as simple as possible.  While it would have been possible to handle I/O in much the fashion of other languages, and require that the compiler automatically supply the I/O routine with information about the types of passed parameters, and while such an approach might in many cases have allowed for more efficient code than is possible with printf(*), defining things that way would have made the compiler more complicated.

In the earliest days of C, code which called a function neither knew nor cared what arguments it was expecting.  Each argument would push some number of words on the stack according to its type, and functions would expect to find different parameters in the topmost, second-to-top, etc. stack slot below the return address.  If a printf method could figure out where to find its arguments on the stack, there was no way for the compiler to treat it any differently from any other method.

In practice, the pattern of parameter passing envisioned by C is very seldom used anymore except when calling variadic functions like printf, and if printf had been defined as using special parameter-passing conventions [e.g. having the first parameter be a compiler-generated const char* containing auto-generated information about the types to be passed], compilers would have been able to generate better code for it (avoiding the need for integer and floating-point promotions among other things).]  Unfortunately, I perceive zero likelihood of any compiler adding features to have compilers report variable types to called code.

I find it curious that null pointers are considered the "billion-dollar mistake", given their utility, and given that they generally only cause severely bad behavior in languages which don't trap null pointer arithmetic and accesses.  I'd consider the harm caused by printf and zero-terminated strings to be much worse.


问:
API to get data, caller may not know how much? How to allocate buffer size
I am writing a C API for retrieving data from a hardware device.  The data will be returned as a string with approximately 30 bytes of text per item.  The problem is there may any number of items.  Could just 10 or there could be 10,000.  So the returned data could range from 10 x 30 = 300 to 10,000 x 30 = 300,000 bytes.

Initially, the function to get the data was like this:

```<code>int get_devicelist(char* devicelist);
</code>```

So the onus is on the caller to know what they are doing and specify a big enough buffer.  Trouble is software using API could be used in many end user applications so the programmer has no end user specific knowledge when they write code to use the API.  The only option then is to specify a buffer (or allocate on heap) that is large enough to hold the largest possible amount of data returned.

So for that reason I am thinking about changing the API as here:

```<code>char* get_devicelist();
void free_devicelist(char* devlist);
</code>```

eg in implementation:

```<code>char* get_devicelist() {
  size_t n = get_devices_size();
  char* devlist = malloc(n * 30);
  if(devlist)
     /* populate devlist */

  return devlist;
}

void free_devicelist(char* devlist) {
   free(devlist);
}
</code>```

Or I just inform users to call free on devlist when no longer needed?

I would change the API code to get the number of devices and then allocate an appropriate amount of memory for devicelist.  The only downside is that the user is then required to call free_devicelist to free the memory allocated.

Is the second API better?  Is there an alternative way?

答:
The iterator approach mentioned by Useless is pretty good, though it may be enhanced by having the "read more" function allow the caller to indicate how many items it is ready to accept.  A limitation with that approach is that it may not be possible for a method to return a "snapshot" without tying up resources which could be left dangling if the caller fails to call a "close" method.

An alternative approach is to define a structure:

```<code>struct ThingProcessor {
  int (*process)(struct ThingProcessor*, struct Thing *, int n);
};
</code>```

and then have a method:

```<code>void getThings(struct ThingProcessor *proc);
</code>```

which will read groups of one or more items and, for each struct Thing someThings[n]; invoke proc->process(proc, Thing, n); [if the supplied method returns a negative value, getThings should exit early].  Provided that the supplied methods always return, the getThings() method will be able to ensure that any required resources get released.

Body:
The iterator approach mentioned by Useless is pretty good, though it may be enhanced by having the "read more" function allow the caller to indicate how many items it is ready to accept.  A limitation with that approach is that it may not be possible for a method to return a "snapshot" without tying up resources which could be left dangling if the caller fails to call a "close" method.

An alternative approach is to define a structure:

struct ThingProcessor {
  int (*process)(struct ThingProcessor*, struct Thing *, int n);
};

and then have a method:

void getThings(struct ThingProcessor *proc);

which will read groups of one or more items and, for each struct Thing someThings[n]; invoke proc->process(proc, Thing, n); [if the supplied method returns a negative value, getThings should exit early].  Provided that the supplied methods always return, the getThings() method will be able to ensure that any required resources get released.


问:
Are imperative events an anti-pattern?
Are events which are intended to tell listeners to carry out explicit actions an anti-pattern?

Imagine a worker service which raises the event WorkStarted at its beginning and the event WorkFinised at its end.

These events convey information about what that worker service did and they are not inherently imperative to any of the potential subscribers of that event.

Consider that it may be the intention of the application to use this event to show or hide a loading icon. Is it an anti-pattern for the worker service to raise a ShowLoadingIcon and HideLoadingIcon event instead?

In this case no information about what the worker service did is conveyed, only an instructive request is made.

In what cases, if any, are either these approaches inappropriate or preferred?

EDIT: To clarify, I'm asking about the existence of standards for event-driven programming. All standardization questions include some amount of opinion, and yet the site is littered with them because there is a different between a question of personal preference and one of generally accepted good practice.

答:
In every well-behaving event-driven architecture, there must be some rules that specify some partial ordering (timeline) for the events that will occur in response to some operations.

Example:

Order of Events in Windows Forms

If these orderings are violated, even by just a little bit, the event-driven world falls apart. This gives rises to non-deterministic or hilariously triggerable bugs such as "application crashes when I mouse over the menu bar when the application is doing (something)".

Events come from a source, and are dispatched to one or more listeners.

There is no requirement that the framework must perform this dispatching in a strictly deterministic and imperative manner. In other words, although the following is a very popular mental model among programmers, the framework is not necessarily implemented in that way.

New event - push a new message into a queue.

Framework - for every message that has one or more listeners, distribute (replicate) it to its listeners.

Each listener waits for a new message from the queue.

Each listener takes and processes the new message.

Notice that event types might be defined based on either the source (e.g. Work can have events WorkStarted and WorkFinished), or on actions (affordances) it can perform (e.g. ProgressIcon can receive ShowLoadingIcon, ShowFinishedIcon, or ShowFailureIcon.)

In some frameworks, the source-defined events and action events are separate types and given separate terminologies (such that the latter are not called "events" at all.) In some other frameworks they are both called events, because of the framework's choice to implement events using a unifying concept called delegates, which has a programmer's mental model that is very similar to callback functions.

You should be able to see where your confusion comes from: because the framework you're using makes everything looks like function calls, you have the temporary illusion that everything you can do with function calls, you can also do with delegates, and by extension also do anything with events. However, this is not the original intention of event-driven architecture.

In addition, programmers that use different frameworks will never face this confusion, and will have a hard time understand why this question arises.

Title: Are imperative events an anti-pattern?


问:
How do I write a proper messaging protocol?
I need to write a messaging protocol between client and server for a game application. I need to send messages back and forth such as, Player joined a game, player left game, player performed this action, etc.

I have a ClientMessage class that will construct a udp or tcp message to the client and send as plain text for now. But of course for the client to understand, there should be a simple protocol for each type of message (the aforementioned examples).

I am just not sure where to start as I've never had to. My only idea is

```<code>// Player actions
private int playerJoinGame = 100;
private int playerLeaveGame = 101;

// Game events
private int gameStart = 200;
private int gameEnd = 201;
</code>```

Then a message would look like

```<code>public PlayerJoinGame(string playerName){
   string msg = playerJoinGame + ',' + playerName;
   SendClientMessage(msg);
}
</code>```

Does this design pattern make sense? Is the only way to manage this, that is writing the responding end (client), to just be diligent and make sure when you update the server code, you update the cilent? (if event IDs change).

Thanks.

答:
If you want a robust protocol that can handle things like an old server talking to a new client for a while (you can't always deploy everything to everywhere in an instant), you need your messages to conform to a specific, schema'd data format that allows for backwards compatible updates to said schema.

I believe XML and JSON are the most popular data formats upon which such protocols are usually built (where I work, we use some of both). XML has the advantage of a single, standardized schema format. JSON has the advantage of being generally less verbose. If you really want to, you can spec out your own extremely simple context-free grammer and write your own parser/builder routines for it, but it's probably worth the initial learning curve to integrate some existing XML or JSON processing libraries. I'm sure C# has plenty of them.


答:
I'd recommend ZeroMQ. While not as informative as writing your own messaging service, it works nicely out of the box and is available for virtually any language you could name, C# included. It's also widely used so you can find support when things go wrong or you want to bring someone else into the project.

It supports a huge number of formats and messaging protocols so it can be made to work however you want for the most part. It's also asynchronous which can be a nice advantage when you've got a bunch of clients.

Title: How do I write a proper messaging protocol?

Body:
I need to write a messaging protocol between client and server for a game application. I need to send messages back and forth such as, Player joined a game, player left game, player performed this action, etc.

I have a ClientMessage class that will construct a udp or tcp message to the client and send as plain text for now. But of course for the client to understand, there should be a simple protocol for each type of message (the aforementioned examples).

I am just not sure where to start as I've never had to. My only idea is

```<code>// Player actions
private int playerJoinGame = 100;
private int playerLeaveGame = 101;

// Game events
private int gameStart = 200;
private int gameEnd = 201;
</code>```

Then a message would look like

```<code>public PlayerJoinGame(string playerName){
   string msg = playerJoinGame + ',' + playerName;
   SendClientMessage(msg);
}
</code>```

Does this design pattern make sense? Is the only way to manage this, that is writing the responding end (client), to just be diligent and make sure when you update the server code, you update the cilent? (if event IDs change).

Thanks.