问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
Consolidate the object model - make all objects extend base Object class. The Object class would (among other things) implement all the magic methods (so they'd be no longer magic!)

Move extensions to their own namespaces - unclutter the global namespace
$conn = new \MySQLi\Connection();

Un-cripple the spl_autoload() function! Seriously, this is possibly one of the greatest features of PHP and also the most useless at the same time. spl_autoload is the default autoloader, that supports namespaces and multiple file extensions, but for some unknown reason requires the filenames to be lowercased. There is a bug report filled for this, but the staff replied they won't fix it because of backward compatibility. Right... it's not like every framework ships with it's own autoloader, since the default one is crippled!


问:
Design review of a small configuration framework
I want to create a simple configuration framework. Yes I know, there are many frameworks, which make their job very well. But for interesting in architecture, I want to create my own.

My framework should notice the principles of SOLID
You should be able, to store you configuration in several formats.
As a proof on concept, I've drawed a simple uml.

Everything starts with a simple factory. This factory returns an abstract class called: "Configurator". Within the "Configurator"-class there's a method factory, which returns an interface, called: "IConfigurationSource". The configuration source is just a interface for storing my settings into a file or any different data storage.

Just a example of a xml implementation:

For a new format, I've to create a new class which inherits "Configurator".
You've to override the factory method and return a concrete type of a "IConfigurationSource". In this class, the "IConfigurationSource" will be initialized. I've also to implement a class which inherits "IConfigurationSource" again. This class will provide my data handling into a concrete data storage, in our example a xml file.

At least, a short description of my variables (examples):

component: For each configuration component, I'll provide a separate xml file. That means: "logging, network, users, etc..."

valueName: This is the name of a configuration item. For example: "maxUsersAtTheSameTime"

value: This is the value itself

This is my idea, to create a simple configuration framework. Later I'll implement something like object mapping etc...

Does this design fully support SOLID principles?

答:
This is a good exercise and I like the thought-process you are on.

Here's my review of that design.

Single Responsibility Principle

It's clear that each class is responsible for a single thing.

Open-Closed Principle

I don't think this is satisfied as the factory would change when a new format is introduced.  The factory doesn't need to be coupled to the set of available formats in my mind.  Service discovery or dependency injection could bridge that gap.

Liskov Substitution Principle

Spot on.  You have single implementation classes (please mark them final) that directly implement interfaces.  The lack of a deep hierarchy makes LSP easy to achieve.

Dependency Inversion Principle

It falls down here as the ConfigurationFactory knows about both Configurator, the interface, and XmlConfigurator, the implementation.  The distinction between Configuration and IConfigurationSource appears to be a meaningless partition without further context.  The diagram shows no others usages of Configurator for example so there's no obvious benefit to the interface if the factory has to know the concrete implementations anyway.

This could be addressed by having the factory load the implementations via service discovery of dependency injection.  In the dependency injection case the factory would be obtained from an injector and the various concrete class bindings would be in a module.

Conclusion

Overall I think you're pretty close on SOLID with this design.

ContentLicense: CC BY-SA 3.0


问:
Is client-side validation really all that important, always?
Through the years I've worked in web development it's been ingrained in me that client-side validation is absolutely and completely necessary in all web applications. Seems to me like all the people in the profession are very adamant on using it every single time. The most commonly mentioned benefits are:

Instantaneous showing of form errors

Less unnecessary requests to the server

But as we're moving towards the modern web, more and more applications are AJAX based. The simple task of submitting forms takes a lot less time now than it did before and validating on the server and returning errors barely impacts the user experience.

Could it be justifiable to completely avoid client-side validation (for example) on an application that only contains small and simple forms?

EDIT: I would argue that the linked duplicate question doesn't really capture the same example I'm giving here. A lot has changed since 2011. All of the answers on the related question are arguing for user experience whereas in my question I'm describing a scenario where the user experience would be unaffected.

When client-side validation no longer improves the user experience does it continue to rank in the same level of importance as before?

答:
It's still a very good idea to do "well-formedness" validation on the client-side...i.e. you expect a number, and encounter an alpha character, or a selection isn't made that renders the submittal moot...and of course, empty fields.

Doing business logic validation client-side is becoming, as the OP ponders, somewhat anachronistic these days, depending on the architecture.  If your user interface is pure VIEW, with little or no MODEL or CONTROLLER aspects, then validating business requirements for data client-side is almost moot.


问:
How to model heuristic uncertainty when sorting data?
Sorting algorithms assume you have a defined comparator. For example, if sorting integers A and B, the A > B operation allows you to determine if A should be after or before B.

Imagine you want to implement a sort, but rather than a defined and consistent comparator, the comparison uses a heuristic of some sense - so it's not a guarantee it will be correct. An example might be analogous to how eye doctors identify your prescription. They show two prescriptions and ask which is better. In some cases, as a patient you might not answer correctly for two close values. For values that are far apart, you will be more accurate.

If for example, you want to compare numeric values, you might model this as a custom comparator like:

```<code>public class HeuristicComparator implements Comparator {

    @Override
    public int compare(double val1, double val2) {
        double adjustedVal1 = val1 + Math.random();
        double adjustedVal2 = val2 + Math.random();

        return Double.compare(adjustedVal1, adjustedVal2);
    }

}
</code>```

In this basic example, I arbitrarily assigning some random variation to the comparison operation, effectively saying that any double values less than 1.000 apart might be sorted incorrectly. 1.5 might be less than 1.3, but only some of the time.

What other strategies are there for modeling heuristic behavior like this rather than a comparator? It seems you could modify the sort logic too (perhaps skip random points, modify a sort to not "finish" all adjacent sorts)?   What sorting algorithms that can be easily modified to match this behavior?

Or would it always be preferable to modify the comparator?

答:
Are you sure you want to implement the Comparator interface, rather than defining some more suitable one of your own?

For example, the randomized example you give cannot meet the transitivity requirement of Comparator, and of course can never be consistent with equals.

Hence you might get some nasty surprises (including possible non-termination) if you were to use this with standard containers and/or searching/sorting algorithms


问:
Is there a way to determine if a database has been altered, then to push new data to the Application
All our (my company) currently applications pull information from that database, is their a way to get the following types of databses to either push data or push an event to allow the application to pull data.

Access

SQL

Oracle

File systems (Files and folders)

The issue today is that most of our application spend a large amount of time constantly looking at databases and file system checking to see if data has changed . It would be better for the database to inform the application when data has changed. Are there tools within Visual studio to allow this or are there tools within the database / filesystem to do this?

All ready asked this on stack overflow but go no answer. I've been doing some more research but I cant seem to get any further. My manager has asked to investigate it as it would mean our applications are much quicker and efficient.

答:
it would mean our applications are much quicker and efficient

In what ways are your applications slow or inefficient now?

Is this a GUI application with a less-than-responsive front-end?  If so, you're querying the database wrong.  You should not do it on the main thread, but on another thread (or task if you're using .Net).

Is your code already using threads for the database polling and yet your application is still too slow?  Maybe you can give the threads a lower priority?

If your database polling is still slowing down your application, can you set up a second application that handles the polling and set up some type of communication between the two applications?  Maybe a message queue?  This would be especially beneficial if you have N copies of your application running as there would be one program polling the database instead of N programs.  Repeatedly polling a message queue should be faster than repeatedly polling a database.

I think that what you want just doesn't exist.  When you send a request to the database, it has to sit and wait for the request in order to acknowledge it.  This means the the database is doing it's own polling.  Maybe it's optimized to be super fast, but at some level there's something spinning and waiting for a signal.  Your application must have a mirror image of this in order to receive a response from the database.


问:
Should Java 8 Stream instances always be close()'d?
Quoth the Javadoc:

Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.)

"Nearly all" and "generally" are vague - if you're writing a library and you're abstracting the source of your Stream from the users of that Stream, then you always anyway have to ask yourself the question - "should I close this?" IO-backed Streams need to be closed because terminal operations don't call close, so effectively I always have to either remember/document where my Stream is coming from, or I always have to close it.

The nuclear option I guess would be to not return Streams from methods or accept Stream parameters, which is a sentiment that has been echoed by some people on the JDK team. I find that to be overly limiting considering the practical usefulness of Streams.

What are your best practices around closing Streams? I looked online for an answer to this from some of the JDK folks who are usually active on similar community questions, but didn't find anything relevant.

答:
As you said, in Java you need to know exactly who is responsible for freeing which resource, so you can put in the appropriate try-catch-constructs, try-with-resources or somehow delegate that task.

The only thing which you can depend on the GC to clean up for you is 100% pure memory.

If there might be some other resources mixed in, the only thing you can reasonably do is simply playing it safe.


问:
Shipping my first class library. Any gotchas I need to be aware of?
I'm a Web Developer about to unlock the "First Class Library Published" achievement in my career and I'm sweating bullets (I was up all night stressing out).  I'd love to tap the experience of the community to see if anyone has any suggestions or recommendations for making sure this goes as smoothly as possible.  Are there any specifics or gotchas I need to be aware of?  Anything special about the build process that can come back to bite me?

