答:
The Strategy pattern is what I would use for this (encapsulating an algorithm). How the alignment is done is something that can be configured at runtime. There are also lots of different ways of aligning elements so you encapsulate them behind an interface. The example below is one way you could use strategy pattern with your Aligner class.</p>

```<code>class Panel
{
    UIElement[] Children;
    IAligner Aligner;

    public SetAlignment(IAligner aligner)
    {
        this.Aligner = aligner;
    }

    public void Render()
    {
        Aligner.Align(Children)
        Display(Children)
    }
}

interface IAligner
{
    void Align(UIElement[] elements)
}

class LeftAligner : IAligner
class RightAligner: IAligner
class CenterAligner: IAligner
</code>```

Body:
The Strategy pattern is what I would use for this (encapsulating an algorithm). How the alignment is done is something that can be configured at runtime. There are also lots of different ways of aligning elements so you encapsulate them behind an interface. The example below is one way you could use strategy pattern with your Aligner class.

class Panel
{
    UIElement[] Children;
    IAligner Aligner;

    public SetAlignment(IAligner aligner)
    {
        this.Aligner = aligner;
    }

    public void Render()
    {
        Aligner.Align(Children)
        Display(Children)
    }
}

interface IAligner
{
    void Align(UIElement[] elements)
}

class LeftAligner : IAligner
class RightAligner: IAligner
class CenterAligner: IAligner


问:
Is PHP actually a web framework?
I was reading an article/interview (Language War: PHP vs. Ruby (by Jeffrey Way; Mar 2011)) by a developer for Envato using Ruby. He says, "PHP is a web framework disguised as a language."

He didn't expound on that statement, so it got me wondering if that is true, and if so how. I did a bit of research but couldn't turn up any information on this topic. I'm wondering how this statement is true and what makes PHP not a programming language. And why do other languages like python or ruby not fit in that category?

答:
I don't have sources - but the statement makes some sense, even if it might just be an attempt to stir controversy.

PHP is definitely a language, and very much not a framework - but if you look at the PHP manual versus, say, the C or C++ specification, the body of functionality that PHP offers has elements that would be considered in the domain of a framework: PDO, XML handling, and so on - this stuff is what would normally be included in a framework like Qt.

ContentLicense: CC BY-SA 3.0

Title: Is PHP actually a web framework?


答:
Officially:

PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.

According to http://us.php.net/

But that isn't necessarily a very apt description.

PHP is a Turing complete computer language. However any distribution of PHP is going to come with a huge number of standard libraries, so much so that the standard PHP libraries could be classified as a framework.

Therefore, when looked at in this way, PHP is either:

A framework with its own unique Turing complete scripting language.

Or

A language wrapped in a massive web-framework, from which it can not be removed.

However if we look at the name "PHP: Hypertext Preprocessor" (PHP), this implies that PHP is a "Preprocessor" (that preprocesses Hypertext) - neither a framework, nor a language, but a piece of software.

When you look at it that way, PHP is an application that runs scripts in a proprietary language, with access to a large internal framework designed to process Hypertext.

Therefore: PHP can not properly be classified as either a framework or as a language. The truth is that there is a language, a framework, and an application, that all have the same name (because they are all rolled into one thing)! Thus "PHP" can refer to any part of the system.

Title: Is PHP actually a web framework?

Body:
I was reading an article/interview (Language War: PHP vs. Ruby (by Jeffrey Way; Mar 2011)) by a developer for Envato using Ruby. He says, "PHP is a web framework disguised as a language."

He didn't expound on that statement, so it got me wondering if that is true, and if so how. I did a bit of research but couldn't turn up any information on this topic. I'm wondering how this statement is true and what makes PHP not a programming language. And why do other languages like python or ruby not fit in that category?


问:
Combining Single Page Application and DDD with a REST API
I'm creating a web application which on the client side consists of a Single Page Application (with Durandal) and on the server side an ASP.NET MVC site with a Domain Driven Design. The two are connected with a REST Api (Web API).

I have a relation between two entities, which on the database level is many-to-many. (Hotels <=> RoomTypes). Since in DDD a best practice is not to have many-to-many relationships I built it so that it can only be navigated from the roomtype to the hotel (since a hotel can exist without roomtypes, but a roomtype should always be associated with a hotel). The relation itself also has attributes (availability for example).

My current issue is how to associate a hotel with a roomtype however. Following DDD practices I would add a method AddHotel to the RoomType-class.
The problem is that in the SPA, you can edit all the attributes of a roomtype (pictures, description, ...) and associated hotels in a single view. After editing these attributes, an update is submitted via the rest api. This means that everything gets submitted in one call to the server.

How would you structure the server and the rest based API so that:

the domain stays in place and there's correct validation inside the RoomType-class

you can post atomic updates from the single page application through the rest

there's no code duplication on the server and the single page application

答:
You seem to hint at your own answer: don't submit everything in one go. If you think about it, what kind of actions would you like to be able to do in your view? One of them is apparently assigning hotels to room types. So for every action you want to perform in your view you either have a method you call on a endpoint controller, or if you want to work with commands, you'd form a AssignHotelToRoomTypeCommand with all the necessary data for executing that procedure, and send that command to an endpoint.

The more I think about it though, assigning a hotel to a room type seems a bit weird/backwards to me... Is there a reason you are modelling a room type as an entity and not a value object?


问:
How to justify migration from Java 6 to Java 7?
We were migrating from Java 6 to Java 7. The project is behind schedule and risks being dropped, in which case it will continue to use Java 6.

What are the specific improvements in Java 7 that we could go back to our manager with and convince him it is important to use JDK 7? Looking for bug fixes that  I could highlight in Oracle Java 7 (with respect to Java 6). Fixes in security, performance, Java 2D/printing, etc. will be more sellable in my case. Compiler fixes for example, will not of much use.

[I am going through many sites like Oracle adoption guide, bug database, questions on Stack Overflow].

Update: Thanks for the answers.  We rescheduled the update to next release.  Closest we got was security.  Accepting the highest voted answer.

答:
Java 6 has reached EOL in February this year and will no longer receive public updates (including security) unless you buy very expensive enterprise support.

That should be all the reason needed.

Besides, overwhelming evidence suggests that backwards compatibility for Java runtimes is excellent. Chances are that you just have to replace the Java 6 installations with Java 7 and all applications will just continue to work without any problems. Of course this is not guaranteed and extensive tests are recommended to confirm that there will indeed be no problems.


问:
C++ Web Development: Wanting a minimalist start
I'm currently working on a Computer Science degree, and I want to build my own Web Server library. The problem? Every search I've done on interacting with web sites points to "Use this library that was built by someone else" - instead of explaining the basics of sending and receiving information.

I'm not asking for a lot - I just want to enter a single alpha-numeric character on a web page, hit a button, and have that one byte of information sent to a C++ program, without the aid of a non-standard library.

答:
Boost.Asio is currently being converted to be (one of?) the future C++ standard way to do networking. (Here is one of the papers: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3388.pdf )

It's really the most basic portable asynchronous communication system you will find using modern C++, as it abstract away other socket libraries or platform provided ones.

All the modern C++ http networking libraries (CppNetlib and CPPCMS) relies on it. I suggest you build your library around it provide basics for sockets and asynchronous (and synchronous) comunication but don't setup a full system for you. Maybe in a few years you can even replace Boost.ASIO by the C++ standard equivalent.

Also, the documentation of Boost.Asio provide insight on how communication works in this kind of context. So reading it might answer a lot of your questions.

And if you want to understand the lower level, read the Asio code. It's a bit hard to read if you're not used to C++ meta-programming and other C++ idioms but you would learn a lot by reading it.


答:
The thing with PHP is that it's not just a programming language, but an entire ecosystem, consisting of:

The PHP programming language itself

A runtime that can hook into a web server (through mod_php or CGI/FastCGI), and provides lots of ways to interact with it

A large library of built-in functions and classes, many of them web related

PHP provides features in the language itself that are very specific to web programming, such as the superglobals ($_SERVER, $_GET, $_POST, $_COOKIE, etc.), jumping between PHP mode and HTML mode using <?php ?> tags, etc., and its semantics are built around the one-process-per-request execution model that was the norm back in the early days of server-side web programming. PHP started out as a web scripting tool, and only evolved into a (somewhat) general-purpose programming language later; the CLI version and other non-web features, even though they can often be used quite effectively, are an afterthought, and with enough exposure to the language and its ecosystem, this can become painfully obvious at times.