Here's where I'm at:

Library is unit tested and has approx 97% code coverage

API is well documented and xml docs for intellisense support have been created

I've ensured that public/private class accessors are accurate and correct. The same goes for all getters/setters

Error handling isn't as graceful as I'd like it to be, but I'm up against a deadline and have accepted that its an "as good as its going to be" for now

No friendly logging.  Debug.Writeline was used extensively...I've learned recently that this is a reflection of my inexperience :(

Your advice is greatly appreciated!

The library will be used to generate reports.  Standard hat -- connects to readonly database, performs calcs, formats and outputs data to response stream.

I was tapped as a fringe resource to fill in for one of the programmers that quit, and this task was given to me as a "cut your teeth" project.  The class library is going to be released for other programmers in the company to use while they write production code.

答:
I have a checklist for deployments that you may find useful.  I do desktop development but some of this should translate.  Here's some of it:

General:

Put in null checks for function parameters that shouldn't be null.  This helps me fail early.

Remove unnecessary comments and commented-out files.  These cause future work.

Search for any "//TODO" comments.  Sometimes I leave notes for myself.  Sometimes I forget about them.

Run a test of my code using the production database where possible.  This helps ensure I have all of my database changes in place on the production server.

Put in copious logging.  Especially for an initial deployment.  In fact I save logging for the end because my code is usually gelled some at this point.  You don't want to be in a situation where you have a crash and you say to yourself "If  only I knew what the value of X was at this time".  Try to plan ahead.

Try to wrap third-party library calls in Facades.  This makes it easy to change libraries in the future as well as provides a checklist of what you require from a library.

.Net specific:

Ensure I'm calling Dispose() on disposable objects.  I use Code Analysis or FxCop to help find cases of this.

Ensure I'm unhooking all event handlers properly.  This prevents memory leaks.


问:
Why is using 'final' on a class really so bad?
I am refactoring a PHP OOP legacy website.

I am so tempted to start using 'final' on classes to "make it explicit that the class is currently not extended by anything".  This might save lots of time if I come to a class and I am wondering if I can rename/delete/modify a protected property or method. If I really want to extend a class I can just remove the final keyword to unlock it for extending.

I.e If I come to a class that has no child classes I can record that knowledge by marking the class a final. The next time I come to it I would not have to re-search the codebase to see if it has children. Thus saving time during refactorings.

It all seems like a sensible time saving idea.... but I have often read that classes should only be made 'final' on rare/special occasions.

Maybe it screws up Mock object creation or has other side effects that I am not thinking of.

What am I missing?

答:
"final" for a class means: You want a subclass? Go ahead, delete the "final", subclass as much as you like, but don't complain to me if it doesn't work. You're on your own. </p>

<p>When a class can be subclassed, it's behavior that others rely upon, must be described in abstract terms that subclasses obey. Callers must be written to expect some variability. Documentation must be written carefully; you can't tell people "look at the source code" because the source code isn't there yet. That's all effort. If I don't expect that a class is subclassed, it's unnecessary effort. "final" clearly says that this effort hasn't been made and gives fair warning. </p>

Body:
"final" for a class means: You want a subclass? Go ahead, delete the "final", subclass as much as you like, but don't complain to me if it doesn't work. You're on your own.

When a class can be subclassed, it's behavior that others rely upon, must be described in abstract terms that subclasses obey. Callers must be written to expect some variability. Documentation must be written carefully; you can't tell people "look at the source code" because the source code isn't there yet. That's all effort. If I don't expect that a class is subclassed, it's unnecessary effort. "final" clearly says that this effort hasn't been made and gives fair warning.


问:
How to map entity class (ClassA) in two different table (Table1 and Table2) in Entity Framework Code First?
Here's the situation. I have two table (Table 1 and Table 2) with the same entities and a class(ClassA) which was mapped to Table 1 but in some scenario I have to transfer the specific data from Table 1 to Table 2. How can I map the two table (Table 1 and Table 2) to ClassA using Entity Framework Code First?</p>

答:
Even though you're using Code First, it's important to remember that your C# entities are projections of your database at runtime. If you use schema generation, your database schema is a projection of your C# entity metadata.

That means the safest mapping is one-to-one. If you can live without schema generation, you can get away with multiple entities mapped to a database object. Conceptually, you can never get away with one entity mapped to multiple database objects. Sure, you might be able to temporarily do it by completely subverting the EF plumbing, but at that point you're not truly mapped in any meaningful sense. Why not step outside the EF world to do whatever needs doing and step back in when you're finished? Either that or modify your model slightly to accommodate EF's expectations.


问:
How can I best manage Android Intent filter Strings across multiple projects?
In my project IntentExamples, I have this filter, corresponding to a service.

```<code><intent-filter>
                <action android:name="biz.rpcodes.apps.intentexamples.START_SERVICE" />
</intent-filter>
</code>```

In another project, UseExampleService, I have something like:

```<code>Intent i = new Intent("biz.rpcodes.apps.intentexamples.START_SERVICE");
                startService(i);
</code>```

...guided by this answer:  https://stackoverflow.com/a/16439551/5181778

My question is: How can I best manage these Intent filter Strings across multiple projects? The best solution I have now is to make a class that I am copy and pasting from Service project into the other projects, i.e.:

```<code>class ExampleServiceIntents {
public static final String ExampleServiceIntents.START_SERVICE =
    "biz.rpcodes.apps.intentexamples.START_SERVICE";
...
</code>```

While I could import the Service classes themselves,  new Intent(this, ExampleService.class) , I would like to keep the Service classes in their own project.

答:
Android Shared Libraries or operating-system dependent symbolic links.

Option 1: Shared Android Library

A formal Android library imported into each project.

Pros: Type safety. Cross-platform and works with source control. Full syntax checking and editor support.

Cons: It is still a bit annoying to import projects as libraries via the current editors (Android Studio or Eclipse with ADT) since they don't offer very good interfaces to do this. If you have to do this task often but not so often you remember all the steps each time, then this might not be worth the effort. But if its a one or two time thing to start with, then you don't have to do it again, it's not too bad.

Option 2 Symbolic Links

Symbolically link a common source file in each project. Then both projects will see the file and changes to it, so they can stay in sync.

Pros: Much simpler to implement.

Cons: Symbolic links don't work so well with source control tools. Not cross-platform (for development) since symbolic links are very different from one operating system to another. Not real clear to a new developer coming onto the project that changes in one automatically get shared with the other.

Therefore, because the symbolic links option have more cons then pros, I would generally recommend the shared library solution for most projects. But, if your particular project doesn't need the features from the cons column of the symbolic link, then that's probably easier. It depends.

PS: There is a terrible third option of having a third full Android application that offers an Android data Provider that offers up the string values. But at that point you need to communicate with that app with special strings that need shared too, so you're only adding a step of abstraction but haven't solved the problem.


问:
Why is JSX good, when JSP scriptlets are bad?
React.js provides JSX as an XHTML-like syntax for constructing a tree of components and elements.  JSX compiles to Javascript, and instead of providing loops or conditionals in JSX proper, you use Javascript directly:

```<code><ul>
  {list.map((item) =>
    <li>{item}</li>
  )}
</ul>
</code>```

What I haven't been able to explain yet is, why is this considered good if analogous constructs are considered bad in JSP?

Something like this in JSP

```<code><ul>
   <% for (item in list) { %>
     <li>${item}</li>
   <% } %>
</ul>
</code>```

is considered a readability problem to be solved with tags like <c:forEach>.  The reasoning behind JSTL tags also seem like they could apply to JSX:

it's a little easier to read when you aren't toggling between XHTML-like syntax (angle brackets, nesting) and Java/Javascript (curlies, commas, parens)

when you have the full language and platform available for use inside the rendering function, there's less to discourage you from putting logic in that doesn't belong there.

The only reasons I can think of why JSX is different is:

in Java, you had an incentive to do the wrong thing - JSP would be hot-reloaded, so it was tempting to put code in JSPs to avoid a rebuild/restart cycle.  Maintainability was sacrificed for immediate productivity. Banishing scriptlets and limiting to a fixed set of template constructs was effectively a way of enforcing maintainability.  No such distortion exists in the JS world.

JSP and Java syntax is clunky with the extra <% ... %> to distinguish Java code from element generation, and with Java's native syntax lacking a foreach concept or first-class functions (until recently). The syntax penalty of using native Javascript for loops and conditionals in JSX is non-zero (in my opinion) but not as bad as JSP, and arguably not bad enough to warrant introducing JSX-specific elements for loops and conditionals.

Is there something else I'm missing?

答:
As an outsider to React, I viewed JSX as being yet another "framework smell" in the very crowded zoo of framework stinks.  I'm still not convinced that this isn't the case.

I think a workable definition of "useful" is that a library/framework/pattern solves more problems than it causes.I'm not yet convinced that JSX fits that definition.  It's the proverbial "squeezing the balloon"...you squish a problem here, it pops out over there.  To me, JSX isn't solving any particular problem...it's only just "different."

The notion of introducing a compilable semantics that needs a formalized build process is useful in some circumstances:  for example, LESS compilation of .css files provides some very-much-needed structure around css, which is a hierarchal structure with imports and overrides, thus being very prone to "spaghetti solutions."  But Javascript pre-compilers...not so much.


问:
How do I approach a complicated merge
Here is the deal, I have joined a new company and have been asked to finish off the work on a branch which hasn't been touched for almost a year. In the meanwhile, the master branch has been growing with a steady pace. Ideally I would like to merge all of the changes from the master branch into the feature branch and continue the work from there, but I'm not too sure how to approach this.

How do I perform this merge safely while preserving important changes on both sides of the branch?

答:
Step 1. Learn about the code, analyze its architecture, and the changes that have been made on both branches since the latest common ancestor.

Step 2. If the feature appears broadly independent and touches mainly different areas of code, merge, fix conflicts, test, fix etc. The is the happy path, you're pretty much good to go. Otherwise go to Step 3

Step 3. Analyze the areas of conflict, understand the functional impact and reasons in detail. There could easily be conflicts in business requirements that come to light here. Discuss with BAs, other devs as appropriate. Get a feel for the complexity involved with resolving the interference.

Step 4. In light of the above, decide whether to aim to merge/cherry-pick/even cut-paste only those parts that do not conflict and re-writing the conflicting pieces, OR whether to re-write the whole feature from scratch.

Title: How do I approach a complicated merge


答:
Try high-latency connections

While rapidly firing a tiny AJAX request to do some on-demand server side validation may seem just as fast as doing it with client side javascript, having the same user experience, it is only true because you have a comparably good internet connection.

Some of your users will have internet connections that for various reasons are slow, unreliable, high latency or a combination of this. For them, this approach to validation will noticeably worsen the user experience.

It is often a good idea to run at least some usability testing with an artificially worsened network connection (there are tools to simlate that), so that you'd understand and have a chance to fix UX in such situations.

Title: Is client-side validation really all that important, always?

Body:
Through the years I've worked in web development it's been ingrained in me that client-side validation is absolutely and completely necessary in all web applications. Seems to me like all the people in the profession are very adamant on using it every single time. The most commonly mentioned benefits are:

Instantaneous showing of form errors

Less unnecessary requests to the server

But as we're moving towards the modern web, more and more applications are AJAX based. The simple task of submitting forms takes a lot less time now than it did before and validating on the server and returning errors barely impacts the user experience.

Could it be justifiable to completely avoid client-side validation (for example) on an application that only contains small and simple forms?

EDIT: I would argue that the linked duplicate question doesn't really capture the same example I'm giving here. A lot has changed since 2011. All of the answers on the related question are arguing for user experience whereas in my question I'm describing a scenario where the user experience would be unaffected.

When client-side validation no longer improves the user experience does it continue to rank in the same level of importance as before?


问:
Soap vs. rest - a hybrid approach?
I have a proper SOA architecture, with web services defined with WSDL and responding to SOAP requests.

But this application has also an endpoint that responds to json request and replies in json format, so a little bit more like REST.

My goal is to transform this application into a sort of platform, exposing an API, and I have to understand all the best practices to build this API.
My question is about the very first step: how can I define an API from such a hybrid architecture?

It is not REST, but it's excluded using SOAP for requests.

Is it still a webAPI? Is there any "classification" beside REST API? I am a bit confused, read everywhere but still don't get the main point of this.

Already read here:
Difference between Web API and Web Service?

答:
REST architecture recognizes that on a field-by-field basis, thereare ultimately only the C.R.U.D. operations that encapsulate ALL state definitions.  This does "break" our so-called oldSchool ideas about transaction boundaries and all that stuff, but just because someone stood up and screamed the acronym "REST!!!!", we don't have to only do that.

Just because it's theoretically possible to decompose every object transfer between systems/components down to a REST-style field-based CRUD operation, doesn't mean we have to.

Title: Soap vs. rest - a hybrid approach?


问:
How are head first books?
I have never read any of them but I find their style interesting and unique.  I am not sure if they are worth giving money/time?</p>

答:
In my opinion, they're good if you are a beginner in programming in general - not only in the topic in question.

That is, before learning the options for conditionals in a language, they will spend a lot of time - and a lot of simple and silly examples - to explain what conditionals are.

The solutions they propose are often very lean and lightweight, but they tend not to explain why they chose that solution and which the alternatives are.

Use cases:

A C++ programmer wants to dive into web development, using PHP. I would recommend one of the mid-level books also by O'Reilly, like "Learning PHP, MySQL and Javascript". Those are still very careful (borderlining on the pedantic) in explaining how the language works, and full of examples: still, if you have the right attitude towards learning new technologies, one of them would suffice to let you build solutions for almost anything within the standard scope of that technology. Also, they can be used as a reference.

A web designer wants to learn some Javascrtipt to liven up his pages. He is a nice specimen, so he prefers having an idea, albeit vague, of what he's writing rather than copypasting around. Nevertheless, he does not want to master that technology and he never read a programming manual - so there would be a steep learning curve for language and conventions themselves with a nice course/reference book, and it's not worth it. In that case, Head First manuals are definitely the best option.

Title: How are head first books?

ContentLicense: CC BY-SA 2.5


问:
CQRS and DDD terminology
Since CQRS and DDD do not imply one another I was curious what terms belong to DDD and what terms belong to CQRS. Because the two concepts are so much used together in the literature I usually mix them up.

I came up with this list of the terms that I think go to one camp or the other.

DDD

Domain model

Aggregate (and aggregate root)

Value objects, entities, services

Bounded context

Ubiquitous language

Events?

CQRS

Command (Command Handlers)

Events? (Event Handlers?)

Saga, process managers

Read model / Write model

Projections (different read models)

Eventual consistency

Could anyone correct me (and/or explain), what is where?

答:
CQRS and DDD are separate/orthogonal concepts, and I think you divided the terms pretty close to right.

Events under DDD are called Domain Events, and are somewhat different from the Messaging events often mentioned with CQRS. Messaging events usually have more to do with Event Sourcing.

Your CQRS category is a conglomeration of a number of patterns, and only one of those (Read model / Write model) is actually definitional to CQRS.

Messaging, implemented as commands and events. Messaging gives you a lot of flexibility over something like, say RPC. Messages, being just request or event data, can be examined, prioritized, queued, partitioned across nodes, forwarded, retried, subscribed to, etc. Conversely, they can also be lost, poisoned, etc.

Saga and Process Manager are often used interchangeably when referring to a Process Manager. Both are strategies for avoiding distributed transactions, usually in order to maintain scalability.

Projection goes way back. You probably know this most commonly from SQL. The SELECT expr [as name] statement is the Projection operation in relational algebra, on which SQL is based. A projection is just a subset or transformation of the underlying data.

In the context of CQRS, projections are usually referring to views (aka read models). Although technically an event-sourced aggregate is also a projection -- it's an event stream transformed into a structured model, just like with views.

Separating read and write models is the essential definition of CQRS. CQRS is helpful because the data you need for views (reads) is different from what is needed for writes. In a traditional 3-layer system (presentation, business, data layers), you often naively start with the same class being used by all 3 layers. As complexity increases, you will end up with extra fields which are used by only one layer, but add mental weight at all layers. "I just added something to this collection. Do I need to update the DisplayCount here or will the view do that? Do I need to persist this DisplayCount or does the view recalculate that each time? Wait, why is DisplayCount a string?!"

You start to realize that read and write needs are different enough to warrant different objects to isolate concerns. That can lead to mapping business object to a view object, which is arguably a form of CQRS. (This also happens in DDD systems not using CQRS, mapping from domain model to view). However when claiming CQRS, people often mean they are persisting both read and write models, not loading the write model and mapping it to a read model. There are typically multiple read models for a given write model to accommodate the specific needs of different ui screens/reports/views.

Eventual consistency is not unique to CQRS either. Any time you create a report that gets run periodically, you have created an eventually-consistent read model. When it is talked about with CQRS, it usually means that most/all read models are eventually consistent. This is optional to CQRS. You could use CQRS in a fully consistent manner, and this would simply shift the IO burden from reads to writes. This by itself is probably an okay trade-off for most system, because IO is likely dominated by reads.

Systems with a single model of data are optimized for writing (normalized) and reads are expensive (i.e. JOINs in SQL). With CQRS, you trade towards cheap reads by making separate (and probably multiple) read models which are denormalized (all necessary data put into each read model so no JOINs are needed). In a fully consistent system, you have to update the write model and all read models at the same time to maintain read/write consistency. You are trading write performance for read performance.

Enter eventual consistency, which buys you cheap reads and writes, with the trade-off that read models will be slightly behind (eventually consistent with) the write model. This is due to an out-of-band process (often called a denormalizer) updating the read models after-the-fact.