By contrast, most other programming languages were designed as general-purpose, systems or application programming languages from the beginning, and anything specific to web programming comes in libraries. If you want to do web programming in, say, Python, you need a web framework, or at least a library to implement web server bindings and things like request parsing, HTML templating and session management, and probably some database bindings too (unless you're really hardcore and write all that from scratch).

PHP has all these things built into it by default, and that's why people like to say that PHP is a web framework in itself.

For a "Hello, world!" web application in Python, you'd typically set up a virtualenv, install some libraries, set up some boilerplate for the web framework, define routes, and write a handler that generates a response with "Hello, world!" in the body; in PHP, it's a matter of writing <?php echo "Hello, world!" in index.php, copying it to apache's docroot, and enabling mod_php. The rest (hooking into the server, parsing requests, generating responses, etc.) still happens, but PHP takes care of it for you.

Title: Is PHP actually a web framework?


问:
How to design a composite pattern in Python?

The concept

I'm programming an interface over pygame as a personal project, to make the creation of games easier for me.

So far I managed to design an architecture that behaves like this :

Objects are displayable components that can appear and move on the screen

Objects can have children objects

When an object displays itself, it ask all his children to display themselves on the parent's surface.

Objects have three important elements : a callback system, a graphics system and a physics system to respectively act, display and move.

Then, when I want to create a game "scene", I create a "root" object that contains other objects like the player, the mouse, the ground, monsters...

Then I just have to ask the root to display itself, and every object appears recursively.

I designed this without knowing about the composite pattern at first, only the basics of OOP.

My main issue was to make the substitutability property of objects that comes from inheritance to work well with the recursive composition I made.

I mean that I have an "abstract" class called "Object" (I put abstract into quotes because Python doesn't really have such concept) that is inherited by classes like "Image" (to be able to display) or "MovingObject" (to be able to move).
Here, inheritance is meant to extend my object abilities.

But my composite pattern requires that "groups of objects must be considered the same as single objects".

So when I call recursively a method from an object, it calls that method from every child of the object, regardless of the fact that some of them may not have that method.

Example

For instance, let's use this root element :

root (Image)

player (MovingObject)

cloud (MovingObject)

background (Image)

sun (Image)

Now let's suppose we want to call the method move() on the root element, to make every child move : First, we cannot because root is an Image instance, so it doesn't know the move() method. But even if it was the case, the children "background" and "sun" would not know it.

So I decided to put an empty method move() inside my "abstract" Object class, so every object knows it, even if it doesn't do anything.

The issue is that my Object class is now containing empty methods that it doesn't understand nor needs, only to permit the recursive behavior.

Possible solution

Then I heard about all the "inheritance vs composition" fuss and one of the solutions that came to my mind was to stop using inheritance for Object abilities and use composition instead. That means I would create, for example, a "Body" class, an "Image" class and a "Callback" class that would represent different actions, and then plug these into an Object instance to "equip" it and give it more power.

But then I thought that this will barely change something because I will have to call move(), and then the object will check if it has the Body plug-in, and use it. But it still requires the move() method to be present inside the Object class.

Questions

So I'm turning to you guys to gave me advices about my pattern :

Did I understand well how the composite pattern works ?

Is my approach correct ?

Does the use of "plug-in" classes will help me ?

Is the recursive behavior a good idea ?

Is there other patterns that are more fitting to my needs ?

I hope you can give me some hints!

答:
In a clean design object in a given tree should be used with an uniform interface. Your doubts reflects a design smell.

The goal of having object trees in scenes is to be able to apply geometric transformations to a group of objects. So if you have objects that can't move, they don't belong to the tree. It does not make sense.

Here is a possible solution. You can have a render class which can have background objects, and the root of the movable objects. All the movable objects can move. A transformation applied to an object is propagated to its children.

To render the scene, you have to render both the unmovable background objects, and the actual scene by calling a render function on the root.


答:
PHP is not a web language. Its has built in features to do programming in Web application. Developing a web application in PHP is very easy compared to other languages like java,ASP,C#.

If you want to develop a web application which is not so huge and uses database with less size (few GB's) ,then you can develop php web application. There are many web host companies which provide PHP based web hosting charging very less price with all the features.Maintaning a PHP site is less compared to Java/ASP. PHP is light weight web application.

Title: Is PHP actually a web framework?


答:
Ryan is probably forming his opinion based on a historical perspective. Historically, PHP was meant to be a web language. Historically a lot of features in the language were designed for this use case, and in fact PHP used to stand for "Personal Home Page". http://www.nusphere.com/php/php_history.htm

But now, PHP has developed a lot and I would personally argue this isn't really true any more.

Just 2 examples:

Threads were only added to the language recently. For a long time, it just wasn't possible. Threads are something that don't make sense in a web environment (instead you tend to kick of a completely new background process or pass a message through a que to a worker elsewhere). http://uk3.php.net/manual/en/book.pthreads.php

Memory & Resource management. PHP provides a __destruct() method on objects, so you can clear up resources. But to start with, this was only called on script shutdown. Now in a web environment this makes sense because you only want your script to run 0.5secs at max, so script shutdown is never far away. But for a long running background or shell script this is terrible. Later versions of PHP fixed this. http://php.net/manual/en/language.oop5.decon.php

However, you will still generally tend to find PHP used in a web and server context and not a desktop app context - so this is where a lot of the focus is.

Title: Is PHP actually a web framework?


问:
pre aggregating documents mongodb
In our current setup, most of our database calls are updates where we increment a key by 1.

If all one is doing is incrementing certain keys on a document (a lot) in mongodb, and there are several application servers doing so at once, does it ever make sense to somehow aggregate these increments at the application layer and then send the pre-aggregated documents to the main mongodb database every set time interval?

I understand it could be risky because if you somehow lose one of these pre-aggregated documents you can potentially lose more data, but is this technique ever used?  I also understand sharding is the accepted way to scale writes, but I was just curious if this technique is ever used because it seems like it could potentially help scale if done right, I could be completely wrong here though.

答:
Sure, it is a smart way if it is viable for your product. It saves lots of calls to the database and that makes scaling easier. Things which don't take up resources don't have to be scaled.

Most important consideration is trust. How much data can you loose and could you detect the fact that you are losing data.

The pattern you describe looks a bit like putting a queue in front of your database to reduce impact of scaling on the database server. You could take a look at that kind of scenarios.

Title: pre aggregating documents mongodb


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
I personally turned a sizable Stack Overflow rep and a higher (relative to the site) Hacker News reputation into a job, though I do not make $100K/year (which as a number matters more depending on the location of the job). SO and HN gave me a 'body of work' that showed off that I was passionate about my work, able to relate to others, demonstrate some level of technical competence, understand people's problems and clearly communicate solutions. And since the job is as a Developer Evangelist, these are all highly-desirable skills for that position.

I tweeted the other day that the perfect resume would be your Stack Overflow profile and your GitHub profile plus some other social interaction history like Hacker News or Twitter.

P.S. If this sounds like you, we're hiring.

ContentLicense: CC BY-SA 2.5


问:
In my permissions API, how do I handle objects that don't exist?
Elgg is designing a permissions API loosely around the Activity Streams model. The user API could look (roughly) like:

```<code>function elgg_can($capability, $subject = null, $object = null, $target = null) { ... }
</code>```

$capability is a string

$subject is a user object

$object is the object acted upon

$target is the context in which the action would take place

E.g. Can the current user edit the title of an object?

```<code>if (elgg_can('edit title', $currentUser, $someObject)) {
    ...
}
</code>```

I'd like to know a good way to handle asking for permission to create objects. If the object doesn't yet exist, then the permissions system can't know anything about it, so there's a chicken-egg problem with a few obvious solutions:

Allow passing in a string in place of $object (e.g. the TypeName).

Put metadata about the object in the $capability. E.g. elgg_can("create PageObject", $currentUser, null, $group).

Have the API user create the object then pass it into the API to decide if it should be allowed to continue existing.

Am I missing another obvious solution? Are there permissions models similar to this (that one could reasonably call successful) that handle this?

答:
Use the Prototype pattern. In this pattern, you create a new object by cloning a prototype. Obviously that requires the prototype to exist. Not an unreasonable limitation usually, as no user can create random objects out of thin air. elgg_can("create BFG9000") is unlikely to work for you :P

Since the prototype must exist, it can have access rights.


问:
Static linking with modified LGPL code
I'm writing a library which links with modified LGPL library,so two questions:

Do I have to make my code LGPL in case of static linking with LGPL library?

in case of dynamic linking?

答:
First, note that your modifications to the LGPL library are under the LGPL.

With respect to code that uses the LGPL library, the FAQ should answer your question:

(1) If you statically link against an LGPL'd library, you must also provide your application in an object (not necessarily source) format, so that a user has the opportunity to modify the library and relink the application.

(2) If you dynamically link against an LGPL'd library already present on the user's computer, you need not convey the library's source. On the other hand, if you yourself convey the executable LGPL'd library along with your application, whether linked with statically or dynamically, you must also convey the library's sources, in one of the ways for which the LGPL provides.

OwnerDisplayName: Sergey Lega

Title: Static linking with modified LGPL code


问:
How to deploy a GNU GPL software with Java Web Start?
I deploy an interactive software using Java Web Start. This is a quiet useful deployment technology and I don't want to change. Besides I am about to publish my software under a GNU GPL license.

Usually, when a user installs a new software he is asked to read the license terms and accept it. Is there any equivalent process with Java Web Start ? How can I ask my user to accept the license terms before using it ?

答:
Usually, when a user installs a new software he is asked to read the license terms and accept it. Is there any equivalent process with Java Web Start ? How can I ask my user to accept the license terms before using it ?

The GPL is not an EULA the end-user needs to accept (e.g. by ticking a check-box). Some software packages that ship with an installer do this but it is not necessary (and this probably created a wrong impression and made you asking). All you need to ensure (when you distribute your GPL'ed software) is that you pass along the license-text with the software and make clear that you license the software under GPL.

Apart from that, Java Web Start probably is not the best way to distribute FLOSS as of now. I strongly suggest you to file a report/feature request with the Issue-Tracker of that software telling them exactly what you do and what you need. E.g. so that you can pass licensing information and more importantly offer sources along with the object code loaded by Java Web Start.

See as well:

If I embed a GPL 2 Java applet into my web app, do I have to release the web app source?

OwnerDisplayName: Eric David

OwnerDisplayName: hakre


问:
BSD-2 Licence Code modifying
I'm using a BSD-2 Licence code in my project and with author permission, I modify the code. Now, I am using this code in my project. I know, I should mention Author's name and copyright information. Should, I mention What I modify in this code??</p>

答:
Should, I mention What I modify in this code[? ...]

You must mention which code is by that person. So if you modify the code, you can do that by writing that you changed it and what you changed.

So yes, you should mention what you modified otherwise it's not clear which code has been made by whom. And the BSD requires you to make visible - at least for the code under it - which code it relates to.

This is one of the requirements the license BSD has.

OwnerDisplayName: Yasir Adnan

Title: BSD-2 Licence Code modifying


问:
Is it mandatory to obtain a licence for distributing software uses bundled Mono runtime?
My software composed of an EXE and dependent class library dlls, built on Windows using visual studio C# Compiler.
I've been able to run it directly on Mac OS X using mono myApp.exe without rebuilding.

Now, for the deployment, I've successfully made mono bundle using mkbundle with --deps option for all dependent class library assemblies. But I did NOT use --static option. So my application dynamically links to mono and glib.

Wrapped it inside mac APP bundle, then copied the needed libmono-[XYZ].dylib , and all other dependent native libs from Library/Frameworks/Mono.framework into that bundle, changing each dylib id and install name to be the copy insde the bundle rather than original in Mono.framework directory.

Tested the M bundle in a mono free machine. the bundle worked perfectly.

My question is, do I still need to obtain a license from Xamarin to distribute my application to end users under my proprietary license, provided that all mono native runtime libraries are in the App bundle and the user can update/replace them as per LGPL license of mono runtime?

Thanks!

答:
As far as I'm aware, as you state that you're complying with the LGPL terms, then you don't need a licence from Xamarin.

However if you're going to deploy your app to the Mac appStore, LGPL is incompatible with it, so then you need to licence your app as proprietary or MIT/BSD, and to be able to do this you would need a Xamarin license (because AFAIK those licences are not compatible with the LGPL; but IANAL). But maybe we're just talking about some bucks, which is how much the Xamarin.Mac licence costs.

UPDATE: It's very likely that this answer is not valid anymore since the moment Microsoft acquired Xamarin, since one of the conditions for the deal is to make Mono completely MIT, and then there's no need to deal again with crappy licensing.

OwnerDisplayName: Assem

OwnerDisplayName: knocte

ContentLicense: CC BY-SA 4.0


问:
Event based logging. Is it a good idea and is it ok to pass a handle to a "logged" object?
Hi I have fairly complex program that is doing computations in a quite large loop. I want to log some basic statistic about the run to be able to analyze its performance over time and vs loop number. For now I am outputting a set of numbers, about 5 or 6, each loop.

The problem is the number of loops is quite large so the log files are big. Also putting 10^6 of measurement points on a plot is kind of pointless.

I thought of "filtering" the results by for example printing every 1k'th loop but I would lose some points-of-interest. I also cannot log only POIs, because I would lose track of general progress.

I decided to switch to an event based logging. Primarily the events I have in mind are combination of the two aforementioned things: improvement of current solution and some progress over the loops.

The Implementation I have in mind is to write a simple StatLogger that would be responsible for outputting the data to the log stream. The main program would just issue a log() method whenever an event occurs. The events can occur simultaneously and it does not make sense to log the state twice, so the class would be responsible for not outputting the stats twice.

My questions are:

Is this a good or common approach and pattern?

Is it better to pass a handler to the number cruncher object, so the logger can get all the interesting stats like StatLogger::log(const RunEnviroment *this), or is better to make another structure to hold all the interesting stats and make a StatLogger::log(const Stats& stats) method.

If my approach is bad, what are common solutions in similar cases?

答:
I would avoid something general like a StatLogger to be dependent on something special like a RunEnviroment, whatever that looks like. Keeping StatLogger independent will most probably enhance the testability and reusability of that class.

If you need, however, a simple method like

```<code>  StatLogger::log( EnumEventType evenTtype, const std::string &logtext)
</code>```

or something like

```<code>  StatLogger::log(const Stats& stats)
</code>```

(where I guess Statsrepresents one log entry), will mainly depend on what information you are going to log and how complex that information is.

If you want to decouple your main program from a specific logger, you could also introduce an abstract base class as an interface (like IStatLogger), and let your main program only access the logger through that interface. That will allow you to replace the real logger easily by a mock logger for testing purposes.

Body:
I would avoid something general like a StatLogger to be dependent on something special like a RunEnviroment, whatever that looks like. Keeping StatLogger independent will most probably enhance the testability and reusability of that class.

If you need, however, a simple method like

  StatLogger::log( EnumEventType evenTtype, const std::string &logtext)

or something like

  StatLogger::log(const Stats& stats)

(where I guess Statsrepresents one log entry), will mainly depend on what information you are going to log and how complex that information is.

If you want to decouple your main program from a specific logger, you could also introduce an abstract base class as an interface (like IStatLogger), and let your main program only access the logger through that interface. That will allow you to replace the real logger easily by a mock logger for testing purposes.


问:
Conceptually, how does one make a rules/constraints (not graphics/physics) engine for a game
I want to make a simple game similar to the choose-your-own-adventure books. The player is presented with a narrative text and gets to choose his action from a list of possibilities. This, in turn, leads to a new narrative text, ad infinitum. The only catch is that depending on some previous decisions, the list of possibilities might differ.

At first glance, this sounds like a load of if-else statements, thus implying a rule engine would be in place. But, it also sounds like a finite state machine to me.

I am about to write this in Java or maybe Groovy. I'm currently more interested in the conceptual issues, i.e. how should this be done on a broad level (how do people implement chess or card games, anyway?), but some advice on a specific library in also welcome.

Obviously, the "game engine" from the title does not refer to collision detection or other physics/graphics mechanics, but the logic deciding what options does a player have given the situation and his current state.

答:
Conceptually, your game is straightforward.  In psudeocode, it would look something like this:

```<code>while not at end of adventure story
    display text
    get response
</code>```

Now, chaining all of the text together so it flows from one action to the next is the hard part.  You could use a relational database.  You could use a tree.

It's a little hard to be more specific without knowing what computer language you want to use.  Since you mentioned Java, I'd lean more towards a tree structure.

Create a response class that holds one response and a link to a text class.

Create a text class that holds the adventure text, and a List of responses as instances of the response class.

Edited to answer the comment:

You don't calculate anything based on this model.  Using your example, the tree would look something like this, where T is the text and A is an action choice:

```<code>T You stumble on a dead police officer
    A Take the gun
    T You hear footsteps
      A Run away
      A Hide and see who comes
    A Don't touch anything
    T You hear footsteps
      A Run away
</code>```

Yes, there is some duplication of text, but by following the chain, future actions can take into account past decisions.  It's a huge decision tree.

Body:
Conceptually, your game is straightforward.  In psudeocode, it would look something like this:

while not at end of adventure story
    display text
    get response

Now, chaining all of the text together so it flows from one action to the next is the hard part.  You could use a relational database.  You could use a tree.

It's a little hard to be more specific without knowing what computer language you want to use.  Since you mentioned Java, I'd lean more towards a tree structure.

Create a response class that holds one response and a link to a text class.

Create a text class that holds the adventure text, and a List of responses as instances of the response class.

Edited to answer the comment:

You don't calculate anything based on this model.  Using your example, the tree would look something like this, where T is the text and A is an action choice:

T You stumble on a dead police officer
    A Take the gun
    T You hear footsteps
      A Run away
      A Hide and see who comes
    A Don't touch anything
    T You hear footsteps
      A Run away

Yes, there is some duplication of text, but by following the chain, future actions can take into account past decisions.  It's a huge decision tree.


答:
The state machine sounds like a safe approach to model your game. There are lots of libraries for interactive fictions:

http://en.wikipedia.org/wiki/Category:Text_adventure_game_engines

not mentioned in wikipedia, twine is very popular at the moment.

Title: Conceptually, how does one make a rules/constraints (not graphics/physics) engine for a game

Body:
I want to make a simple game similar to the choose-your-own-adventure books. The player is presented with a narrative text and gets to choose his action from a list of possibilities. This, in turn, leads to a new narrative text, ad infinitum. The only catch is that depending on some previous decisions, the list of possibilities might differ.

At first glance, this sounds like a load of if-else statements, thus implying a rule engine would be in place. But, it also sounds like a finite state machine to me.

I am about to write this in Java or maybe Groovy. I'm currently more interested in the conceptual issues, i.e. how should this be done on a broad level (how do people implement chess or card games, anyway?), but some advice on a specific library in also welcome.

Obviously, the "game engine" from the title does not refer to collision detection or other physics/graphics mechanics, but the logic deciding what options does a player have given the situation and his current state.


答:
I think the answer is in the title: you need a rules engine. If you are planning to write your application with Java, you of course can write your own as Gilbert Le Blanc suggested, OR you might want to take a look at Drools, a rules engine.

what options does a player have given the situation and his current
  state

With Drools, or any other rules engine in fact, you can define a parameterized situation which outputs a list of possible actions. You can encode simple rules suc has:

player is at pageX:

choice 1: title: "go left", action: "page45"

choice 2: title: "go right", action: "page56"

IF player has the Staff of Fireballs THEN choice 3: title "launch fireball", action: "page32"

IF player has a Perception Skill of 10 THEN choice 4: title "check writings on the wall", action: "page67"

What is interesting with Drools is that you can encode all your rules in an Excel file, and then at the beginning of the game, make Drools read that file. After that everything is in memory, you only need to bother about your User Interface.

Here are some ressources to help you get started with Drools:

Getting started (java + maven)

Drools Expert


答:
Based on what you've said in comments, this is how I would handle it:

Implement the story as a finite state machine, with a twist.  Each State is a page of the story, and each Transition is a link from one page to another.  But each Transition also has Conditions.  The Conditions could be null, in which case the Transition always shows up as an available option, but if not, then they have to be evaluated when the page displays, and if the evaluation returns False, the Transition does not show up.

There are two basic ways you could implement the Conditions.  The first is to set up a full-blown script engine inside the game, and then the Condition looks like return player.inventory.contains(GUN).  This is initially more complicated to set up, but allows for more advanced scripting.

The second is to hard-code the possible conditions into some sort of object.  It could have a RequiredItem field, and if that field has a value, you check to see if the condition is met.  This system is simpler to set up.  It limits what you can do a lot more than scripting would, but if you don't need the flexibility that a script engine would provide, it's probably a lot easier to use.


问:
When does SOAP make more sense than REST?
From my understanding of REST, the implicit assumption is that all operations are CRUD operations. Sometimes, you are not doing CRUD operations and are doing some more complex logic. In this case, is not SOAP more suitable? Or is it the case that all operations no matter how complex are a series of CRUD operations so they should be split up into a set of smaller CRUD operations to be called one after the other? But, does this not make the operation you are attempting more cumbersome to write? I am trying to understand when it might make more sense to use SOAP instead of REST.</p>

答:
REST may look like CRUD, but in a Resource Oriented Architecture you can handle complex cases, though it may require some thinking.

For example if you want to charge a credit card, that may seem like a verb and thus wouldn't fit with CRUD, but there's no reason you can't have a Purchase resource. Then for a Purchase POST the service can actually charge the credit card behind the scenes.


问:
Building a web app with encrypted MySQL database entries?
I have some experience in building PHP based websites with MySQL access, storing encrypted user details, but all other fields being plain text. My most recent project will require sensitive data to be stored in the database. All of which I'm hosting myself.

I want to set up a system where a user can access his own entries and see the plain text results, but even if he was able to access someone else's they would be encrypted, unintelligible strings.

I have an idea of how to accomplish this, but perhaps it's not optimal or there exist tools to do this already in a more efficient way.

Store username as plain text, and password encrypted with sha1(). Or both encrypted with sha1().

Take the user's password (not the encrypted one, but the one he typed in and use it do define a key specific to that username and password, which will then be stored as a session variable.

Encrypt, or decrypt all of that users data with that key.

In my opinion even if someone gained access to the database and saw a list of plain text usernames and encrypted passwords they couldn't figure out the specific key since it's not stored anywhere. Therefore even if access was gained, they couldn't decipher the content of the sensitive database fields. Of course I'm building in ways to stop them accessing the database anyway, but as a catch-all effort this seems like a good set of steps.

Could the experts please comment on this, and offer some advice? Thanks a lot.

答:
Sha1() is not an encryption function, it is a hashing function. This means that it is one way. You can encode a string using sha1() and it will produce a hash but you can't go from hash to string.

Second, a password should ALWAYS be stored as a hash and never as plain text. But ofcourse the security depends on the strength of the hash, and sha1() isnt the best you can use. It is out dated and shouldn't be use for passwords. Use blowfish or pbkdf2 or similar to store the passwords and use a different random Salt for every user.

Then as ott allready commented. You could use the mysql AES_Encrypt and Decrypt functions.
But then store the encryption string somewhere safe. For instance on the client-side, but then you must use SSL. Or as a session in php, but then it is stored as plain text in a file on the filesystem.

Or you could send the encrypted data encrypted to the client and decrypt it on client side. Then when sending data you encrypt it on client side an store the encrypted file in the database. I'm however not that at home in encryption with javascript.


问:
JIRA Ticket Best Practices: How to write a good JIRA ticket
We "use" JIRA as our ticketing system, but "use" is a real stretch. We have no standards, no templates, no "best practices" documentation for writing a proper JIRA ticket. So I'm spearheading the movement to create such a doc.

It's bad. Real bad. Sometimes, the reporter just copies-n-pastes a stacktrace and submits the ticket without providing any context, backstory, or directions to reproduce.

I was wondering if anybody had some good input for what format/template we could use and enforce so that I never get a lousily-written ticket assigned to me ever again! Thanks in advance!

答:
The basic information needed in any error report:

What exactly did you do?

What exactly did you expect to happen?

What exactly happened instead?

There's a bunch of other information that can be crucial, but depends on the specifics of the system and your environment - things like what user account was used, what domain objects were being worked on, what server the error occurred on, etc.

But also be careful that your effort to increase ticket quality does not end up discouraging people from submitting tickets at all - that's what happens when you cram everything you can think of into a template and force people to fill out all fields even when most of them don't apply to every ticket.


问:
Provide both RESTful interfaces and Java ones?
I am writing a RESTful service in Java, of course it's typical HTTP based interface.

I am wondering should the service provide Java interface which has same semantic to the RESTful interface? I think Java interface will ease other Java code to call the service. (Client Java code doesn't need to use HTTP client to trigger HTTP requests to invoke RESTful) The problem is it's difficult to write same semantic Java interface to a RESTful one, I mean same semantic.

Any advice for the design? Thanks!

答:
The problem is it's difficult to write same semantic Java interface to a RESTful one, I mean same semantic.

What is difficult about it? The standard way of doing REST interfaces in Java consists of writing a Java interface and adding some JAX-RS annotations, that's all.


问:
What is the most inspiring speech from a developer you ever watched?
Please put a direct link to it.

Required:

Still available online (please put a direct link to it)

Must be a speech from a current or former developer

Speaker's popularity doesn't matter

Target audience should be other developers

It is not required that the topic is programming (the task). I'm more looking for subject generally developing here within P.SE rather than SO.

Explain why it was inspiring

(please, native english speaker, edit my question)

答:
50 in 50 by Guy L. Steele, Jr. and Richard "Dick" P. Gabriel. If you have seen either Dick Gabriel or Guy Steele speak, you might think you can imagine what an experience this is going to be. You're wrong.

Describing it as "Live Multimedia Performance Art Poetry Slam" doesn't even come close to doing it justice.

The topic of this "talk" is to celebrate 50 historically important, relevant, interesting, strange, curious and sometimes just plain silly programming languages in 50 words each.


答:
I don't write in Java, but the same concepts apply.

For most projects I work on, I try to do both. Basically my project is set up such that the REST interface just uses the underlying API. Basically the flow is:

```<code>REST -> Front-end API -> Useful code
</code>```

This way I can write additional front-ends for the same backend. I don't generally release the API, but I try to keep it in a state that if it needs to be released, it can be.

For example, in one project, I needed to open up a TCP API using JSON, and provide UDP output packets. Since everything was already going through the standard API, this was dead simple.

In answer to your question, I would only release the REST API (as @MichaelBorgwardt pointed out, this isn't as terrible as it sounds) so you only have to officially support one, but definitely keep them separate so it's easy to release it as a library or add a different front-end.

Title: Provide both RESTful interfaces and Java ones?

Body:
I am writing a RESTful service in Java, of course it's typical HTTP based interface.

I am wondering should the service provide Java interface which has same semantic to the RESTful interface? I think Java interface will ease other Java code to call the service. (Client Java code doesn't need to use HTTP client to trigger HTTP requests to invoke RESTful) The problem is it's difficult to write same semantic Java interface to a RESTful one, I mean same semantic.

Any advice for the design? Thanks!

Body:
I don't write in Java, but the same concepts apply.

For most projects I work on, I try to do both. Basically my project is set up such that the REST interface just uses the underlying API. Basically the flow is:

REST -> Front-end API -> Useful code

This way I can write additional front-ends for the same backend. I don't generally release the API, but I try to keep it in a state that if it needs to be released, it can be.

For example, in one project, I needed to open up a TCP API using JSON, and provide UDP output packets. Since everything was already going through the standard API, this was dead simple.

In answer to your question, I would only release the REST API (as @MichaelBorgwardt pointed out, this isn't as terrible as it sounds) so you only have to officially support one, but definitely keep them separate so it's easy to release it as a library or add a different front-end.


问:
Need a transition from my workflow, or make it better / fix it
This is how I roll with git:

I clone/fork something locally

I create a new branch devel. This is supposed to be a quickfix branch. It is also supposed to be parent to all branches.

I create a topic branch (say make a new theme lex)

I actually create a few more child-topic-branches (say lex.th2) to test/see different things.

But so now, I have to quickfix (in devel) a core functionality (say re-correct database credentials in wp-config).

I then have to switch to lex and merge devel. And then to lex.th2 and merge lex. (So that changes from devel could goto lex and to lex.th2)

Doing all this severely messes up my history-graphs

I'll admit that the "official" workflow was too much for me and I just took the parts that I liked from it... probably badly. So any suggestions how to make it "tidy" while still not complicating or deviating too much?

答:
You should learn the rebase command and (and how to do it interactively). I do it because it lets me keep all the changes in a straight revision graph instead of a tangled mess.

So whenever I have a hotfix I usually commit that directly to the master branch. Whenever I work on a small feature, I commit that to the master branch. Before I push anything I do:

```<code>git pull --rebase
</code>```

This fetches the latest changes on your master branch and rebases your changes with that. I don't really mind the merge conflicts as I like to take them head on while I know what I did.

If I ever need to rearrange my commits in situations where I did a bunch of hotfixes while finishing up a feature I do the interactive rebase command (i.e. do an interactive rebase of the master branch on top of the changes of the origin remote's master branch):

```<code>git rebase -i origin/master
</code>```

It'll prompt a text file with a list of commits like this:

```<code>pick 1111111 Implemented feature #34
pick 2222222 Updated readme to feature #34
pick 3333333 FIX: something works now
# ... a bunch of commands listed below
</code>```

The order of commits is from top to bottom. But I can rearrange these the way I want them:

```<code># moved commit 3333333 first will be applied first in the
pick 3333333 FIX: something works now

# I want feature #34 to be one commit so I do it like this:
pick 1111111 Implemented feature #34
squash 2222222 Updated readme to feature #34
# squash will squash commits 1111111 2222222 to one commit
# and prompt for a new commit message using both as template
</code>```

Save and close and the rebase is performed according to the text file. This way git will keep it all nice and tidy the way you want it... in my case a long nice straight queue of changes to be pushed.

There are times when I create topic branches, but I do the same thing before merging it to master. I.e. rebase the changes on the topic branch with master and then interactively rebase it if I want to tidy it up.

It may seem like a bad thing to rewrite the history like this, but as long as you haven't pushed the changes you can do what you want with it. This is the reason why I rarely have a devel branch; your local master branch is already your devel branch. As long as you haven't pushed anything it is only available at your repository.

Body:
You should learn the rebase command and (and how to do it interactively). I do it because it lets me keep all the changes in a straight revision graph instead of a tangled mess.

So whenever I have a hotfix I usually commit that directly to the master branch. Whenever I work on a small feature, I commit that to the master branch. Before I push anything I do:

git pull --rebase

This fetches the latest changes on your master branch and rebases your changes with that. I don't really mind the merge conflicts as I like to take them head on while I know what I did.

If I ever need to rearrange my commits in situations where I did a bunch of hotfixes while finishing up a feature I do the interactive rebase command (i.e. do an interactive rebase of the master branch on top of the changes of the origin remote's master branch):

git rebase -i origin/master

It'll prompt a text file with a list of commits like this:

pick 1111111 Implemented feature #34
pick 2222222 Updated readme to feature #34
pick 3333333 FIX: something works now
# ... a bunch of commands listed below

The order of commits is from top to bottom. But I can rearrange these the way I want them:

# moved commit 3333333 first will be applied first in the
pick 3333333 FIX: something works now

# I want feature #34 to be one commit so I do it like this:
pick 1111111 Implemented feature #34
squash 2222222 Updated readme to feature #34
# squash will squash commits 1111111 2222222 to one commit
# and prompt for a new commit message using both as template

Save and close and the rebase is performed according to the text file. This way git will keep it all nice and tidy the way you want it... in my case a long nice straight queue of changes to be pushed.

There are times when I create topic branches, but I do the same thing before merging it to master. I.e. rebase the changes on the topic branch with master and then interactively rebase it if I want to tidy it up.

It may seem like a bad thing to rewrite the history like this, but as long as you haven't pushed the changes you can do what you want with it. This is the reason why I rarely have a devel branch; your local master branch is already your devel branch. As long as you haven't pushed anything it is only available at your repository.


问:
does haskell have dependent types?
I know Haskell already has the ability to parametrise a type over another type (similar to template programming in C++), but I'm wondering whether Haskell can also parametrise a type over values – whether it supports dependent types. With dependent types, you can have a type that's parametrised over integers, for example vectors of size n, matrices of size n×m, etc.

If not, why not? And is there any possibility that it will be supported in the future?

答:
To expand a bit on what Ptharien's Flame explained nicely about the current status - and GHC Haskell seems to be moving further in the direction of dependent types (while preserving phase separation) with each version.

So for eg at ICFP 2013 this September, a paper on the next phase of this process should be presented, "Towards dependently typed Haskell:
System FC with kind equality", about collapsing the kind and type levels. As was announced to be the plan some 3 years ago.

And it even mentions the next step: "We are also aware that Adam Gundry’s forthcoming dissertation will include Π-types in a version of System FC and we will want to make this feature available in the source language as well. (Personal communication)"

Title: does haskell have dependent types?


答:
From my understanding of REST, the implicit assumption is that all
  operations are CRUD operations.

Certainly not. You might be referring to an experience of one particular REST web service toolkit, but in general there is no restriction like that. REST is about exchanging documents, representations of state.

In fact, REST is so flexible you can describe your whole complex logic in a document, POST it to a /transactions URL, and use the returned /transactions/<id> to monitor the execution and grab the results. Whether such a shotgun application of REST is useful is another matter, and is dependent on the design of your application.

The SOAP/WSDL combination can be used when a rigid web interface contract is needed, a case that can be justified in some business scenarios. SOAP can be used with REST, but the SOAP/REST combination has not found its supporters, probably because it adds nothing of value to common REST architectures. I personally use SOAP, when I do, only for compatibility/legacy reasons. Or as part of the whole WS-* gamut when I was doing grid computing.

Title: When does SOAP make more sense than REST?

Body: From my understanding of REST, the implicit assumption is that all operations are CRUD operations. Sometimes, you are not doing CRUD operations and are doing some more complex logic. In this case, is not SOAP more suitable? Or is it the case that all operations no matter how complex are a series of CRUD operations so they should be split up into a set of smaller CRUD operations to be called one after the other? But, does this not make the operation you are attempting more cumbersome to write? I am trying to understand when it might make more sense to use SOAP instead of REST.</p>


答:
```<code> > When does SOAP make more sense than REST?
</code>```

With soap you have further interoperability standards WS-* that cover among others XML_Signature and XML_Encryption

In theory SOAP is not limmited to http(s) it can also be used via ftp, email,....
However i have never seen SOAP with non http(s).

If can choose between soap and rest i will always prefer rest.

Body:
 > When does SOAP make more sense than REST?

With soap you have further interoperability standards WS-* that cover among others XML_Signature and XML_Encryption

In theory SOAP is not limmited to http(s) it can also be used via ftp, email,....
However i have never seen SOAP with non http(s).

If can choose between soap and rest i will always prefer rest.


问:
What is the general format of a Software Design Specification?
I'm trying to document a piece of software I wrote in detail. An SAS is too high level and doesn't cover the API. I found several examples of an SDS online, but I don't see a trend in their format.

I'm wondering if there are some general guidelines to writing a Software Design Specification or what the best approach is?

答:
You could do a lot worse than starting with the DOD-STD-2167A Software Design Document Data Item Description.

The US Department of Defense has a lot of experience with software development, a lot more than any one company.  They also have a vested interest in actually getting software that did the job, and that could be maintained down the road.  They went to a lot of trouble to figure out what information needed to be in the various documents that support a software project, using experience from a large number of projects, and more than a few very expensive failures.

The Software Development Plan DID (available here) includes a number of items that must be addressed.  If you look closely, you'll notice that those sections are written in the blood of program managers who failed to address those items.


问:
When are Getters and Setters Justified?
Getters and setters are often criticized as being not proper OO. On the other hand, most OO code I've seen has extensive getters and setters.

When are getters and setters justified? Do you try to avoid using them? Are they overused in general?

If your favorite language has properties (mine does) then such things are also considered getters and setters for this question. They are the same thing from an OO methodology perspective. They just have nicer syntax.

Sources for Getter/Setter Criticism (some taken from comments to give them better visibility):

http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

http://typicalprogrammer.com/?p=23

http://c2.com/cgi/wiki?AccessorsAreEvil

http://www.darronschall.com/weblog/2005/03/no-brain-getter-and-setters.cfm

http://www.adam-bien.com/roller/abien/entry/encapsulation_violation_with_getters_and

http://www.yegor256.com/2014/09/16/getters-and-setters-are-evil.html

To state the criticism simply: Getters and Setters allow you to manipulate the internal state of objects from outside of the object. This violates encapsulation. Only the object itself should care about its internal state.

And an example

Procedural version of code:

```<code>struct Fridge
{
    int cheese;
}

void go_shopping(Fridge fridge)
{
     fridge.cheese += 5;
}
</code>```

Mutator version of code:

```<code>class Fridge
{
     int cheese;

     void set_cheese(int _cheese) { cheese = _cheese; }
     int get_cheese() { return cheese; }
 }

void go_shopping(Fridge fridge)
{
     fridge.set_cheese(fridge.get_cheese() + 5);
}
</code>```

The getters and setters made the code much more complicated without affording proper encapsulation. Because the internal state is accessible to other objects we don't gain a whole lot by adding these getters and setters.

The question has been previously discussed on Stack Overflow:

https://stackoverflow.com/questions/565095/java-are-getters-and-setters-evil

https://stackoverflow.com/questions/996179

答:
Consider a Size class which encapsulates width and height. I can eliminate setters by using the constructor but how does that help me draw a rectangle with Size? Width and height are not internal data to the class; they're shared data that must be available to the consumers of Size.

Objects consist of behaviors and state - or attributes.  If there is no exposed state then only behaviors are public.

Without state, how would you sort a collection of objects?  How would you search for a specific instance of an object?  If you only use constructors, what happens when your object has a long list of attributes?

No method parameter should ever be consumed without validation. Therefore it is laziness to write:

```<code>setMyField(int myField){
    this.myField = myField;
}
</code>```

If you do write it that way then you have at least prepared for using the setter for validation; it's better than a public field - but just barely.  But at least you have a consistent public interface that you can come back and put in validation rules without breaking the code of your customers.

Getters, setters, properties, mutators, call them what you will, but they're necessary.

Title: When are Getters and Setters Justified?

Body:
Consider a Size class which encapsulates width and height. I can eliminate setters by using the constructor but how does that help me draw a rectangle with Size? Width and height are not internal data to the class; they're shared data that must be available to the consumers of Size.

Objects consist of behaviors and state - or attributes.  If there is no exposed state then only behaviors are public.

Without state, how would you sort a collection of objects?  How would you search for a specific instance of an object?  If you only use constructors, what happens when your object has a long list of attributes?

No method parameter should ever be consumed without validation. Therefore it is laziness to write:

setMyField(int myField){
    this.myField = myField;
}

If you do write it that way then you have at least prepared for using the setter for validation; it's better than a public field - but just barely.  But at least you have a consistent public interface that you can come back and put in validation rules without breaking the code of your customers.

Getters, setters, properties, mutators, call them what you will, but they're necessary.


答:
Soap makes more sense than rest when you know that you will stick with .net, and that your consumers will stick with .NET.

I say this, because with SOAP and visual studio integration, making the connection is a breeze.

Step outside of the .NET arena, and connecting to a rest service is a simple matter for any other language.

If you have to use .NET as a provider, and want to provide a rest like interface for your consumers, go with ASP.NET MVC, otherwise, go with WebAPI. (MVC allows for complex behaviors similar to SOAP, just make sure to document your inputs and outputs clearly)


答:
In addition to the great responses already here, another reason might be with who you are communicating with or what language you are developing in.

Some applications only have SOAP or REST interfaces.  In other cases programming languages favor (by design or just practice) one protocol over the other.

For example. Ruby on Rails has excellent support for REST and if you need help a lot of resources.  On the other hand, there are modules for doing SOAP in Rails, but they are not as well supported and you may have a lot more difficulty with that.   Additionally the culture of Rails is to use REST and if you app does not support that you may not get Rails developers to use it or they will complain loudly about it.

On the other hand Microsoft has been a big supporter of SOAP and while I am not a C# or .NET programmer, it is my understanding that the support for SOAP there is very good.  The same is somewhat true for Java, there seems to be better support for SOAP than for for REST there.

All this said, none of the examples above are impossible with one or the other, just that the culture of the programmers that use the language or the language itself tends to favor one or the other.  You should take that into consideration when making your decision.


答:
Look at your requirements.  Do you have a solid requirement for REST?  Is this customer facing or internal?  The answers to these questions may answer it for you.

If external, I would just do REST and be done with it.  If internal, look at your consumers and make a decision.  I would do one or the other though and not both.


答:
You can certainly encrypt each user's data in the table itself, but do so only after recognizing the downside.  If you encrypt the data, your search options will be limited.  You wont, for example, be able to do searches such as name like 'Bob%' or cost > 1000 if the entries are encrypted.  Similarly, you could use multiple databases - one per user (or even one table per user), but you'll start running into problems keeping the schemas in sync should your app ever grow and evolve.

Ultimately, schemes like that may not be as secure as you think they are.  They still wont prevent, for example, the primary way people access other people's data... by simply using their computer or guessing their password.

I believe, quite honestly, your question is being asked out of inexperience with handling this kind of data.

My advice to you is to resist the urge to use security gimmicks.  Design the database and tables as you normally would.  And then put all the effort you would have spent encrypting the data into ensuring your server side application is secure.  Make sure every request properly verifies user authorization to the data being requested.  Make sure you have no possible injection issues.  Use ssl for the connections.  Make sure the proper firewalls are running on the server.

Title: Building a web app with encrypted MySQL database entries?

Body:
I have some experience in building PHP based websites with MySQL access, storing encrypted user details, but all other fields being plain text. My most recent project will require sensitive data to be stored in the database. All of which I'm hosting myself.

I want to set up a system where a user can access his own entries and see the plain text results, but even if he was able to access someone else's they would be encrypted, unintelligible strings.

I have an idea of how to accomplish this, but perhaps it's not optimal or there exist tools to do this already in a more efficient way.

Store username as plain text, and password encrypted with sha1(). Or both encrypted with sha1().

Take the user's password (not the encrypted one, but the one he typed in and use it do define a key specific to that username and password, which will then be stored as a session variable.

Encrypt, or decrypt all of that users data with that key.

In my opinion even if someone gained access to the database and saw a list of plain text usernames and encrypted passwords they couldn't figure out the specific key since it's not stored anywhere. Therefore even if access was gained, they couldn't decipher the content of the sensitive database fields. Of course I'm building in ways to stop them accessing the database anyway, but as a catch-all effort this seems like a good set of steps.

Could the experts please comment on this, and offer some advice? Thanks a lot.


问:
Code formatting SQL queries
Should I break SQL queries in different lines? For example in the project I am working on, we have a query that is taking 1600 columns! 1600 + tab chars. I wrote queries like this:

```<code>   "SELECT bla , bla2 , bla FROM bla " .
     "WHERE bla=333 AND bla=2" .
      "ORDER BY nfdfsd ...";
</code>```

But they demanded me to put them in one line and said that my style is bad formatting. Why it is bad practice?

答:
I often use the format put forth by @glasnt to troubleshoot a complicated query, however usually have queries in a single line.

This might not answer your question, but I'd also strongly suggest breaking down your query into smaller queries. Obviously this depends on the query, but the more clauses and joins you add to your query - the less the SQL engine is able to optimise your query.

Your database vendor should have tools like MySQL's EXPLAIN (or MSSQL's SHOWPLAN_ALL setting) which will show you what the database is doing behind the scenes to optimise your query, every time the database has to create a temporary table or some such, you're adding huge delays when you're talking about multiple concurrent users.

By moving what might seem like trivial logic out of the SQL and into your code, you can provide dramatic performance increases - SQL is great at simple operations.

The obvious benefit to this as it might relate to you, is that your queries are much less complex and easy to read - easy to manage (not >1600 columns), and faster. Definately an all-round win.

Hope this helps :)

Title: Code formatting SQL queries


问:
What is the difference/ advantage of doing double assignment?
Is there any advantage / is it a bad practice in Java to do the below

```<code>x = x = 5
</code>```

I saw it in one of my peers code and I was surprised why he would do double assignment?

Is this something that is same as x = 5 or if x = x= 5 makes a difference?

答:
Is there any advantage/ is it a bad practice to do the below

x= x = 5

You haven't specified the language, but in most C-like languages the value of an assignment is the value being assigned. That is, the value of the expression x = 5 is 5, and the expression you're asking about is essentially the same as doing:

```<code>x = 5;
x = 5;
</code>```

There's no value in the extra assignment, so no reason to do it.

Now, what you do sometimes see is the assignment of two (or more) variables to some value at the same time, like this:

```<code>x = y = 5;
</code>```

In this case, you're assigning 5 to y, and then assigning the value of that expression (again, 5) to x. This ensures that both x and y get the same value.

Another possibility is that one of the assignments was intended to be a comparison, with the result assigned to the variable being compared:

```<code>x = x == 5;
</code>```

This isn't a double assignment, it's assignment of the boolean expression x == 5 to x. That is, if the value of x is 5 before the expression, x will get the value of true (some non-zero integer); if x is not 5, x will be set to false (i.e. 0).

Body:
Is there any advantage/ is it a bad practice to do the below

x= x = 5

You haven't specified the language, but in most C-like languages the value of an assignment is the value being assigned. That is, the value of the expression x = 5 is 5, and the expression you're asking about is essentially the same as doing:

x = 5;
x = 5;

There's no value in the extra assignment, so no reason to do it.

Now, what you do sometimes see is the assignment of two (or more) variables to some value at the same time, like this:

x = y = 5;

In this case, you're assigning 5 to y, and then assigning the value of that expression (again, 5) to x. This ensures that both x and y get the same value.

Another possibility is that one of the assignments was intended to be a comparison, with the result assigned to the variable being compared:

x = x == 5;

This isn't a double assignment, it's assignment of the boolean expression x == 5 to x. That is, if the value of x is 5 before the expression, x will get the value of true (some non-zero integer); if x is not 5, x will be set to false (i.e. 0).


答:
I'll start out with this: I much prefer REST to SOAP. REST has some great advantages, if done right, like distributability, cacheability of responses, clear defined semantics, the ability to be consumed directly in a browser, and so on. However, I like arguing against myself, so here's why you should use SOAP in your next project. A lot of these points come from REST In Practice which everyone should have on his/her desk when starting a REST-y project.

SOAP is everywhere

In the '00s, SOAP replaced a ton of un-interoperable technologies like CORBA, DCOM, RMI, to name a few. If there's a legacy system that you need to integrate with of that vintage, chances are it speaks SOAP, and will happily consume your WSDL. Every language imaginable has a tool that will parse WSDL into domain objects, and loads of developers know how to use it. That can't necessarily be said for REST. You could also go through the pain of interacting with a REST service through an HTTP client library directly (like Apache's HTTP Components). Tool support for REST is getting better: the latest JAX-RS 2.0 has a standard client that's pretty nice to use.

The S in SOAP stands for Simple

Here's the specification for SOAP 1.1. It's short, and outlines quite clearly what a SOAP message looks like. A lot of the spec is dedicated to IMO esoteric cases (never in 10 years have I ever used a partially-transmitted array, e.g.), but the meat of it is: Envelope, Header, Body. I'll concede that the Header and Envelope are redundant when the SOAP message is sent over HTTP, but SOAP can be sent over any medium (as another answer mentions), so it's a necessary evil. You can easily eyeball a SOAP message, and you don't need fancy software to write one either.

WS-* extensions add functionality

There's no in-built transaction support in REST-ful web services. It's possible to make a transactional REST service, but the semantics of your transactional system may be different from the semantics of my transactional system. SOAP has extensions like WS-Transactions that define clear workflows and mechanisms for transactional consistency. Likewise, other extensions like WS-Addressing and WS-Security describe message routing and message authentication/encryption. To do message authentication in REST, you either have to use client-side SSL, or roll your own.

SOAP doesn't require you to map domain operations onto CRUD

REST is not all about CRUD, but to perform non-CRUD operations, you have to map them onto resources. That's not necessarily a bad thing™, but it can cause your designers some headaches. Mapping a verb-operation like "check out a book" to one of the HTTP verbs could be a PATCH request to set an isCheckedOut flag on the book; it could be creating a new /checkout resource, or any number of other things. With a SOAPy web service, and auto-generated code from WSDL, you might simply do service.checkOut(book, patron). The intent is very clear.

SOAP's Fault mechanism encourages richer fault handling

OK, so it's not perfect, and most SOAP web services don't do it right, but that's not SOAP's fault. SOAP has built-in support for exceptions (faults), that are actual objects. They can contain great detail about what went wrong, and how you might fix it. REST's use of HTTP status codes is incredibly handy in this regard, because it encourages the developer to think about whether they should send back a 400, 403, 500, etc. and these codes have standard meanings. However, there's no standard for the message body, and there's no REST mechanism to enforce my-crappy-REST-service from sending back 200 OK responses with error bodies. It's just as easy for a REST service to produce unhelpful responses as it is for a SOAP service.

My experience

Maybe these aren't great reasons to use SOAP over REST in your next project, but I kind of wanted to try to convince myself.

I'm on a project at the moment that exposes a REST API, and consumes a SOAP API, so I'm in the best/worst of both worlds. I hate the SOAP stuff, but that's mostly because the back-end system that I'm working with leaves room for improvement. JAX-RS is a really nice server-side REST API, and it's nearly painless. Because of REST, and because we're being really strict about sticking to the REST constraints, we're making great use of HTTP caching in our infrastructure which will hopefully improve our user experience. We're not, however, doing a full-on HATEOAS service because our application simply doesn't require it. Our service is also primarily CRUD by its nature, so we haven't needed to make hard decisions about how to noun a verb.

In short, I guess SOAP isn't always a bad choice, but there's not a lot going for it unless you have a big SOAP infrastructure already.


答:
When you only plan to interact with the Microsoft stack and large-scale bandwidth consumption is not a issue, SOAP is better.

Otherwise, offering a SOAP-only API to non-Microsofters, is generally considered rude. And I figure there must be some dictatorial state, somewhere, where it earns you a death sentence.


答:
One solution would be to introduce the logging levels. Each level would correspond to importance (or maybe priority) of log information. Such strategy would enable a log information to be grouped and therefore more easily filtered out. These groups could be for example:

TRACE; DEBUG; INFO; WARN; ERROR; FATAL

One such implementation can be found in Linux kernel.

Also, I'm sure you will find more information by googling various logger implementations.

Title: Event based logging. Is it a good idea and is it ok to pass a handle to a "logged" object?

Body:
Hi I have fairly complex program that is doing computations in a quite large loop. I want to log some basic statistic about the run to be able to analyze its performance over time and vs loop number. For now I am outputting a set of numbers, about 5 or 6, each loop.

The problem is the number of loops is quite large so the log files are big. Also putting 10^6 of measurement points on a plot is kind of pointless.

I thought of "filtering" the results by for example printing every 1k'th loop but I would lose some points-of-interest. I also cannot log only POIs, because I would lose track of general progress.

I decided to switch to an event based logging. Primarily the events I have in mind are combination of the two aforementioned things: improvement of current solution and some progress over the loops.

The Implementation I have in mind is to write a simple StatLogger that would be responsible for outputting the data to the log stream. The main program would just issue a log() method whenever an event occurs. The events can occur simultaneously and it does not make sense to log the state twice, so the class would be responsible for not outputting the stats twice.

My questions are:

Is this a good or common approach and pattern?

Is it better to pass a handler to the number cruncher object, so the logger can get all the interesting stats like StatLogger::log(const RunEnviroment *this), or is better to make another structure to hold all the interesting stats and make a StatLogger::log(const Stats& stats) method.

If my approach is bad, what are common solutions in similar cases?


答:
From what I remember reading in a book.

1) SOAP imposes a structure

2) Using Soap is more secure

3) It can handle complex structures e.g. pass objects.

I think REST would be a better solution if you have small applications.
Android has been using Rest and not soap, I guess because it is more lightweight.


问:
Code review if nobody in team has knowledge in some technology?
Sample situation: A team of Java developers starts an iOS project. Only one developer has Objective-C/iOS knowledge, and in the beginning he will work on this project alone.

How we can perform code reviews in this situation? What are processes, approaches, tools that this developer will use?

答:
In this situation, code reviews would be a great way to spread Objective-C/iOS knowledge throughout the team, so that someone else can fix bugs when the iOS developer goes on a honeymoon/quits in a huff/gets hit by a bus/is moved to a higher priority project.

Finding bugs is only half the value of code reviews. Spreading knowledge (about both the technology and the solution implemented) is the other half.

Besides, a decent Java developer may well spot logic errors/etc. in Objective-C code.  Just the act of saying "So why do you do this here?" can easily cause the original developer to spot something himself.


答:
The same process would go for any development. I understand and agree it would be, little more work in a new technology, but once you create few test cases, you will be basically eyeing for same errors(Mathematical/Logical/) as in other technologies.

So,

List all the test cases.

Discuss it with your peers. (Team Work is very important here.)

If possible join some groups in apple developers (for Objective C) and look for more information.

Also look for some more information in SE.

This link will help you get more information on the same.
Code Review

Title: Code review if nobody in team has knowledge in some technology?

Body:
Sample situation: A team of Java developers starts an iOS project. Only one developer has Objective-C/iOS knowledge, and in the beginning he will work on this project alone.

How we can perform code reviews in this situation? What are processes, approaches, tools that this developer will use?


问:
Common and frequently used algorithms of Data structures?
I have been programming for a while, and the edge that I am missing over other programming is algorithms. I know what is linked-list and binary tree, but I dont know many more of them.

I failed on 2 interviews, because of exercises that demanded me to know some data structures algorithms. I am also starting to build a javascript project which has some heavy processing, and I need to know a few good frequently used algorithms?

答:
http://en.wikipedia.org/wiki/List_of_data_structures

Start with

Arrays

Lists

Graphs

Trees

Hash Tables

See also http://sijinjoseph.com/programmer-competency-matrix/, wherein the author describes the following levels, in order of increasing competency:

Able to explain and use Arrays, LinkedLists, Dictionaries etc in practical programming tasks

Knows space and time tradeoffs of the basic data structures, Arrays vs LinkedLists, Able to explain how hashtables can be
  implemented and can handle collisions, Priority queues and ways to
  implement them etc.

Knowledge of advanced data structures like B-trees, binomial and fibonacci heaps, AVL/Red Black trees, Splay Trees, Skip Lists, tries
  etc.


答:
I personally believe it is difficult to learn enough and you should always be looking at what to learn next, either to deepen or broaden your current knowledge base.

However the basic algorithms and data structures required would be:

Minimum

Data Structures

Ones, Two's Complement, and Related Arithmetic

Linked Lists

Hash Tables (maps or dictionaries)

Arrays, Trees, Stacks, Queues, Graphs, Databases

Algorithms

Sorting

Bubble Sort (to know why it's bad)

Insertion Sort

Merge Sort

Quick Sort

Radix style sorts

Counting Sort and Bucket Sort

Heap Sort

Searching

Linear Search

Binary Search

Depth First Search

Breadth First Search

String Manipulation

Iteration

Tree Traversal

Hashing Functions

Concrete implementation of a Hash Table, Tree, List, Stack, Queue, Array, and Set or Collection

Also, the MOST IMPORTANT thing is to know when to USE them.

Robert, above gave the link for List of Data Structures, Here's for Algorithms

Title: Common and frequently used algorithms of Data structures?

Body:
I have been programming for a while, and the edge that I am missing over other programming is algorithms. I know what is linked-list and binary tree, but I dont know many more of them.

I failed on 2 interviews, because of exercises that demanded me to know some data structures algorithms. I am also starting to build a javascript project which has some heavy processing, and I need to know a few good frequently used algorithms?


问:
UML representation of type being passed as a parameter
I want to draw a UML diagram of my program. Class Barney has a method Yabadaba(Doo d) which takes a parameter of type Doo.

How do I represent that class Doo is used in class Barney in my UML diagram?

答:
At the very least, you want a dependency relationship from class Barney to class Doo:

If class Barney maintains an instance of Doo at some point in its life, then the relationship is stronger and becomes an association relationship:

The association relationship can be made even strong by adding a direction.

You can also consider multiplicity, which is the number of elements. This is most useful for if the element is optional or for composition/aggregation relationships. You may also decide that it may not be appropriate to include the Doo class in your model, in which case you can simply indicate the method exists in Barney.


答:
Smells like a homework. Oh well.

I want to draw a UML diagram of my program.

What type of UML diagram? Class, sequence, collaboration? You need to learn to be precise and clear when asking questions.

With that said, I am going to assume you meant to ask for a class diagram (and my answer will be based off that assumption.)

Class Barney has a method Yabadaba(Doo d) which takes a parameter of
  type Doo.

How do I represent that class Doo is used in class Barney in my UML
  diagram?

You represent it by having a class artifact for Barney, in a class diagram, and with a method that takes the type  (Doo) in question

If, the class Barney has a member field of type Doo, in addition to a method that takes an instance of Doo, then, you will have Barney with a Doo field on it.

Either that, or as an aggregation/association of some type. This example would show a composition of Barney with Doo.

What association/method you use to represent this, that depends on what you want to do. And for that, well, the solution is to read the manual. Hope it helps.

=== edit ===

btw, these images were created with the yuml.me online drawing tool.

Title: UML representation of type being passed as a parameter

Body:
I want to draw a UML diagram of my program. Class Barney has a method Yabadaba(Doo d) which takes a parameter of type Doo.

How do I represent that class Doo is used in class Barney in my UML diagram?


问:
Dealing with frustration when things don't work
You ever try to implement something simple but for some strange reason it doesn't work.

So you try a possible solution but then something else doesn't work. You keep trying different workarounds but every time something different isn't working.

Every time you get one step closer you also get one (or more) step farther from solving this problem and its now been 3 hours when this should have taken you 10 minutes. And it still isn't solved.

There is no one in your company who can help, and you are about to put your fist through your screen.

At this point you are so frustrated you can no longer think about the problem clearly. What should you do at this point? Or what can you do to avoid reaching this point?

答:
Fatigue or lack of sleep is never an issue with me.  I'm more frustrated with the lack of organization within the industry as a whole, and overall the low standards we've set for ourselves.  Here's five things that frustrate me:

API's that are complicated in design.  It's like learning a whole new programming language.  In fact some API's are much harder to learn than learning new programming languages.  I admire your intelligence, but you could have saved me time by putting in the documentation that I needed a phd in software engineering or computer science to understand it.

Lack of good documentation.  I can never get over the fact that so many API designers spend a great deal of time in making an API only to release it with minimal documentation.  Thanks, but how do I use this?  What to do in this situation? etc.

Proprietary implementations.  Some proprietary implementation is ok, but if standards exists, for the sake of humankind please follow those standards.  Nothing more frustrating than spending time wondering why something doesn't work only to discover the implementation doesn't follow the normal standards.

Sandboxed environments/Restrictions.  Ok, maybe this helps to keep the bad people out, but in my opinion, restrictions on what a programmer can do only limits creativity and technological progress.  Many of great ideas I've had have been trashed after discovering that I'm not allowed to do something.  The programming industry is really made for churning out everyday applications, not innovative ground-breaking software.  So if you decide on being a programmer you are really choosing to be a modern day grunt, unless you want to become a lonely academic.

Modern discussions.  People today still debate over the ugliness of Lisp parenthesis, or the merit of Pythons cleanliness, or how some languages like Cobol or Fortran are going extinct, etc, etc.  Really people?  This is what we debate about?  Let's talk about parallelism, or better ways to design safer systems, or how logic programming can improve our lives.  Let's stop thinking like coders and start thinking like designers of tomorrow's world.

So I personally don't program that much anymore due to these frustrations.  Until the industry decides it wants to do more than just create the next Facebook, or reinvent the word processor I'm all set.  I'll leave it to you guys.  Honestly no offense meant, it is good money.


问:
Why Aren't Rule Engines Written In Prolog?
From what I've seen of Prolog, it seems as if it would be ideal for crafting a rule engine for an app.  Yet, I don't believe I've ever seen a rule engine written in Prolog.  Is there some inherent limitation in Prolog (e. g. poor garbage collection algorithm) that would prevent it from being used to build a rule engine? </p>

答:
Generally, the point of a rules engine is that it is a part of another application. It is rather rare to see applications written in Prolog, and there isn't a commonly available interface to connect Prolog to applications written in other languages. </p>

<p>One rule-based tool for rule engines, that is written to be added to other applications, is CLIPS. CLIPS was based on OPS5 and uses the Rete algorithm for pruning rules.   </p>

Body:
Generally, the point of a rules engine is that it is a part of another application. It is rather rare to see applications written in Prolog, and there isn't a commonly available interface to connect Prolog to applications written in other languages.

One rule-based tool for rule engines, that is written to be added to other applications, is CLIPS. CLIPS was based on OPS5 and uses the Rete algorithm for pruning rules.


答: Tongue-in-cheek answer: because if the creators of Rules Engines knew about Prolog (or Mercury or PLANNER or …) they wouldn't be writing Rules Engines, they'd be using Prolog.</p>

Title: Why Aren't Rule Engines Written In Prolog?

Body: From what I've seen of Prolog, it seems as if it would be ideal for crafting a rule engine for an app.  Yet, I don't believe I've ever seen a rule engine written in Prolog.  Is there some inherent limitation in Prolog (e. g. poor garbage collection algorithm) that would prevent it from being used to build a rule engine? </p>


答:
If you have the resource to create Java interface, go for it. I'm sure that REST API is your core API, usually because it's a client-server system. It's not hard to write client code calling REST api directly but it also longer and if you use it a lot you'll see repetitions all over the place.

What usually happens is you write a native wrapper for most frequently used interfaces to help people writing client applications. It also gives an extra benefit that when you change your REST interface you can just update the wrapper, e.g. when you change REST api from returning  application/json to application/hal+json your wrapper still returns array of objects.

You can see this everywhere. Twitter, for example, has more than one Java wrappers. Obviously they don't have time to write wrapper for every language out there, but it's also very useful that a lot of people put time in writing one.


问:
When should we stop work and make tool?
As a software engineer, we are always eager to get effective tools to boost our productivity.
And in our daily work, we are often unsatisfactory with the existing tools and would like to have better ways such as better GDB script config, Vim script and some Python script to make boring things automatic.

However, it is actually a trade-off since making tools also needs time and energy. It does not give productivity boosting immediately. Therefore, how do you judge whether it is time to stop work and to make some tools to ease your future pain?

答:
All of the other answers are good, but I'd add one more reason why it's valuable to spend time to build small tools (and customise your .vimrc, .emacs etc.):

Sometimes you get creatively or motivationally "stuck in a rut" and doing something, anything, will "get the juices flowing" again (to mix metaphors). Ideally that would be something that productively pushes the project forward, but if it's a bit tangential and that inspires you, then that's good too.

You might not be staring at a blank screen, but instead simply having trouble seeing the progress you're making on a big task. In that situation ticking off something tangible can stop you feeling like you're not getting anywhere.

A variation on this is when you keep thinking about something that should be on the "back burner" - just taking a moment and doing it will get it off your mind and free you up to put your full energy into the main task again.

Title: When should we stop work and make tool?


问:
Best Practice: Should error messages be handled by the API or by the App?
I am designing an application that interacts with a RESTful API.

When returning error messages like Unable to sign up user

Should the error message be generated by the app? or by the API? I am looking for best practices.

答:
I try to handle as many errors as possible by the API. In environments with multiple clients this helps to keep things consistent and easier to maintain.

When performing the error handling via the API the mere status code is defintely not enough. The approach I take here, is to provide an additional error response body that also provides a human readable message as well as a more detailed message for the developer and a link to further resources that provide some extra explanation. In JSON this could look something like this:

```<code>{
    "status": 404,
    "code": 404-07,
    "message": "Ooops! Seems like the file does not exist.",
    "developerMessage": "File resource for path /uploads/foobar.txt does not exist.",
    "moreInfo": "http://www.mycompany.com/errors/404-07"
}
</code>```

Example taken from stormpath.

The clients then use the human readable message and directly present them to the end user.

To handle i18n we use the HTTP Accept-Language and Content-Language headers. The error messages then get delivered in the desired language.

Body:
I try to handle as many errors as possible by the API. In environments with multiple clients this helps to keep things consistent and easier to maintain.

When performing the error handling via the API the mere status code is defintely not enough. The approach I take here, is to provide an additional error response body that also provides a human readable message as well as a more detailed message for the developer and a link to further resources that provide some extra explanation. In JSON this could look something like this:

{
    "status": 404,
    "code": 404-07,
    "message": "Ooops! Seems like the file does not exist.",
    "developerMessage": "File resource for path /uploads/foobar.txt does not exist.",
    "moreInfo": "http://www.mycompany.com/errors/404-07"
}

Example taken from stormpath.

The clients then use the human readable message and directly present them to the end user.

To handle i18n we use the HTTP Accept-Language and Content-Language headers. The error messages then get delivered in the desired language.