Many people have developed "CQRS systems" which are combinations of these patterns plus CQRS. However, the CQRS pattern really only amounts to separating read and write models. It doesn't mean you have eventual consistency, event sourcing, process managers, messaging, or anything else. However, the mentioned patterns do synergize well with CQRS and are basically progressive optimizations to take further advantage of it.

Also, CQRS is based on another pattern, Command-Query Separation, but takes it a step further.

Edit: For a more detailed explanation on the difference between Domain Events and Events used for event sourcing, please see this classic Greg Young post.

Title: CQRS and DDD terminology


答:
Is this for academia or for the work world?

In the work world, JSON is so much easier to parse than XML.  For example, in the PHP language, JSON data seamlessly imports into an associative array (which is a data structure native to PHP and operated on by dozens of built-in PHP functions).  XML, however, usually has to be parsed with special library functions which are more limited.  And even then, iterating the nodes of an XML document is less intuitive.

SOAP has also proven to be a very picky protocol.  I've seen multiple real-world occasions where different SOAP adapters didn't talk to one another successfully.  There were lots of cryptic SOAP fault errors thrown.  And deep inspection and tweaking of the SOAP messages led to inexplicable dead-ends.

I'm convinced that it's reasons like these that REST/JSON seems to be slowly replacing SOAP/XML as the preferred format and protocol for exchanging data out in the industry.

As for exact REST or SOAP theoretical specifications and how each API or vendor adheres to them in practice...don't ask.  Theoretical specifications are for authors of computer science papers.  Results are for people trying to deal with business challenges and put food on their table at the end of the day.  The web has always been a kludge of half-baked, ill-fitting technologies.

If you can find a way to simply, easily, reliably, securely, and coherently exchange data...then you win.  The simpler, the better.

Title: Soap vs. rest - a hybrid approach?

Body:
I have a proper SOA architecture, with web services defined with WSDL and responding to SOAP requests.

But this application has also an endpoint that responds to json request and replies in json format, so a little bit more like REST.

My goal is to transform this application into a sort of platform, exposing an API, and I have to understand all the best practices to build this API.
My question is about the very first step: how can I define an API from such a hybrid architecture?

It is not REST, but it's excluded using SOAP for requests.

Is it still a webAPI? Is there any "classification" beside REST API? I am a bit confused, read everywhere but still don't get the main point of this.

Already read here:
Difference between Web API and Web Service?


问:
Using a switch vs multiple classes and a hashmap
So I have a file to process that contains a command on each line. Currently it's implemented like this(this is a refactoring assignment):

```<code>hashmap.get(commandStr).sendCommand();
</code>```

The objects(4) inside the hashmap, each contain a different sendCommand method.

The thing is each of these method implementations are just 2 or 3 lines and this feels a bit wrong because those object don't store anything and they just have one method.

Should I instead make this a into a switch and instead process all the commands in one function?

Is there any other way to do this? Any design pattern meant to this? Any other reason the initial implementation is bad or good?

答:
The good thing about a switch statement is that it is fast, if you need speed.  The bad thing is that in a command processor it lacks flexibility; if you need to add a new kind of command, its time to rewrite the command processor.

With this hash table for decision making it is better, but with hardcoded methods for the command actions, you still face the same problem of recoding the command processor if a new command is added.

If I were in your shoes I would think about an interface or abstract method to define a command and perhaps handle some of the common tasks and having a child class for each command.  Your processor could have or call a factory method that would instantiate the correct command class.  This way as your command set evolves, less of your code would be affected.  Hope this is a help.


问:
Trying to understand on what "user.dir" property actually means?
So basically wen I googled on what the "user.dir" property does I got this link to a similar question on stackexchange: Java “user.dir” property - what exactly it means?

So basically the answer given was : It's the directory where Java was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run Java.

Which is okay, but then I found this other link in the android context: Why does System.getProperty(“user.dir”) return “/”
As the documentation says, the user.dir property is the user working directory, which is not necessarily the same as the directory where your apk is placed.

So the first best voted answer in the first link says the directory does not have to be within the users home directory while the other says "it is the user working directory."

Now I am terribly confused and need help on this.

答:
A home directory is associated with a user (for a user MIke, this is often something like /home/mike).

A working directory is associated with a running process; in a shell this is often printed as part of the prompt, for other processes there is usually no direct way of observing it. A user typically starts a shell session in their home directory but then can move away from it.

The directory where Java is installed is a third, unrelated thing (and the directory in which a java application or library is installed could be yet another, unrelated fourth directory).
But as the documentation says,

By default the classes in the java.io package always resolve relative
  pathnames against the current user directory. This directory is named
  by the system property user.dir, and is typically the directory in
  which the Java virtual machine was invoked.

In other words, user.dir is the working directory of the process that started the Java process at the time when it started the process. If this was a shell, it is the directory to which the shell user had last switched. If Java was called from another program, e.g. a window manager, it is whatever that program had as its working directory.


问:
Using Apache Licensed font for mobile
We are looking to incorporate an open source font which uses the Apache License v2 in our mobile application. I have a couple of questions on proper procedure/etiquette:

For a font, does creating an application that incorporates the font count as a derivative work (in other words, do we need to include the Apache license somewhere)? I always assumed that a "derivative work" for a font would mean making new fonts based on the original font, but a partner suggested that the license also applies to any application that incorporates the font.

Secondly, if we are required to display the license, how do we go about this on mobile where there are no accessible text files (e.g. NOTICE, README, LICENSE) included with the install? Do we put it in the license on the store? In a screen somewhere in the app?

答:
Copying someone else's work into yours makes yours a derivative work, even if you don't modify anything.

In the Android world, it's common to add acknowledgements and copyright notices to the Settings menu, as a menu item on the end.  Look at some of the apps from Google that come pre-installed for examples.

Title: Using Apache Licensed font for mobile


答:
You have an API that uses HTTP, in my book that makes it a "web API". That's a completely generic term that implies nothing else.

REST and Web Service are two examples of web APIs. Yours isn't REST and only part of it is a SOAP Web Service.

I would describe it as "A web API that uses mostly SOAP but also has a more freeform endpoint that uses JSON requests and responses".

No need to overthink this stuff.

Title: Soap vs. rest - a hybrid approach?


问:
How can QA staff test caching logic that they can't see?
I just implemented a caching layer in my web application, and now I'm wondering how QA is supposed to test it, since caching is transparent to the user.

One idea I have is to put logging in the methods that invoke the code that populate the cache, and record when an object is pulled from cache and when it requires recreation from the database, and then the testers could view the logs to see if, for example, a certain object is reloaded from the db every 10 minutes, instead of every page view.

But can anyone suggest some better practices for this situation?

答: When I was testing caching solution we have implemented then what we have tested basically the performance. We have done that caching solution for XML results and after the cache it takes very low time to give the response. Also we have checked it with the server log by checking the log entries.</p>


问:
Selenium Testing w/ dynamically generated element id's: XPATH or CSS selectors?
Background: I'm an intern tasked with learning Selenium; my organization plans on having QA/Testing use it to simplify testing. We use JSF and WebSphere Application Server.

One of the persistent issues I (and other users) have had with using Selenium is identifying input elements that have dynamically generated ID attributes. Simply put, I don't know how the ID's are generated or when they change, so hard-coding the ID's into the test case is right out.

Fortunately, I figured out two solutions to the problem. I'm not sure which is better, and as a result I'm not sure which I should recommend.

1) I could use XPATH to locate the element. The devs almost always use the ID attribute when they write up the html, and while JSF will re-assign it on the rendered page, the dev-assigned substring is always (AFAIK) a part of the JSF-generated id. For example:

```<code><input id="name"...>
</code>```

will be rendered as something like:

```<code><input id="j_id1234567:name"...>
</code>```

However, a search using XPATH can yield false positives. It also might not stay stable if a dev changes the ID, or if the id-generation algorithm changes.

2.(Recommended by friend who actually works with Selenium) Create empty CSS classes for the input elements, as CSS selectors can be used to locate an element in Selenium., e.g.

```<code><input id = "name"... class="... qa_name">
</code>```

where .qa_name is empty, and then use driver.findElement.(By.cssSelector(".qa_name")) to locate.

If you create one class per tested element, you have a deterministic way to identify the desired element. What concerns me about this is that

I don't know if this will create any overhead while loading the page.

The webapp this would be used for has a LOT of input fields.

Dev will probably not be thrilled about having to create a bunch of custom CSS for each page.

This doesn't seem like a proper use of CSS. I was under the impression that CSS was purely for styling, not giving information about an element.

Are one of these methods more valid than the other, or are these both valid? Also, are my concerns about these methods valid?

答:
First, you need to identify if there might be some logic to the ID's that you are simply not aware of. You state that Simply put, I don't know how the ID's are generated or when they change which makes me thing that there might be logic to these ID's that you are simply not aware of. As these ID's most likely matter when submitting data (they will likely function as keys in handling POST data), there is a good chance they are deterministic.

If your ID's are really dynamic, you need to go about this the other way. Let's say that you have a dynamically generated input form for a questionnaire. If you think about the way a user would fill out this form, they would not 'enter John Doe in the field with id fld_name'. Instead, they will see an element labeled 'Enter your full name' with a textbox along side it and enter their full name into that textbox. Write your test in that way: look for the logical 'grouping' of elements (such as a table row containing a label with the text 'Enter your full name') and from that level, determine where you need to go (the textbox that is present in the table row)

CSS can be useful as a selector, but should really only be used to identify items by their styling. Adding CSS specifically for UI-tests can easily be replaced by adding a data-dash attribute which is semantically clearer and much less subject to change.


问:
Will Java still be relevant in 5 years?
Will Java have the same importance it had in the past, or it will be less relevant than nowadays?</p>

答: It was losing importance in the mobile market, but with Android, it has regained it again.</p>

Title: Will Java still be relevant in 5 years?


问:
How do I learn linking compiling, makefile quickly? Any book recommendations?
I'm very good at programming in C++ but when it gets to linking and the other important stuffs I feel very ignorant. I want to learn allegro without wasting time. So please suggest a book or a resource to learn the concepts mentioned above. Thanks a lot in advance.</p>

答:
Understand make, and it will be your best friend.

Make is a kind of dataflow system. In a dataflow system you build the application from components, by connecting their input and output ports, where they send messages (data packets, or sometimes only triggers), so they finally form a processing network. See Wikipedia dataflow programming and flow-based programming articles.

In the case of make, the components are the compilation units, the messages are changes of files (source, object, other resource). When a file changes, it triggers a component (a compiling node), then the component, after doing its task, producing outputs, and triggering other components, which are doing same way, until the message chain reaches the final (sink) component, which produces a.out.

Opposite to other dataflow architectures, make does not run continuously. you have to launch it, when you feel that a file has changed, and it will trigger a component. If you run make when there's no changed files, so no component will be triggered, it says a "nothing to do" message and stops.

If there're parallel paths in the dataflow net, make can run components parallel, try make -j option. (It's an interesting effect that the G++ itself does not utilize multiple processors, but it does with the help of make.)

Making a good makefile is not trivial, but if you think of make as a dataflow application builder, it can be a very effective tool.


问:
Architecture supporting digitally signing of tons of soap requests
What is the optimal architecture for such case:

Web application(.Net Web Forms) connects to third party web service via wcf.

Third party web service accepts only digitally signed soap requests

Some typical business processes consist of several soap requests.

User must start business process (send several soap requests) via web application and digitally sign it in the front-end by its certificate (smart-card holding its certificate). Web application doesn't store any user certificates, it only stores user data that must be sent to web service.

My current thoughts are to create some proxy web service that would intercept user soap requests without digital signatures and put them into database. Then user would open some web form where he would see all requests that he must digitally sign. User signs requests via some web browser plugin. As the result of that operation web application gets digitally signed requests that it can send to original web service.

There is some problem with this realization though - it doesn't consider any if's logic and it can't use results gained from previous requests. The process of information exchange between web application and web service must be straightforward since user sends requests to fake proxy web service that can't return real data and results. So we would send data as-is hoping that there would be no results that our process of informational exchange would depend on.

Another option is to digitally sign all requests to web service in real-time. But I can't get how to do it in WCF. I can use IClientMessageInspector and intercept message before it would be sent to web service. In theory I can make some callback at this moment to frontend and wait for user to digitally sign request and then replace original request to user's one. But current realization of web application doesn't allow any callbacks to front end in WCF.

Any thoughts would be highly appreciated.

答:
This is definitely an asynchronous workflow.  The user cannot practically be in the loop in a blocking manner because it will tie up connections and resources upstream.

I would put unsigned messages on an queue for unsigned messages.  I would have a user-interface that subscribes to the queue for unsigned messages.  This could be EventSource-based for efficiency, but XHR long-polling will also suffice.  This interface would allow signing and would submit signed messages back to the server which would put them on a queue for signed messages.

A separate process which can actually be on any machine with access to the queue for signed messages would then submit those messages to the consuming service.


答:
I think you can do this with a combination of tech, its looks like you have most of it in place already.

1: website javascript or active X to communicate with the card reader

2: webserver side code for duplex communication with the client. this seems to be the bit you are missing. Its pretty new but this can now be done with websockets

http://www.asp.net/signalr

3: custom signing pipeline on the WCF service

so the flow would be

client -> establish websockets connection to webserver

client -> button clicked POST json command to server

webserver-> do logic and send commands to WCF service

WCF -> create messages to 3rd party SOAP endpoint

Custom WCF signing -> send message to webserver requesting that it be signed.. (maybe use a messaging queue?) wait....

webserver -> using websocket connection send message to client to be signed

client -> receive message and talk to card reader to get it signed

client -> send signed message back to webserver (again websockets)

webserver -> complete RPC style call from WCF by sending the signed message back

WCF Custom Signing : complete pipeline with signed message

Title: Architecture supporting digitally signing of tons of soap requests

Body:
What is the optimal architecture for such case:

Web application(.Net Web Forms) connects to third party web service via wcf.

Third party web service accepts only digitally signed soap requests

Some typical business processes consist of several soap requests.

User must start business process (send several soap requests) via web application and digitally sign it in the front-end by its certificate (smart-card holding its certificate). Web application doesn't store any user certificates, it only stores user data that must be sent to web service.

My current thoughts are to create some proxy web service that would intercept user soap requests without digital signatures and put them into database. Then user would open some web form where he would see all requests that he must digitally sign. User signs requests via some web browser plugin. As the result of that operation web application gets digitally signed requests that it can send to original web service.

There is some problem with this realization though - it doesn't consider any if's logic and it can't use results gained from previous requests. The process of information exchange between web application and web service must be straightforward since user sends requests to fake proxy web service that can't return real data and results. So we would send data as-is hoping that there would be no results that our process of informational exchange would depend on.

Another option is to digitally sign all requests to web service in real-time. But I can't get how to do it in WCF. I can use IClientMessageInspector and intercept message before it would be sent to web service. In theory I can make some callback at this moment to frontend and wait for user to digitally sign request and then replace original request to user's one. But current realization of web application doesn't allow any callbacks to front end in WCF.

Any thoughts would be highly appreciated.


答:
Just a few thoughts :

DDD

Domain model

Aggregate (and aggregate root)

Value objects, entities, services

Bounded context

Ubiquitous language

Domain Events

CQRS

Command (Command Handlers)

Events? (Event Handlers?) See Event Sourcing instead

Saga, process managers Sort of a neighboring approach, but not "core" CQRS per se

Read model / Write model

Projections (different read models)

Eventual consistency Not invented here, but definitely a key underlying concept

Title: CQRS and DDD terminology

Body:
Since CQRS and DDD do not imply one another I was curious what terms belong to DDD and what terms belong to CQRS. Because the two concepts are so much used together in the literature I usually mix them up.

I came up with this list of the terms that I think go to one camp or the other.

DDD

Domain model

Aggregate (and aggregate root)

Value objects, entities, services

Bounded context

Ubiquitous language

Events?

CQRS

Command (Command Handlers)

Events? (Event Handlers?)

Saga, process managers

Read model / Write model

Projections (different read models)

Eventual consistency

Could anyone correct me (and/or explain), what is where?


问:
What are the benefits of Docker?
Docker is becoming quite popular. I've used it as an end-user just 3 times, and it never worked as expected. But assuming it does work, can you please list some actual benefits? And contrast them with install scripts, for example (considering the overhead of the VM and the issues in VM-host communication).

There are two use-cases:

software that gets distributed to end-users for deployment

internal software that gets deployed on your own (or cloud) infrastructure.

Let's look at the 2nd case, which is more dominant. Why would I, as a developer, package my software with docker, if I can provide install scripts that do all of that, and thus have scriptable deployment without any extra overhead or learning curve? Or is docker mostly useful for the 1st usecase above?

答:
The primary advantage of Docker is the ability to create wholly deployable applications as build artifacts.  The deployable applications can be run through test suites that verify that they operate correctly before promotion as production images.

This differs substantially from install scripts because the testing is done before production and less is subject to change.

I would not consider Docker to be a good solution for distributing software to end-users.  I see it as internal software for your own cloud computing infrastructure.

As for the VMs vs containers discussion it seems that many CSPs (Cloud Service Providers) are building container offerings which make single VMs single Docker hosts.  This seems like the worst of all worlds since it requires the additional setup of the containers and the coarse grained allocation of VMs beneath them.  Secure container native infrastructure should be demanded by any customer running Docker in production.  At minimum, container-based allocation and transparent distribution of containers across physical machines is essential.

Title: What are the benefits of Docker?


问:
Where to describe architectural problems?
I joined the middle of a middle size project, which runs already for several years. One of problems is that the document describing the architecture was never written. Now I was assigned a task to write the architecture description.

During the time I working on this project, I gathered all information I needed to write the document. Since I also added some features, I identified some pieces of code, which are clearly breaking the architecture as it is described.

For example, the GUI was supposed to be a thin layer, without business logic. That is what I was told. The implementation contains lots of logic.

My boss assigned me the task, to write the document describing the architecture of the system. The target audience are current and future developers working on the project. I need to describe what should be, but I also need to describe the deviations somehow.

So, where should I describe these problems? Bugs tracking software? Or should I describe implementation's deviations from the architecture in the document describing the architecture of the system?

答:
If you are documenting a design or architecture of a system that has already been built, the document should describe it as-built and not as-designed or as-intended. If there are oddities or discrepancies in the architecture, then this document should call out those issues and explain them as much as possible to a reader.

If you are able to get information from people who have worked on the system from the beginning (or at least longer than you have), it would be useful to capture more information about what was actually intended and why the architecture and design deviated from this intention.

At the end of the day, a design document should serve as a guide to the code. If the document doesn't help a new developer understand the current state of the code base and how it is structured, than the document isn't useful.

This document should be a living document that is used to guide future planning and design of changes to the system and then updated accordingly, within your development process. As the design changes and evolves over time, the document should also help developers understand why things are the way they are at present.

If you are looking for advice on capturing the architecture, I like the approach advocated in IEEE Standard 1016-2009 IEEE Standard for Information Technology - Systems Design - Software Design Description. It provides a reasonable structure for a design description, which can be used to capture both architectural and detail level design information.

I would also consider these deviations to be a form of technical debt. It may be a large undertaking, perhaps even a small project, to fix the issues, I would recommend making the existence of the technical debt more visible. If that means you use your defect tracking tool, then you can put one or more issues there. If you have another tool that you use for tracking suggestions and enhancements to the software, that may be another place to put it.


答:
When formalizing the architecture of the system it is important that you understand not only the value behind what the architecture will bring to the table, but also to understand and appreciate what it should be.

The primary goals of Software or Technical Architecture is to identify the Non-Functional requirements that are realized by the Quality Attributes that will drive the System Architecture.

On Non-Functional Requirements:

A non-functional requirement is a requirement that specifies criteria
  that can be used to judge the operation of a system, rather than
  specific behaviors. They are contrasted with functional requirements
  that define specific behavior or functions. The plan for implementing
  functional requirements is detailed in the system design. The plan for
  implementing non-functional requirements is detailed in the system
  architecture.

Broadly, functional requirements define what a system is supposed to
  do and non-functional requirements define how a system is supposed to
  be. ... Non-functional requirements are often called "quality attributes" of a system. Other terms for non-functional requirements are "qualities", "quality goals", "quality of service requirements", "constraints" and "non-behavioral requirements"

Of course identifying the architecturally significant requirements makes sense when on a greenfield project, however when working with existing software, it is best to be as disciplined as possible.  You will not want your software architecture to be influenced by the existing system.

Software architecture to be authoritative really needs to be 3 things.

Declarative

This is the part of the documentation where you declare NOT WHAT IS, but how things SHOULD BE.  We do this through the use of various Architectural Views of the system.  We define the components that should be, how they interact, and then we optionally drill down into each component for more granular views that declare how the system should be designed.

This is an important distinction.  The System Design should be constrained by the System Architecture, they are in fact separate but related things.

Rationale

The Rationale of your Software Architecture is what provides legitimacy and authority to the architecture decisions that were made.  Perhaps the decision was made to utilize a Pub/Sub event listener over MQ for triggering a batch job and you diagram it?

Why was this decision made?  We explain why in the Rationale section and link back our explanation to Non-Functional Requirements, Quality Attribute Goals, or Architecturally Significant Requirements. (Eg. Jobs must be asynchronous and repeatable, Maintainability as a quality attribute drives that in the event of a batch job failure that jobs can be re-initiated via an MQ message, The System must have Zero Message Loss with asynchronous communication, etc...)

Risks

Now that you have declared how architecture should be and proved it with your Rationale, you can now identify Risks on the current state of the system to where this doesn't abide.

(Eg. Server side validation is being duplicated on the client side Javascript code.  This is a violation of the DRY principle and this runs counter to the Quality Attribute of Maintainability.  There are no Non-Functional requirements defined around Performance in this area so there is no Rationale for the current system behavior)

Your Risks can also diagram where current state is currently deviating from Architecture.  These Risks can be addressed by the development team now, either through their project plan or by adding this into the backlog.

Title: Where to describe architectural problems?

Body:
I joined the middle of a middle size project, which runs already for several years. One of problems is that the document describing the architecture was never written. Now I was assigned a task to write the architecture description.

During the time I working on this project, I gathered all information I needed to write the document. Since I also added some features, I identified some pieces of code, which are clearly breaking the architecture as it is described.

For example, the GUI was supposed to be a thin layer, without business logic. That is what I was told. The implementation contains lots of logic.

My boss assigned me the task, to write the document describing the architecture of the system. The target audience are current and future developers working on the project. I need to describe what should be, but I also need to describe the deviations somehow.

So, where should I describe these problems? Bugs tracking software? Or should I describe implementation's deviations from the architecture in the document describing the architecture of the system?


问:
How is polymorphism better than two function calls in this example [ATM design]?
So I've finally started reading Designing Object-Oriented Software and my needle is stuck at a small but important point. I understand that the example I'm about to present might appear a bit out of context, because it's being developed in the book over the last few chapters, but I believe the overall idea is really simple and I'll do my best to provide context wherever I can. About me, I'm a junior developer teaching myself, so I'm hoping putting this question here will result in some fruitful discussion.

Well, finally we have the preliminaries out of the way.

The system I'm talking of an Automated Teller Machine (ATM), which we need to model in terms of object-oriented software. The discussion is about input classes that will gather numeric input from user. Two possible cases are identified - gathering account numbers, amounts, etc., and gather the PIN, which are to be rendered differently (the PIN being displayed like a password field).

So the authors defined two different classes - Form and SecureForm, the latter deriving from the former.

Now here's a section from the book (debating the utility of SecureForm) that's causing me trouble:

The intended distinction between Form and SecureForm is whether user
  input is echoed literally or symbolically (perhaps with an X). This
  can be done by invoking two different messages: getValue() and
  getSecureValue(), but the sender [the class making the request]
  would have to test to determine which message to send. This could lead to maintenance difficulties. It is better to use polymorphism;
  that is, to have one message that invokes different methods depending
  on the class of object to which it is sent. For this reason we keep
  SecureForm [that is, don't discard it from our design].

The part in italics doesn't make sense to me. What would the calling object have to test? Perhaps for the type of input required, but then to me it doesn't seem to make a difference whether you use polymorphism or not. Consider the following two hypothetical examples:

```<code>//inside doTransaction function of WithdrawalTransaction

//example 1
form = new Form();
pin = form->getSecureValue();

//example 2
form = new SecureForm();
pin = form->getValue();
</code>```

Hardly seems different to me, and not a "maintenance nightmare" by any measure.

I feel like there's some subtlety I'm missing here, but it eludes me. I'll be very grateful if someone can help me decipher the author's intent, and even better if some examples can be provided.

I hope there isn't any critical information missing from my post. If there is, please point out and I'll add more details.

答:
I interpret that to mean that while you could have a SecureForm which implements both a getValue and a getSecureValue, you shouldn't because it becomes a maintenance headache.

In other words, like that, the caller would have to make a distinction in the code on how to call the instance of SecureForm, being careful not to call getValue but getSecureValue if that is what was desired.

You'd end up with code like this everywhere in your program:

```<code>String value;
if (form instanceof SecureForm) {
  value = ((SecureForm)form).getSecureValue();
} else {
  value = form.getValue();
}
</code>```

Having to know what type it is is very much an anti-pattern.
True polymorphism means not caring how getValue is implemented.  If you need to call getValue AND getSecureValue in SecureForm, then you're not doing something right (and you should probably not be structuring your code in this fashion in that case).  SecureForm can call getSecureValue internally, but one instance of Form should be interchangeable with any other instance though Listkov's principle.

Body:
I interpret that to mean that while you could have a SecureForm which implements both a getValue and a getSecureValue, you shouldn't because it becomes a maintenance headache.

In other words, like that, the caller would have to make a distinction in the code on how to call the instance of SecureForm, being careful not to call getValue but getSecureValue if that is what was desired.

You'd end up with code like this everywhere in your program:

String value;
if (form instanceof SecureForm) {
  value = ((SecureForm)form).getSecureValue();
} else {
  value = form.getValue();
}

Having to know what type it is is very much an anti-pattern.
True polymorphism means not caring how getValue is implemented.  If you need to call getValue AND getSecureValue in SecureForm, then you're not doing something right (and you should probably not be structuring your code in this fashion in that case).  SecureForm can call getSecureValue internally, but one instance of Form should be interchangeable with any other instance though Listkov's principle.


问:
What is a good security practice for storing a critical database on developer's laptops?
We have a few givens:

Developers need a replica of the production database on their machines.

Developers have the password to said database in the App.config files.

We don't want the data in said database compromised.

A few suggested solutions and their drawbacks:

Full-disk-encryption. This solves all problems, but degrades the laptop's performance, and we are a start-up, so don't have money for powerhorses.

Creating a VM with encrypted hard disk, and store the database on it. It works well, but it doesn't help too much, since there's a password in Web.Config.

Solution number 2 + requiring the developer to type the database password every time he runs anything. It solves all problems, but it is really cumbersome for developers that sometimes fire up the application multiple times a minute. Also, we have multiple applications that connect to the same database, and implementation of a password screen will have to differ in each.

So, my question is, if there's any common solution to such problem, or any suggestions on how to make any of the above solutions workable?

答:
Not only do you not want a copy of the production database, it may actually be illegal. For example, in the US, you cannot move production data out of the production environment if it contains regulated information like personal health data, financial data, or even data that could be used in identity theft. If you do, you could be fined, lose your compliance standing and therefore be subject to more aggressive audits, or even be named in a lawsuit.

If you need production-scale data for testing, you have a couple options:

Generate all dummy data. This is trickier than it sounds. It's surprisingly difficult and labor-intensive to generate sensible imaginary data.

Anonymize your production data. This may be easier, but proceed with caution.

For option #2

In the production environment, an authorized database admin makes a copy of the production data.

Still in the production environment, the same authorized admin runs a routine that anonymizes all sensitive data. If in doubt, anonymize.

Only then should the data be moved to another environment.


答:
Just in that 4 line example there is a lot of things that are subtly bad practice.  The caller knows too much about the underlying implementation of the callee and the callee knows a bit too much on how things are calling in to it. Ideally these two things should not know about each other.

A big strength of polymorphism is that the details of how or what are hidden away from the caller because they don't care or need to know about it.  Also enforcing implementations to obey a contract (interface) will make it easier on the caller.  Unneeded intimate knowledge leads to unnecessary tight coupling which can lead to a maintenance nightmare.

Title: How is polymorphism better than two function calls in this example [ATM design]?

Body:
So I've finally started reading Designing Object-Oriented Software and my needle is stuck at a small but important point. I understand that the example I'm about to present might appear a bit out of context, because it's being developed in the book over the last few chapters, but I believe the overall idea is really simple and I'll do my best to provide context wherever I can. About me, I'm a junior developer teaching myself, so I'm hoping putting this question here will result in some fruitful discussion.

Well, finally we have the preliminaries out of the way.

The system I'm talking of an Automated Teller Machine (ATM), which we need to model in terms of object-oriented software. The discussion is about input classes that will gather numeric input from user. Two possible cases are identified - gathering account numbers, amounts, etc., and gather the PIN, which are to be rendered differently (the PIN being displayed like a password field).

So the authors defined two different classes - Form and SecureForm, the latter deriving from the former.

Now here's a section from the book (debating the utility of SecureForm) that's causing me trouble:

The intended distinction between Form and SecureForm is whether user
  input is echoed literally or symbolically (perhaps with an X). This
  can be done by invoking two different messages: getValue() and
  getSecureValue(), but the sender [the class making the request]
  would have to test to determine which message to send. This could lead to maintenance difficulties. It is better to use polymorphism;
  that is, to have one message that invokes different methods depending
  on the class of object to which it is sent. For this reason we keep
  SecureForm [that is, don't discard it from our design].

The part in italics doesn't make sense to me. What would the calling object have to test? Perhaps for the type of input required, but then to me it doesn't seem to make a difference whether you use polymorphism or not. Consider the following two hypothetical examples:

```<code>//inside doTransaction function of WithdrawalTransaction

//example 1
form = new Form();
pin = form->getSecureValue();

//example 2
form = new SecureForm();
pin = form->getValue();
</code>```

Hardly seems different to me, and not a "maintenance nightmare" by any measure.

I feel like there's some subtlety I'm missing here, but it eludes me. I'll be very grateful if someone can help me decipher the author's intent, and even better if some examples can be provided.

I hope there isn't any critical information missing from my post. If there is, please point out and I'll add more details.


问:
Does Python have any features which can be used for encapsulating private data?
Usually in OOP world we are told that modularity is a good practice and keeping loose coupling between module is a great thing. Encapsulation helps us achieve this loose coupling.

In Java encapsulation is achieved via access modifiers, in Ruby we have stricter rules via attr_accessor.

But what about Python? I see that I can't hide my fields or methods except using tricks like __ in front of names. Is this the correct / only way to achieve encapsulation in Python?

答:
Take a look at the following C++ code:

```<code>#include<iostream>
using namespace std;

class Foo {
    private:
        int x;

    public:
        Foo(int x): x(x) {}

        void printX() {
            cout << "My x is " << x << endl;
        }
};

int main(int argc, char** argv) {
    Foo foo(12);
    foo.printX(); // prints "My x is 12"

    //foo.x = 13; // error: ‘int Foo::x’ is private

    *((int*) &foo) = 14;
    foo.printX(); // prints "My x is 14"

    return 0;
}
</code>```

I've broken the encapsulation by casting a pointer. Does that mean encapsulation is broken in C++? No - because no one in their right mind would do that! Cast at your own risk.

It's the same with Python - use fields prefixed with _ at your own risk. Encapsulation is for safety - not for security. You don't put private keys in private fields and trust the encapsulation to prevent users from touching them. You use encapsulation to protect the users of your classes from internal implementation details - and if these users don't respect Python's convention it's their own damn problem.

Body:
Take a look at the following C++ code:

#include<iostream>
using namespace std;

class Foo {
    private:
        int x;

    public:
        Foo(int x): x(x) {}

        void printX() {
            cout << "My x is " << x << endl;
        }
};

int main(int argc, char** argv) {
    Foo foo(12);
    foo.printX(); // prints "My x is 12"

    //foo.x = 13; // error: ‘int Foo::x’ is private

    *((int*) &foo) = 14;
    foo.printX(); // prints "My x is 14"

    return 0;
}

I've broken the encapsulation by casting a pointer. Does that mean encapsulation is broken in C++? No - because no one in their right mind would do that! Cast at your own risk.

It's the same with Python - use fields prefixed with _ at your own risk. Encapsulation is for safety - not for security. You don't put private keys in private fields and trust the encapsulation to prevent users from touching them. You use encapsulation to protect the users of your classes from internal implementation details - and if these users don't respect Python's convention it's their own damn problem.


问:
Refactoring three very similar classes using inheritance?
I'm currently working on refactoring the code-base for one of our services. I'm been going through reviewing everything, and I feel it's a bit scattered, and could probably adhere to OOP principles better.

I have three classes that are all derivative of another class Cache. All three of these classes perform the exact same operations, the only difference is the type of object they are querying for and what method call they use to query them. What would be the best method of making these classes even more simple?

```<code>public static class ZenDeskCache
{
    public static ZendeskApi Api = new ZendeskApi(GlobalVariables.ZendeskUrl, GlobalVariables.ZendeskUser,
        GlobalVariables.ZendeskPass);

    public class Users : Cache<Users, List<User>>
    {
        protected override List<User> GetData()
        {
            var users = Api.Users.GetAllUsers();
            var allUsers = new List<User>(users.Users);

            while (users.NextPage != null)
            {
                users = Api.Users.GetByPageUrl<GroupUserResponse>(users.NextPage);
                allUsers.AddRange(new List<User>(users.Users));
            }

            allUsers = allUsers.OrderBy(n => n.Name).ToList();

            return allUsers;
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromDays(1);
        }
    }

    public class Organizations : Cache<Organizations, List<Organization>>
    {
        protected override List<Organization> GetData()
        {
            var organizations = Api.Organizations.GetOrganizations();
            var allOrgs = new List<Organization>(organizations.Organizations);

            while (organizations.NextPage != null)
            {
                organizations = Api.Users.GetByPageUrl<GroupOrganizationResponse>(organizations.NextPage);
                allOrgs.AddRange(new List<Organization>(organizations.Organizations));
            }

            allOrgs = allOrgs.OrderBy(n => n.Name).ToList();

            return allOrgs;
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromDays(1);
        }
    }

    public class Groups : Cache<Groups, List<Group>>
    {
        protected override List<Group> GetData()
        {
            var groups = Api.Groups.GetGroups();
            var allGroups = new List<Group>(groups.Groups);

            while (groups.NextPage != null)
            {
                groups = Api.Groups.GetByPageUrl<MultipleGroupResponse>(groups.NextPage);
                allGroups.AddRange(new List<Group>(groups.Groups));
            }

            allGroups = allGroups.OrderBy(n => n.Name).ToList();

            return allGroups;
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromSeconds(600);
        }
    }
}
</code>```

答:
Could you create a generic class with a type variable for the varying data class?

```<code>public class WhateverCache<T> : Cache<T, List<T>> {
  protected override List<T> GetData() {
    // whatever logic you have
  }
</code>```

The specific classes would only override the time span-defining method.

Body:
Could you create a generic class with a type variable for the varying data class?

public class WhateverCache<T> : Cache<T, List<T>> {
  protected override List<T> GetData() {
    // whatever logic you have
  }

The specific classes would only override the time span-defining method.


问:
What is the supposed productivity gain of dynamic typing?
I often heard the claim that dynamically typed languages are more productive than statically typed languages. What are the reasons for this claim? Isn't it just tooling with modern concepts like convention over configuration, the use of functional programming, advanced programming models and use of consistent abstractions - all of which could be used in statically typed languages as well? Admittedly there is less clutter because the (for instance in Java) often redundant type declarations are not needed, but you can also omit most type declarations in statically typed languages that use type inference, without losing the other advantages of static typing. And all of this is available for modern statically typed languages like Scala as well.

So: what is there to say for productivity with dynamic typing that really is an advantage of the type model itself?

Clarification: I'm more interested in big / medium sized projects than in quick hacks. :-)

答:
I think first of all you need to define "productivity". What does "productivity" mean and include?

If by "more productive" you mean writing less lines of code to implement the same feature, then yes, dynamic-typing programming languages are more "productive" than static-typing languages.

However, if you also consider the time spent on debugging and bug fixing, then dynamic-typing languages may not be that productive, because dynamic-typing languages tend to push the error checking to run-time while, in contrast, static-typing languages can perform some error checking in compile time. As it is commonly accepted that, usually, the later a bug is found, the more expensive to fix that bug. Therefore, dynamic-typing code may result in the generally equal or perhaps even less than the productivity than static-typing code.

ContentLicense: CC BY-SA 4.0


问:
How can I write a flexible messaging structure for sending TCP messages to clients and server
The general question: how can I write a flexible, but not property heavy, messaging structure for sending TCP messages to clients and server?

Example:

I have a TCP Server for a game that sends some messages through TCP sockets to clients:

Chat messages, including chat text, chat room, and speaker.

Game messages, including game actions and events

Client messages, including clients connecting, logging in, and disconnecting

To achieve this, when one of these actions occurs within the program, an event handler is called generating some specific event type.

```<code>ChatEvent with ChatEventArgs
GameEvent with GameEventArgs
ClientEvent with ClientEventArgs
</code>```

These all extend the EventArgs class.

Now to my question. As things get more complex, I begin to cram more pieces of info into these EventArgs. My GameEventArgs start as

```<code>GameEventArgs gameArgs = new GameEventArgs(GameAction.Start);
gameArgs.gameId = "gameId123";
gameArgs.turn = "thisPlayersTurn";
JSON json = GameEventArgs.ToJson(gameArgs);
SendMessageToClient(json);
</code>```

From this you can gather that GameEventArgs has some public properties such as gameId and turn. But a game is more than IDs and Turns. The client will need to receive game actions, which can be very complex. Suddenly the GameEventArgs needs more and more properties. This is fine, except, that only a few of these properties will be sent at a time. There could be 20-40 unused properties of GameEventArgs. Should I make more classes that inherit GameEventArgs, and only contain certain properties? I will be sending messages often, and I want to take the GC into consideration, as these messages are one time uses. (Should they then be IDisposable?).

Is there a better method to go about creating a messaging structure, where only a few of the defined properties of the message will be used at one time?

答:
This problem has been solved very elegantly by Google, in their protocol buffers project.  It has some issues that you need to be comfortable.  It is a binary format.  The sender and receiver need to agree on the message type being transferred (but not the message type version), and last time I checked the C# implementations were not Google implementations (or followed their API style).

However, the plus of having a light weight (both bytes and CPU) message format, that copes well with out of version sync client/servers and has a lot of features by default for message specifications are a winner for me.


答:
Corbin March's answer is pretty good, I will just add an additional detail, that you generally have two classes of data in your production database: system/application metadata; and client user data/transactional data.  This latter should NEVER be used in a development environment "as is."

It's very rare indeed that you need actual production client information to do development with.

However, if the problem that the OP is describing here involves trade secret data or otherwise highly proprietary system data that doesn't involve customer data, that is required by devs...the security approach has to involve a scheme that doesn't have the db password kept in cleartext in a resource file somewhere. There needs to be a mechanism to, for example, regenerate a daily password, that isn't stored on disk.

Title: What is a good security practice for storing a critical database on developer's laptops?

Body:
We have a few givens:

Developers need a replica of the production database on their machines.

Developers have the password to said database in the App.config files.

We don't want the data in said database compromised.

A few suggested solutions and their drawbacks:

Full-disk-encryption. This solves all problems, but degrades the laptop's performance, and we are a start-up, so don't have money for powerhorses.

Creating a VM with encrypted hard disk, and store the database on it. It works well, but it doesn't help too much, since there's a password in Web.Config.

Solution number 2 + requiring the developer to type the database password every time he runs anything. It solves all problems, but it is really cumbersome for developers that sometimes fire up the application multiple times a minute. Also, we have multiple applications that connect to the same database, and implementation of a password screen will have to differ in each.

So, my question is, if there's any common solution to such problem, or any suggestions on how to make any of the above solutions workable?


问:
Java - Using a Function variable to set the toString() method's return value
Lately I've started adding this to certain classes in an in-house API:

```<code>public class MyClass {

  // I usually do this with classes I expect to
  // be printed out or tested a lot (particularly
  // in the early stages of creating the class/package).
  //
  // Having one field is not a criteria for doing this,
  // just a simple example.  And of course there is always
  // a default value for the toString field.

  private Object oneOtherFieldExample;

  private Function<MyClass, String> toString =
      myClass -> String.valueOf(oneOtherFieldExample);

  ...

  public void setToString(Function<MyClass,String> toStringFunction) {
    toString = toStringFunction;
  }

  public String toString() {
    return toString.apply(this);
  }
</code>```

This has come in handy a couple times but since I'm working on an in-house API I'm wondering

Do you all foresee any potential issues I'm missing?

Is this reasonably legible and intuitive?

Does this or something similar already exist as some kind of pattern (and if so, what is it called)?

Since this is especially used for testing and early building, should I add a static way to set the default toString variable to avoid having to set it manually every time I instantiate a new MyClass Object (in the case where thousands are being created)?

答:
First-Class functions and Higher Order Functions

A programming language has first-class functions if it supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

In languages where functions are first-class citizens, functions can be passed as arguments to other functions in the same way as other values (a function taking another function as argument is called a higher-order function).

It's a perfectly valid, well-respected technique, especially among the Functional Programming crowd. As you've already discovered, it allows you to change the behavior of a class without changing the class itself.

The canonical example of higher-order functions is Map.  The Map function accepts a function as a parameter and iterates over a list, applying the function to each item in the list.

```<code>void map(int (*f)(int), int x[], size_t n) {
    for (int i = 0; i < n; i++)
        x[i] = f(x[i]);
}
</code>```

Another example of higher-order functions is a comparator.  Comparators are used in sort functions to define how the sort compares one value in the collection to another value for ordering purposes.

```<code>var result = MergeSort(listOfImaginaryNumbers, ImaginaryNumberComparator);
</code>```

Is this a viable technique for your scenario?

To be fair, any given class should already know how to ToString() itself, without any help from the outside world.  If I were designing such a class, and I needed some variation on the ToString() output, I would probably provide some parameter in the constructor that the ToString() method could use to modify its behavior, rather than resorting to first-class functions.  Or I would examine the state of the object to decide how ToString() should behave.  To be genuinely useful, the first-class function would have to have knowledge of your class's internals, which would violate encapsulation.

Depending on exactly what you want to accomplish, a Map function might be a suitable alternative.

Further Reading

First-Class Functions

Body:
First-Class functions and Higher Order Functions

A programming language has first-class functions if it supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

In languages where functions are first-class citizens, functions can be passed as arguments to other functions in the same way as other values (a function taking another function as argument is called a higher-order function).

It's a perfectly valid, well-respected technique, especially among the Functional Programming crowd. As you've already discovered, it allows you to change the behavior of a class without changing the class itself.

The canonical example of higher-order functions is Map.  The Map function accepts a function as a parameter and iterates over a list, applying the function to each item in the list.

void map(int (*f)(int), int x[], size_t n) {
    for (int i = 0; i < n; i++)
        x[i] = f(x[i]);
}

Another example of higher-order functions is a comparator.  Comparators are used in sort functions to define how the sort compares one value in the collection to another value for ordering purposes.

var result = MergeSort(listOfImaginaryNumbers, ImaginaryNumberComparator);

Is this a viable technique for your scenario?

To be fair, any given class should already know how to ToString() itself, without any help from the outside world.  If I were designing such a class, and I needed some variation on the ToString() output, I would probably provide some parameter in the constructor that the ToString() method could use to modify its behavior, rather than resorting to first-class functions.  Or I would examine the state of the object to decide how ToString() should behave.  To be genuinely useful, the first-class function would have to have knowledge of your class's internals, which would violate encapsulation.

Depending on exactly what you want to accomplish, a Map function might be a suitable alternative.

Further Reading

First-Class Functions