问:
How should web development design patterns differ from software development design patterns?
I want to become a better developer, and so have been dedicating most of my free time outside of work to learning design patterns, and when to implement them (since I feel learning general patterns is a better starting point than learning specific libraries or tools). One issue is, that the majority of highly regarded  design patterns I'm reading about tend to described in terms of their applications in software development.

I was wondering what should be considered when applying them to web development rather than software development?

For reference, these(Reference1 Reference2) is what I've been using as a reference when picking out what design pattern would be best applied for my current project.

答:
First of all I have to say it is best practice to learn design patterns! But be sure you don't   mix up the meaning of design patterns and architectural patterns.

» Design patterns

In computer software a design pattern is a reuseable approach to solving a commonly-occurring software design problem. A design pattern is a template for solving a problem that can be used in many different situations.

Object-oriented design patterns illustrate relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.

» Why I am explaining this to you?

What I am trying to explain is that it is possible and often the case that third generation programming languages have some of them already implemented and this isn't system or programming lanugage specific. And I am guaranteeing you that you already use some of them. The best example is the observer pattern, which you always use if use bind an event to an object or eventhandler.

» Architectural patterns

An architectural pattern is a widely recognised and reused solution to a recurring design problem in the field of software architectures. The concept of an architectural pattern has a broader scope than the concept of design pattern.

The architectural patterns address various issues in software engineering, such as computer hardware performance limitations, high availability and minimization of a business risk. Some architectural patterns have been implemented within software frameworks like ASP.NET MVC.

» Back to topic

I was wondering what should be considered when applying them to web development rather than software development?

So let wikipedia answer this question for us, referring to arechitectural patterns rather than design patterns with the example of the Model View Controller pattern:

Although originally developed for personal computing, Model View Controller has been widely adopted as an architecture for World Wide Web applications in all major programming languages. Several commercial and noncommercial application frameworks have been created that enforce the pattern. These frameworks vary in their interpretations, mainly in the way that the MVC responsibilities are divided between the client and server.
Early web MVC frameworks took a thin client approach that placed almost the entire model, view and controller logic on the server. In this approach, the client sends either hyperlink requests or form input to the controller and then receives a complete and updated web page (or other document) from the view; the model exists entirely on the server. As client technologies have matured, frameworks such as JavaScriptMVC and Backbone have been created that allow the MVC components to execute partly on the client (see also AJAX).

Because I see you are interested in good practices, take a look on architecture patterns (MVC, MVP, MVVM). The only thing you have to keep in mind here, is that you have to adapt your architecture patterns to the HTTP-mechanics.


问:
Ways of developing for small system. What is expedient?
I'm developing a small system for internal automation. I use asp.net webforms and faced with a choice:

develop a system architecture in an object-oriented style (development becomes more difficult and time-consuming)

or

just put controls on forms and write sql queries in control handlers (high speed development, the complexity of testing)

Сurrently I'm using the first method, but starting to have doubts that my choice is correct.
What way is expedient?

答:
This question isn't truly answerable without us knowing virtually everything about your organization, but here's a few pointers anyway.

Do not blindly listen to the advice that every line of code you write has to be perfectly abstracted and layered, ESPECIALLY for new systems. If you take your initial requirements, and create a perfectly layered, abstracted app, what will you do 6 weeks after deployment when the user come back and say "Oh, you know, what we ACTUALLY need isn't 'x', its 'y'." You will grumble and groan, and some programmers will actually try to convince the user that they are wrong about the new requirement. All because you've got a great architecture that you are invested in, and you don't want to rip it all out.

Sometimes the change that comes back after the deployment is minor, or maybe you understood the domain enough to anticipate it during your design phase, but that does not always occur. The change might be bolting on some NEW domain that you've got no experience with. In that case, its virtually impossible that your existing models can just be added to, you'll have to rip out, change, and transform LOTS of code.

My advice is always that for NEW software ("hey, can you give the sales guys a database for contacts?"), you should ALWAYS create a working prototype as quickly/easily as possible. Webforms with SQL datasources right there in the markup are PERFECTLY FINE for this prototype phase. Hell, are you sure you even need a real database? You can do a lot with NoSQL or just plain serialized objects on disk now, and its much faster to develop than coding to fill SQL tables. Use a UI framework like Twitter Bootstrap to cut down your UI time. Look into Entity Framework to speed up your data access, if you truly need to write to a relational database from day 1.

Just make sure you communicate that "done and deployed" means "I still need to come back in 2 months and optimize it". Bake those figures into your estimate, and when those post-deployment changes come back, just add in the extra time needed.

Depending on the level of change that comes back after the first deployment, you'll have to decide at what point you've become confident that you 'really' know the system is stable, and then take the time to break things out into proper layers. Premature optimization is the root of a lot of problems, and premature abstraction and layering falls into "optimization", in my opinion. Good luck with it!

ContentLicense: CC BY-SA 3.0


问:
Freelance charging based on tasks completed
I've just started freelancing and have two projects where I am splitting my week with both companies, one I'm charging hourly and everything is fine, the other one however they have said they will pay me based on a points basis using Pivotal Tracker.

For example, there's a fixed rate per point and they work on an estimate that I will complete two points per day, I was just wondering if this is something that is used regularly or if I should try and get them to switch to hourly?

My concern is that points are only used for features and if a feature has a bug this isn't taken into consideration so any time spent fixing that bug won't be charged. Correct?

答:
they have said they will pay me based on a points basis ... I was just wondering if this is something that is used regularly or if I should try and get them to switch to hourly?

Whether this approach is common or not doesn't really matter, it's what is being offered to you.

Contract work is usually hourly or by per-project.  For example, if framing a house the crew might be paid $X per hour or they might be paid $ABC total for the project.

The second company is offering you a variation of the per-project approach.  Their projects are variable in size and they are using points as a means to assess the size.

Switching to per-project shifts some of the risk of the project onto the contractor (you, in this case).  The company is saying "we'll pay $ABC total for you to do XYZ."  You have to assess the risk of being able to complete XYZ in a period of time that keeps your earnings at a reasonable level.

This can work to your advantage if you're really quick at programming.  If you complete the project in less time than they expect, then you are effectively paid more per hour of work.

This can work against you if the estimates are off or you run into unforeseen problems.  Your effective hourly rate will be lower in this case.

You need to think about how accurate their estimates are, what the quality of their code is, and how well you can work within their code base.

My concern is that points are only used for features and if a feature has a bug this isn't taken into consideration so any time spent fixing that bug won't be charged.

Not necessarily.  This is something to negotiate with the company.  In other trades, per-project contracts often have an "extenuating circumstances" clause that allow for an hourly time-and-materials rate to be charged when unforeseen problems occur.

In this case, the sooner you can identify problems the better.  You want to be able to raise the issue prior to investing too much of your time that may not be compensated.

Whether or not you should accept their per-point offer depends upon how comfortable you are with the risks involved.  It also depends upon whether or not you think you can make the circumstances work in your favor.

You may not have a choice either.  The company may not be willing to negotiate.  And if that's the case then you'll need to look for contract work elsewhere.


问:
Unit testing side effect-heavy code
I'm starting to write C++ code to run a robot, and I don't know how to incorporate unit testing, if indeed I can. I have been provided with a library which allows the creation of "commands" for the robot, which are automatically scheduled and executed. The mechanism to create these commands is to subclass a command base class they provide, and implement virtual void Initialize(), void Execute(), and void End() methods. These functions are run purely for their side effects, which do things to the robot (run motors, extend pistons, etc.). Because of this, I don't really see anywhere to attach unit tests to the code, short of mocking the entire library so that I can check the virtual before and after states of the robot. Is there a way to unit test this that isn't overly burdensome?

Edit

I think I may have been misleading about the functionality of the library. The library provides most of the interface to the robot as well as the command/scheduling system, so it's not as simple as mocking the command base class, I'd have to mock the entire interface to the hardware. I unfortunately just don't have the time to do that.

答:
What I would do in this case would be to introduce my own RobotControl interface with methods corresponding to the ones in the real lib.

After having done this,  I would make a RobotControlImpl class which implements this interface against the real robot lib.

The commands that I consequently would write would not extend the base class,  but instead operate on the interface that you introduced.

This way you can mock RobotControl,  pass the mock to any command and verify that it called the right methods on the interface.

In prod you would pass the real impl of RobotControl to the commands that you implemented.

Im not sure if this is what you had in mind and considered cumbersome?

Edit:
Oh,  and if you expect the commands to sleep in order to wait for completion (nightmare,  but sometimes this is what you have),  I would require the commands to call a sleep method on RobotControl.  This way you can disable sleeps during test and just verify that the command tries to sleep.

Title: Unit testing side effect-heavy code


问:
Location of Solution Components - Centralisation versus Multiple Instances versus Libraries
We're currently in the early stages of building a substantial system, aiming to do much of what several existing systems do, in a flexible, extensible, maintainable way.  It will support multiple complete instances for different customers.  One of the things which keeps coming up across the whole system is: where should [component x] sit?

We could:

(A) completely centralise it into a single separate web service, shared by all instances; configuration would be held centrally so that it could give each instance what it needed, and may include instance-specific plugins

(B) have it as a separate service, but install it multiple times, configured individually for each main instance of the solution; the service might be used by several co-operating components within one instance

(C) create the functionality as a library and incorporate it directly into the other components

For each there are some clear pros and cons:

A is resource-efficient, and easily allows e.g. monitoring of activity across the whole solution.  Making a single service sufficiently configurable/flexible will create additional development challenges.  Upgrades to the code might have an impact across the whole solution both in terms of down-time and testing/deployment planning, whether or not the code change is intended to improve every instance.

B uses more resources, but localises configuration, which may be less complex.  Code changes can be rolled out in a more manageable way, but more effort will be required to do the roll-out in more than one place.

C removes the need for a separate service at all, and offers the potential for maximum flexibility if calling code doesn't have to be restricted to carrying out all functions via the web service API; upgrades to the code would require redeployment of DLLs everywhere they were used, which could be in every component of an instance rather than just once per instance as in B.

I'm specifically thinking about it from a functionality PoV not, worrying about e.g. where the data is actually stored.  I've ignored option D, "copy and paste code all over the place, or reimplement willy nilly".

I'm wondering how it applies to a whole range of components, from specific business functions, to broader things like logging, error-handling, data-access, etc etc.  I realise that the final answer will always depend heavily on each example, but are there considerations I haven't mentioned which could have a big impact?  Are there examples where it's an absolute no-brainer?  Is there some systematic way to help make this decision?  Have I completely missed an entire option?

EDIT (a little more detail just in case it makes a difference):
Historically, because of a lack of forethought, we have catered to the needs of several similar but also substantially different customers by basically forking the entire codebase apart from a handful of trivial libraries.  We are definitely committed to some kind of SOA approach with the rewrite, and certainly a dramatically more shared codebase, but there may still be some benefit or requirement to maintaining some separation to each "instance", by which I mean an entire collection of services providing everything needed for one customer: the customer may require their own logically or physically or even geographically separate install; one customer's instance may consist of modules A and B, another B and C and D and E.  I feel instinctively that there are sort of two ways to be "SOA" here: one to have literally one of everything, and let them all work together in different ways for different customers, or alternatively to have one of each of the needed modules within a customer, but the loosely coupled nature of the services would still allow you to add one more module to an existing customer easily, or move a resource-intensive module to its own hardware for only one customer.

Don't get me wrong, I appreciate all the points made, but I think I'm not quite in a mental place where merely the fact that doing something a certain way, which could definitely offer some benefit in some situations, could also lead to problems if managed poorly, is wholly unacceptable.  So it's best just to not even let the possibility exist even if that leads to more complexity/effort/etc.  Kind of like not allowing booze in the house, because you know that if it's there you might drink it all yourself and run out into the street in your underpants, even though a quiet drink to unwind after work might be nice.  I should probably stop waffling now...

答:
I second Falcon with option A, but with this caveat:

You should handle complexity and difficulty by moving it to the location where you have the tools to deal with it.

If your systems administrators are god-like masters-of-nagios, and your programmers mewling neophytes, then it is probably a good idea to go for solutions that simplify the programming task at the expense of additional systems administration overhead. If the converse is true, of course, then that pulls you in a different design direction.


问:
What are good ways of balancing informative exceptions and clean code?
With our public SDK, we tend to want to give very informative messages about why an exception occurs.  For example:

```<code>if (interfaceInstance == null)
{
     string errMsg = string.Format(
          "Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
          ParameterInfo.Name,
          ParameterInfo.ParameterType,
          typeof(IParameter)
    );

    throw new InvalidOperationException(errMsg);
}
</code>```

However, this tends to clutter up the flow of the code, as it tends to put a lot of focus on error messages rather than what the code is doing.

A colleague started refactoring some of the exception throwing to something like this:

```<code>if (interfaceInstance == null)
    throw EmptyConstructor();

...

private Exception EmptyConstructor()
{
    string errMsg = string.Format(
          "Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
          ParameterInfo.Name,
          ParameterInfo.ParameterType,
          typeof(IParameter)
    );

    return new InvalidOperationException(errMsg);
}
</code>```

Which makes the code logic easier to understand, but adds a lot of extra methods to do error handling.

What are other ways to avoid the "long-exception-messages clutter logic" problem? I'm primarily asking about idiomatic C#/.NET, but how other languages manage it are helpful as well.

[Edit]

It would be nice to have the pros and cons of each approach as well.

答:
Microsoft seems to (via looking at the .NET source) sometimes use resource/Environment strings.  For example, ParseDecimal:

```<code>throw new OverflowException(Environment.GetResourceString("Overflow_Decimal"));
</code>```

Pros:

Centralizing exceptions messages, allowing for re-use

Keeping the exception message (arguably which don't matter to code) away from the logic of the methods

The type of exception being thrown is clear

Messages can be localized

Cons:

If one exception message is changed, they all change

The exception message is not as easily available to the code throwing the exception.

Message is static and contains no information about what values are wrong. If you want to format it, it's more clutter in the code.

Body:
Microsoft seems to (via looking at the .NET source) sometimes use resource/Environment strings.  For example, ParseDecimal:

throw new OverflowException(Environment.GetResourceString("Overflow_Decimal"));

Pros:

Centralizing exceptions messages, allowing for re-use

Keeping the exception message (arguably which don't matter to code) away from the logic of the methods

The type of exception being thrown is clear

Messages can be localized

Cons:

If one exception message is changed, they all change

The exception message is not as easily available to the code throwing the exception.

Message is static and contains no information about what values are wrong. If you want to format it, it's more clutter in the code.


问:
Readability vs benefits of polymorphism
We are dealing with a lot of CRUD operations in our application. Each database table has one or more corresponding SQLContainer instances to perform various types of operations. All of these SQLContainers are stored in one helper class, so that you could perform any type of CRUD operation anywhere from the program (once you have the reference to that helper class).

Now that the scale of the application is growing rapidly, this database helper class has also grown immensely (5+ KLOC).   The growth of this helper class was impacted by the fact, that every SQLContainer has a seperate set of methods for performing the same operations, e.g. if you had to commit employeesContainer, you would call commitEmployeesContainer() and so only reading the method name gives a clear idea of the action. (You could call getEmployeesContainer().commit(), but we also perform some additional operations after commiting, like returing the status code of the commit which is almost the same for each container except for few containers)

Now we are considering to add some polymorphism to this helper class and create general purpose methods, e.g. for  committing records the commitContainer(getEmployeesContainer()) could be used, but such polymorphism will have no typesafety whatsoever and if some table will have few different containers you could accidentally pass a wrong container.

One of the benefits is that you won't have to add new sets of methods when new SQLContainers will be added, and also modifications to the committing algorithm would be easier to adapt.

Question:

Which approach would ease the maintenance whilst keeping the readability or is there an alternative solution for this type of problem?

答:
The common approach to this sort of thing is to create a class (whose name ends with DAO) with static helper methods to perform CRUD methods pertaining to that particular database table.  That static class derives from a common static class with protected methods which assist derived classes.

For instance, org.project.dao.UserDAO.getByUsername("MICHAELJ") would be called so that static class UserDAO can return a UserEntity object based on the username passed.  The UserDAO would then call the super protected method get passing all information required in order to construct a query and return an object array (array, for when you're expecting multiple values).  UserDAO would take the first one, cast it, and return it to the caller (or return null in the case in which none is found).  In this way, you're not violating DRY, and you can perform changes to all reads or just UserDAO simply by modifying the appropriate method.

If you're going to use an instance (say, if you wanted to retain database connection info), that is fine too, but you cannot access it in a global manner like you're doing now.  You need to pass it into the classes which require it, meaning you're going to have to modify all the classes which currently use your helper class.

Then, I usually take things a step further and create a User class which takes as its only constructor argument, a UserEntity instance.  Throughout my program I would use User for getting and setting information and taking care of niceties and data validation.  In this way, if UserEntity ever changed, you would not need to change UserDAO unless it were a key field and you would likely need to do little more than add a getter and setter to User leaving the rest unchanged.  The User class would be the only class to directly interface with UserDAO, and so that too is easy to fix when necessary.

While this Façade pattern is optional, I find it makes my program very flexible and easily maintainable, all while keeping its readability.  I hope that helps!

Title: Readability vs benefits of polymorphism


问:
Why did Java make package access default?
I'm asking this question because I believe they did it for a very good reason and that most people do not use it properly, well from my experience in industry so far anyway.
But if my theory is true then I'm not sure why they included the private access modifier...?

I believe that if default access is properly used it provides enhanced testability whilst maintaining encapsulation. And it also renders the private access modifier redundant.

The default access modifier can be used to provide the same affect by using a unique package for methods that need to be hidden from the rest of the world, and it does this without compromising testability, as packages in a test folder, with the same are able to access all the default methods declared in a source folder.

I believe this is why Java uses package access as 'default'. But I'm not sure why they also included private access, I'm sure there is a valid use case...

答:
I don't think they focused on testing,  simply because testing wasn't very common back then.

What i do think they wanted to achieve was encapsulation on the package level.  A class can as you know have internal methods and fields and only expose some of it through public members.  In the same way a package can have internal classes,  methods and fields,  and only expose some of it.  If you think this way,  a package has an internal implementation in a set of classes,  methods and fields,  along with a public interface in another (possibly partially overlapping)  set of classes,  methods and fields.

The most experienced coders I know think this way.  They take encapsulation and apply it to an abstraction level higher than the class: a package,  or a component if you like. Seems reasonable to me that the designers of Java were already this mature in their designs,  considering how well Java still holds up.


答:
Why not have specialized exception classes?

```<code>if (interfaceInstance == null)
{
    throw new ThisParticularEmptyConstructorException(<maybe a couple parameters>);
}
</code>```

That pushes the formatting and details to the exception itself, and leaves the main class uncluttered.

Title: What are good ways of balancing informative exceptions and clean code?

Body:
With our public SDK, we tend to want to give very informative messages about why an exception occurs.  For example:

```<code>if (interfaceInstance == null)
{
     string errMsg = string.Format(
          "Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
          ParameterInfo.Name,
          ParameterInfo.ParameterType,
          typeof(IParameter)
    );

    throw new InvalidOperationException(errMsg);
}
</code>```

However, this tends to clutter up the flow of the code, as it tends to put a lot of focus on error messages rather than what the code is doing.

A colleague started refactoring some of the exception throwing to something like this:

```<code>if (interfaceInstance == null)
    throw EmptyConstructor();

...

private Exception EmptyConstructor()
{
    string errMsg = string.Format(
          "Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
          ParameterInfo.Name,
          ParameterInfo.ParameterType,
          typeof(IParameter)
    );

    return new InvalidOperationException(errMsg);
}
</code>```

Which makes the code logic easier to understand, but adds a lot of extra methods to do error handling.

What are other ways to avoid the "long-exception-messages clutter logic" problem? I'm primarily asking about idiomatic C#/.NET, but how other languages manage it are helpful as well.

[Edit]

It would be nice to have the pros and cons of each approach as well.

Body:
Why not have specialized exception classes?

if (interfaceInstance == null)
{
    throw new ThisParticularEmptyConstructorException(<maybe a couple parameters>);
}

That pushes the formatting and details to the exception itself, and leaves the main class uncluttered.


答:
[note] I copied this from the question into an answer in case there are comments about it.

Move each exception into a method of the class, taking in any arguments that need the formatting.

```<code>private Exception EmptyConstructor()
{
    string errMsg = string.Format(
          "Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
          ParameterInfo.Name,
          ParameterInfo.ParameterType,
          typeof(IParameter)
    );

    return new InvalidOperationException(errMsg);
}
</code>```

Enclose all of the exception methods into region, and place them at the end of the class.

Pros:

Keeps the message out of the core logic of the method

Allows for adding logic information to each message (you can pass in arguments to the method)

Cons:

Method clutter.  Potentially you could have a lot of methods that just return  exceptions and aren't really related to the business logic.

Cannot reuse messages in other classes

Body:
[note] I copied this from the question into an answer in case there are comments about it.

Move each exception into a method of the class, taking in any arguments that need the formatting.

private Exception EmptyConstructor()
{
    string errMsg = string.Format(
          "Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
          ParameterInfo.Name,
          ParameterInfo.ParameterType,
          typeof(IParameter)
    );

    return new InvalidOperationException(errMsg);
}

Enclose all of the exception methods into region, and place them at the end of the class.

Pros:

Keeps the message out of the core logic of the method

Allows for adding logic information to each message (you can pass in arguments to the method)

Cons:

Method clutter.  Potentially you could have a lot of methods that just return  exceptions and aren't really related to the business logic.

Cannot reuse messages in other classes


问:
How is major software protected?
I am a new software developer and I wish to sell my software. I recently realized that from C++ code we can not stop the user seeing parts of the code that are related to scripts or system commands.

Would you make some comments on how software written in C++/JAVA (distributed via CD-ROMs or available via download) is protected from reverse engineering, scanners for when the code is in memory and direct copy of parts (as system commands).

What a small software company which just starts producing software should do to protect its product from the technological point of view (it should not be able to pay legal fees …)?

答:
If the software is in the client machine, all you can do is delay the inevitable.

Obfuscation and encryption only makes the task of disassembling harder. If you are going that path, you probably want to reach a point were the they will decide "ok, screw this, I'll implement from scratch because it will take less time". Although, in practice it is very hard (if possible) to reach that point... as others has pointed out most mayor companies don't reach that point.

On the other hand, maybe attackers don't want to create an alternative product! (If what they wanted was to compete with you, then all that there is to it is to stay ahead of the competition and stop worrying.)

In practice there has been an actual arms race is in techniques to mod and prevent modding of software. This happens when you decide to add protection from unwanted copies by adding restriction to your software. If you do that, then all of the sudden you will have a bunch of people willing to modify your product to remove those restrictions without paying. This is even more common than a third party replicating your software, you see it from games (for example the "No CD" patches) to illegal activation of Operating Systems (cough Windows cough), antivirus software, and others.

As said, this is an arms race. You say: Anti-A, and they invent A+1, you say Anti-A+Infinity and they say B. It's like a game of whack-a-mole: they will always find a way to keep popping up until you get tired. You can also think of it as a game of Tetris, you are trying to build a perfect wall without holes... but we all know that there is only a way to finish the game of Tetris (At least the original Tetris): you lose.

So, since they want to mod you software the make patches or patchers software that we call "cracks".

Things may start to look scary when you they start to make cracks. It is common for antivirus companies to add those fake versions of programs to their database. As countermeasure the those who distribute those pieces of software will suggest to disable antivirus... result: a bunch of people running software with the antivirus disabled. You will never know when will they take that opportunity to put actual malicious software in there...

And yes, it affects you. It means less sells for you. On one hand because people use the cracks and on the other because the cracks damages your image.

Since all this problem comes from running code in the client, a common approach is to drive the activation of copies through a server. But the client needs to remember if it is activated...

From the attacker standpoint most of the cases look like an "if" branch that says:

```<code>   If (Software is Activated) do this Else do that.
</code>```

All they have to do to unlock your application is to inject some code to negate the verification. So, things like testing the hash of your files to see if they are the originals wont work.

Of course this can be mitigated, take a look to Hash-And-Decrypt, and similar techniques that may actually give some headache to the attacker.

So... ¿Do you want a definitive solution? ¿Something 100% secure?

There are two options:

Never run your software in the client's machine. Run only on your own servers.

Give the software as free and open source. You can add a good legal license, and it will be easy to show that any other software there is a copy. Drive money from something else, like:

2.1. Selling installation and support.

2.2. Additional products.

2.3. Remote "Cloud" execution computing services.

It all point to Hardware and Cloud. it is not rare that all mayor companies are "moving to the cloud".

Title: How is major software protected?

Body:
If the software is in the client machine, all you can do is delay the inevitable.

Obfuscation and encryption only makes the task of disassembling harder. If you are going that path, you probably want to reach a point were the they will decide "ok, screw this, I'll implement from scratch because it will take less time". Although, in practice it is very hard (if possible) to reach that point... as others has pointed out most mayor companies don't reach that point.

On the other hand, maybe attackers don't want to create an alternative product! (If what they wanted was to compete with you, then all that there is to it is to stay ahead of the competition and stop worrying.)

In practice there has been an actual arms race is in techniques to mod and prevent modding of software. This happens when you decide to add protection from unwanted copies by adding restriction to your software. If you do that, then all of the sudden you will have a bunch of people willing to modify your product to remove those restrictions without paying. This is even more common than a third party replicating your software, you see it from games (for example the "No CD" patches) to illegal activation of Operating Systems (cough Windows cough), antivirus software, and others.

As said, this is an arms race. You say: Anti-A, and they invent A+1, you say Anti-A+Infinity and they say B. It's like a game of whack-a-mole: they will always find a way to keep popping up until you get tired. You can also think of it as a game of Tetris, you are trying to build a perfect wall without holes... but we all know that there is only a way to finish the game of Tetris (At least the original Tetris): you lose.

So, since they want to mod you software the make patches or patchers software that we call "cracks".

Things may start to look scary when you they start to make cracks. It is common for antivirus companies to add those fake versions of programs to their database. As countermeasure the those who distribute those pieces of software will suggest to disable antivirus... result: a bunch of people running software with the antivirus disabled. You will never know when will they take that opportunity to put actual malicious software in there...

And yes, it affects you. It means less sells for you. On one hand because people use the cracks and on the other because the cracks damages your image.

Since all this problem comes from running code in the client, a common approach is to drive the activation of copies through a server. But the client needs to remember if it is activated...

From the attacker standpoint most of the cases look like an "if" branch that says:

   If (Software is Activated) do this Else do that.

All they have to do to unlock your application is to inject some code to negate the verification. So, things like testing the hash of your files to see if they are the originals wont work.

Of course this can be mitigated, take a look to Hash-And-Decrypt, and similar techniques that may actually give some headache to the attacker.

So... ¿Do you want a definitive solution? ¿Something 100% secure?

There are two options:

Never run your software in the client's machine. Run only on your own servers.

Give the software as free and open source. You can add a good legal license, and it will be easy to show that any other software there is a copy. Drive money from something else, like:

2.1. Selling installation and support.

2.2. Additional products.

2.3. Remote "Cloud" execution computing services.

It all point to Hardware and Cloud. it is not rare that all mayor companies are "moving to the cloud".


问:
How to best protect from 0 passed to std::string parameters?
I have just realized something disturbing.  Every time I have written a method that accepts a std::string as a paramater, I have opened up myself to undefined behaviour.

For example, this...

```<code>void myMethod(const std::string& s) {
    /* Do something with s. */
}
</code>```

...can be called like this...

```<code>char* s = 0;
myMethod(s);
</code>```

...and there's nothing I can do to prevent it (that I am aware of).

So my question is: How does someone defend themself from this?

The only approach that comes to mind is to always write two versions of any method that accepts an std::string as a parameter, like this:

```<code>void myMethod(const std::string& s) {
    /* Do something. */
}

void myMethod(char* s) {
    if (s == 0) {
        throw std::exception("Null passed.");
    } else {
        myMethod(string(s));
    }
}
</code>```

Is this a common and/or acceptable solution?

EDIT:  Some have pointed out that I should accept const std::string& s instead of std::string s as a parameter.  I agree.  I modified the post.  I don't think that changes the answer though.

答:
How about changing the signature of your method to:

```<code>void myMethod(std::string& s) // maybe throw const in there too.
</code>```

That way the caller has to create a string  before they call it, and the sloppiness you are worried about will cause problems before it gets to your method, making obvious, what others have pointed out, that it is the caller's error not yours.

Body:
How about changing the signature of your method to:

void myMethod(std::string& s) // maybe throw const in there too.

That way the caller has to create a string  before they call it, and the sloppiness you are worried about will cause problems before it gets to your method, making obvious, what others have pointed out, that it is the caller's error not yours.


问:
What HTTP verb is appropriate for an api route that restarts an application the server?
I got asked to do a code review of a very simple one-route web service that when hit would simply restart an application on the system. The developer had coded this up as a POST which strikes me as odd.

Now I realize that this is not really the type of thing that HTTP is all about - you can't even query state - but is there a more appropriate HTTP verb? My intuition is that since this is mostly idempotent and creates no new resources it should be a PUT.

答: I would also use POST for this, though I can see an argument for PUT. Based on RFC 2616 and my own experience, PUT is usually reserved for updating or replacing a resource. While restarting an application could conceptually fall into that category, to me this seems more like a server-side action, which is typically the purview of a POST request.</p>


答:
Whenever you want to protect something you have to think about which threads you want to defend against.

Do you have secrets that you want to protect?

Do you want to protect against software piracy by private
individuals?

Do you want to protect a company from competition.

As far as 1. goes, if you have secrets post the software that deals with them on your own server and do SaaS.

As far as 2. goes, it's probably not worth your while to invest into protection as the protection of all software gets broken.

As far as 3. goes the danger isn't straight reverse engineering through code but someone reprogramming your idea. If you want to protect against that you would need to go the expensive road and buy patents.

Title: How is major software protected?

Body:
I am a new software developer and I wish to sell my software. I recently realized that from C++ code we can not stop the user seeing parts of the code that are related to scripts or system commands.

Would you make some comments on how software written in C++/JAVA (distributed via CD-ROMs or available via download) is protected from reverse engineering, scanners for when the code is in memory and direct copy of parts (as system commands).

What a small software company which just starts producing software should do to protect its product from the technological point of view (it should not be able to pay legal fees …)?


问:
Cpu-heavy web server
When reading about web servers, frameworks, etc most of the time I notice that the goal is to have a technology that has the next features:

Able to handle as many connections as possible.

Fit an I/O model (connections to DBs and other web services).

Those features fit the actual web model but I am interested in knowing which technologies will fit a heavy-cpu user case.

For example, Node.js is a technology that really shines when you have to write an application that uses a lot of I/O. On the other hand, due to the Node.js nature of being evented, It is not suitable for being use in CPU-heavy user cases.(video encoding, machine learning, graphics)

I also have take a look at Haskell web frameworks like Snap and Warp and at the benchmarks they really are fast.

Are they Haskell web frameworks suitable for CPU-heavy problem? Which other languages/technologies are candidates?

答: Don't forget the massive improvements (two orders of magnitude) you can get from GPU acceleration for some of the tasks you mentioned.If this is not possible, order of magnitude improvements are still possible with parallelism and vectorization.</p>

Title: Cpu-heavy web server


答:
I think is possible to make the code testable in a minimally invasive way. By that I mean by that is that you can write the commands exactly as intended by the robot library authors. This can be advantageous if you want to exchange code with others that are not using your intermediate layer.

It does require a separate "unit test build" of your code.

What you do is that in one central header file, you check a compile time define if this is the unit test build, and if so, redefines the name of the base class, and maybe some other classes in the robot library to names of classes of your test implementation. You should define the same virtual functions as in the robot lib, as well as provide stubs for methods you invoke on the robot.

Then you have commands that you can throw in your own testing framework that invokes the same methods the robot library would do.

This will involve some amount of stubbing and mocking, but that is inevitable in any unit test design.

Changing the base class name could be done with a #define or probably preferred, a typedef.

Title: Unit testing side effect-heavy code

Body:
I'm starting to write C++ code to run a robot, and I don't know how to incorporate unit testing, if indeed I can. I have been provided with a library which allows the creation of "commands" for the robot, which are automatically scheduled and executed. The mechanism to create these commands is to subclass a command base class they provide, and implement virtual void Initialize(), void Execute(), and void End() methods. These functions are run purely for their side effects, which do things to the robot (run motors, extend pistons, etc.). Because of this, I don't really see anywhere to attach unit tests to the code, short of mocking the entire library so that I can check the virtual before and after states of the robot. Is there a way to unit test this that isn't overly burdensome?

Edit

I think I may have been misleading about the functionality of the library. The library provides most of the interface to the robot as well as the command/scheduling system, so it's not as simple as mocking the command base class, I'd have to mock the entire interface to the hardware. I unfortunately just don't have the time to do that.


答:
C) Will only work if your services implement some kind of logic or calculation and do not rely on some database or other persistent data. Even if the service is implementing a calculation you will run into a problem when a change is needed.

For example, if your service performs some pricing calculation, then you will have a problem when the pricing calculation formula needs to changed (because of a change in the business) because you won't be able to update all of the applications that use that library all at the same time.

Title: Location of Solution Components - Centralisation versus Multiple Instances versus Libraries

Body:
We're currently in the early stages of building a substantial system, aiming to do much of what several existing systems do, in a flexible, extensible, maintainable way.  It will support multiple complete instances for different customers.  One of the things which keeps coming up across the whole system is: where should [component x] sit?

We could:

(A) completely centralise it into a single separate web service, shared by all instances; configuration would be held centrally so that it could give each instance what it needed, and may include instance-specific plugins

(B) have it as a separate service, but install it multiple times, configured individually for each main instance of the solution; the service might be used by several co-operating components within one instance

(C) create the functionality as a library and incorporate it directly into the other components

For each there are some clear pros and cons:

A is resource-efficient, and easily allows e.g. monitoring of activity across the whole solution.  Making a single service sufficiently configurable/flexible will create additional development challenges.  Upgrades to the code might have an impact across the whole solution both in terms of down-time and testing/deployment planning, whether or not the code change is intended to improve every instance.

B uses more resources, but localises configuration, which may be less complex.  Code changes can be rolled out in a more manageable way, but more effort will be required to do the roll-out in more than one place.

C removes the need for a separate service at all, and offers the potential for maximum flexibility if calling code doesn't have to be restricted to carrying out all functions via the web service API; upgrades to the code would require redeployment of DLLs everywhere they were used, which could be in every component of an instance rather than just once per instance as in B.

I'm specifically thinking about it from a functionality PoV not, worrying about e.g. where the data is actually stored.  I've ignored option D, "copy and paste code all over the place, or reimplement willy nilly".

I'm wondering how it applies to a whole range of components, from specific business functions, to broader things like logging, error-handling, data-access, etc etc.  I realise that the final answer will always depend heavily on each example, but are there considerations I haven't mentioned which could have a big impact?  Are there examples where it's an absolute no-brainer?  Is there some systematic way to help make this decision?  Have I completely missed an entire option?

EDIT (a little more detail just in case it makes a difference):
Historically, because of a lack of forethought, we have catered to the needs of several similar but also substantially different customers by basically forking the entire codebase apart from a handful of trivial libraries.  We are definitely committed to some kind of SOA approach with the rewrite, and certainly a dramatically more shared codebase, but there may still be some benefit or requirement to maintaining some separation to each "instance", by which I mean an entire collection of services providing everything needed for one customer: the customer may require their own logically or physically or even geographically separate install; one customer's instance may consist of modules A and B, another B and C and D and E.  I feel instinctively that there are sort of two ways to be "SOA" here: one to have literally one of everything, and let them all work together in different ways for different customers, or alternatively to have one of each of the needed modules within a customer, but the loosely coupled nature of the services would still allow you to add one more module to an existing customer easily, or move a resource-intensive module to its own hardware for only one customer.

Don't get me wrong, I appreciate all the points made, but I think I'm not quite in a mental place where merely the fact that doing something a certain way, which could definitely offer some benefit in some situations, could also lead to problems if managed poorly, is wholly unacceptable.  So it's best just to not even let the possibility exist even if that leads to more complexity/effort/etc.  Kind of like not allowing booze in the house, because you know that if it's there you might drink it all yourself and run out into the street in your underpants, even though a quiet drink to unwind after work might be nice.  I should probably stop waffling now...


问:
How do I verify if 3rd party payment succeeded?
I'm working on a payment processing website that will function like PayPal does on many e-commerce websites. The idea is for the customer to fill their shopping cart and click checkout, then be directed to the payment page on a secure site. After the payment page processes the payment, it directs the customer back to the original website. So far, I think I'm ok up to the point of receiving the payment, but what mechanism do sites like PayPal use to allow the original website to verify whether the payment was successfully received?

My Current Process:

Customer click's checkout

Store cart items as a pending order in database

Post merchant ID, payment amount, the return URL, etc. to secure payment page. This uses SSL and I have also posted a hash of the other posted values to ensure they are not tampered with in transit.

Customer enters card info and clicks "Pay"

Secure site redirects to the specified return URL with a query string of relevant transaction information including a flag indicating success or failure.

For the last step, the original site needs to be sure the request came from the payment site so that a user can't just navigate to that URL, providing the query string themselves, to complete an order. I currently have the same hashing mechanism in place to make sure the query string variables are not tampered with. It is very crude. I append the variables into one long string and then append a shared secret key to the end, hash that whole string, send it. The receiving end does the same thing and compares the hashes.

答:
Sign the query string along with a timestamp and a transactions ID that you randomly generate on your backend with the SSL certificate of your website.

You should also think about the case where a payment gets through but the users computer loses it's internet connection directly afterwards.

For that case you should send the server of the website directly a signed message about the fact that the transaction went through.

I would also provide a way for the website to query for information about a transaction.


答:
If you can get away with a little more general errors you could write a public static generic cast function for you, that infers the source type:

```<code>public static I CastOrThrow<I,T>(T t, string source)
{
    if (t is I)
        return (I)t;

    string errMsg = string.Format(
          "Failed to complete {0}, because type: {1} could not be cast to type {2}.",
          source,
          typeof(T),
          typeof(I)
        );

    throw new InvalidOperationException(errMsg);
}

/// and then:

var interfaceInstance = SdkHelper.CastTo<IParameter>(passedObject, "Action constructor");
</code>```

There are variations possible (think SdkHelper.RequireNotNull()), that only check requirements on the inputs, and throw if they fail, but in this example combining the cast with producing the result is selfdocumenting and compact.

If you are on .net 4.5, there are ways to have the compiler insert the name of the current method/file as a method parameter (see CallerMemberAttibute). But for an SDK, you probably can't require your customers to switch to 4.5.

Body:
If you can get away with a little more general errors you could write a public static generic cast function for you, that infers the source type:

public static I CastOrThrow<I,T>(T t, string source)
{
    if (t is I)
        return (I)t;

    string errMsg = string.Format(
          "Failed to complete {0}, because type: {1} could not be cast to type {2}.",
          source,
          typeof(T),
          typeof(I)
        );

    throw new InvalidOperationException(errMsg);
}

/// and then:

var interfaceInstance = SdkHelper.CastTo<IParameter>(passedObject, "Action constructor");

There are variations possible (think SdkHelper.RequireNotNull()), that only check requirements on the inputs, and throw if they fail, but in this example combining the cast with producing the result is selfdocumenting and compact.

If you are on .net 4.5, there are ways to have the compiler insert the name of the current method/file as a method parameter (see CallerMemberAttibute). But for an SDK, you probably can't require your customers to switch to 4.5.


问:
How to do simple natural language categorization
How would you go about parsing a sentence like
"Bought two kilos of steak from Acme supermarket" into a data structure like the following JSON representation:

```<code>{
  item: {name: "steak", tags: "meat,beef" },
  quantity: { value: 2, unit: "kg"},
  source: "ACME Supermarket"
}
</code>```

?

I'm looking for a high-level conceptual overview of where to start e.g. some papers or introductory material that don't require PhD level knowledge. For context, this is part of the preliminary investigation for a personal expense tracker I'm planning to build.

To break it down a little further, I'm interested in basic named entity recognition, and categorization strategies. I don't have a CS education, so you may want to keep that in mind when answering :) Thanks in advance. Not interested in 3rd party web services, since this is a learning exercise, and is intended to work offline.

答:
Your best bet is to define your own syntax which appears to be natural (or close-to-natural) language, even though it's actually much more rigid.

For example, a SQL select statement:  SELECT <something> AS <foo> FROM
 WHERE <something else> IS  (note that I replaced = with IS to make the point, but that the capitalization is not important).

In your case, it would be BOUGHT <quantity> OF <thing> FROM <location>.  Then you just have to parse <quantity>, <thing>, and <location> to match them up against known items.

```<code>switch (quantityString)
{
   case "a":
   case "1":
   case "a single":
   case "one":
     return 1;
   case "a pair":
   case "2":
   case "two":
     return 2;
   ....
 }
</code>```

You could even make the first word variable input too, but only from a select set of known verbs (the way SQL has SELECT, DELETE, INSERT, etc).  You could handle derivatives of them ("purchased" vs "bought") similarly.

This would be an example of defining a href="http://en.wikipedia.org/wiki/Domain-specific_language" rel="nofollow">Domain-Specific Language like @Robert-Harvey mentioned.

Body:
Your best bet is to define your own syntax which appears to be natural (or close-to-natural) language, even though it's actually much more rigid.

For example, a SQL select statement:  SELECT <something> AS <foo> FROM <table> WHERE <something else> IS <a value> (note that I replaced = with IS to make the point, but that the capitalization is not important).

In your case, it would be BOUGHT <quantity> OF <thing> FROM <location>.  Then you just have to parse <quantity>, <thing>, and <location> to match them up against known items.

switch (quantityString)
{
   case "a":
   case "1":
   case "a single":
   case "one":
     return 1;
   case "a pair":
   case "2":
   case "two":
     return 2;
   ....
 }

You could even make the first word variable input too, but only from a select set of known verbs (the way SQL has SELECT, DELETE, INSERT, etc).  You could handle derivatives of them ("purchased" vs "bought") similarly.

This would be an example of defining a Domain-Specific Language like @Robert-Harvey mentioned.


问:
Dictionary vs List
So I ran into a Dictionary<int, int> today at work. This just seemed weird to me because I would have probably just used a List<int> instead. Is there a difference and would there be a use case where one structure would be preferred over the other?

答:
These are great answers that seem to cover the bases.

Another consideration I will offer is that Dictionaries (in C#) are more complex from a coding perspective.  Having both lists and dictionaries in the same codebase makes your code harder to maintain in that both methods have subtle differences in how to do basic operations such as searching and marshalling object data.  My perspective is that unless you need a dictionary for some justifiable reason, use a list.

Title: Dictionary vs List


问:
Should test fixtures be added to code repositories?
I'm unit testing some code that processes data from an external API. That external API serves up a large pile of JSON data.

The right thing to do here, of course, is to use fixtures in the unit tests, so that I don't do a real API call every time the test runs.

Those fixtures can be quite large though - many thousands of lines, even. I'm not sure whether I should put them into git. It seems like a bad idea, since they seem like static files. On the other hand, writing the unit tests really requires specific fixtures, so I do want them shared with anybody working on the project (and shared with our build machinery).

Should large fixtures be committed into a repo?

答:
I would commit them to some sort of a repository, yes.

It doesn't need to be the main repository, but you want to preserve the effort you put into creating the fixtures in the first place.  Likewise, if someone else works on the project with you, then being able to check out those fixtures will save them a lot of time.


答:
Absolutely yes. Anyone should be able to run your unit tests by getting them out of the repository. Any build automation is going to require this (it should, anyway), as will future developers.

An alternative might be to put a pre-test block in the unit test that checks for the files and downloads them if they're not there. That way it's easy for you to update them if the API changes, and anyone getting the code will just be able to run it without digging round your machine to find the missing files.

As Guy pointed out, compressing files is unlikely to help - between the SSD/disk cache and git compressing things you almost certainly won't see a speed increase. With large chunks of static data it might make sense to put a gz wrapper around them (or similar) to speed up loading if that's easy to do in your language. That pushes the size down, and with fairly static data new commits (and consequent diffs) are going to be very rare.

Title: Should test fixtures be added to code repositories?

Body:
I'm unit testing some code that processes data from an external API. That external API serves up a large pile of JSON data.

The right thing to do here, of course, is to use fixtures in the unit tests, so that I don't do a real API call every time the test runs.

Those fixtures can be quite large though - many thousands of lines, even. I'm not sure whether I should put them into git. It seems like a bad idea, since they seem like static files. On the other hand, writing the unit tests really requires specific fixtures, so I do want them shared with anybody working on the project (and shared with our build machinery).

Should large fixtures be committed into a repo?


问:
Design pattern for configuring objects

Context

In a Cocoa application I am developing, I need to load a data model that is defined in plist files. So, I have something like:

```<code>root (Array)
---- item (Dictionary)
-------- name : "objects" (string)
-------- prefab : "object" (string)
-------- children : (Array)
...
---- item (Dictionary)
-------- name : "actions" (string)
-------- prefab : "action" (string)
-------- children : (Array)
</code>```

So, the previous data model is loaded in the code to become an object representation using the language's primitives (arrays, dictionaries, strings, ... etc). No custom classes here. When I load that model, I know that an item in the table view can have children if the "prefab" key is set. When "add child" is pressed, I go to the prefabs (some other plist) and fetch that prefab's structure. e.g:

```<code>root (Array)
---- item (Dictionary)
-------- name : "object" (string)
-------- parameters : (dictionary)
------------ key "object_id" : value ""
------------ key "x_position" : value 0
...
</code>```

As you can see, from the prefab in the first model, I can go to the second plist and fetch a structure that is defined in a plist. All loaded using a plist library, without any subclass creation whatsoever. There is a single prefab factory class that contains the prefab structures, and instantiates and initializes the object from the prefab with the configuration data.

Problem

I hope you see the grave danger in this design. The model contains both user generated data as well as configuration data!! EEEEK!!! ... Sheesh, that's so bad...

The problem haunted me when I started exporting the model after the user of the app interacted with the model though the UI. The exported model would contain the configuration data (such as the prefab key), which makes the exported data rigid and un-upgradable. If I were to change the prefab key in later version of the app, to something else, and you load an old model, that model will load the old configurations with it, in our case, referencing the old prefab.

Question

I need help find a proper design pattern that clicks with this data driven design that I have, by providing the configuration data from a separate file, and somehow, linking it with the data model.

答:
Funnily, while writing the question part of the post, I wrote this:

I can't create subclass for each data entity (object, action, ... etc), but I can create a generic subclass that fits all the objects.

That's it!

Even though the prefab factory can configure the instantiated object on-the-fly, it can only do that when the object is created for the very first time. When it is loaded from the model, it is more or less de-serialized, which meant I had to traverse the model tree... Which was so ugly, I couldn't write such code. Writing a custom subclass to rule them all, I can have it configure itself even when loaded from a serialized data model.

(Final remarks: I didn't want all that typing in the question to go to waste, besides stackexchange promotes Q&A style spreading knowledge kinda thing, so, yay)

Title: Design pattern for configuring objects


答:
Unless you're talking about terabytes of data (which I don't believe you are here) then I would put it in source control. You really want everything in your source control solution so that anybody can check it out and run the full test suite without requiring any other dependencies to be hooked up.

I would also not zip the data as many source control systems already provide compression behind the scenes and if not the source control system then the media that you store it on may provide compression. The reason that I would generally not compress data is that there are times when you'll want to change the data and you'll want to be able to do a diff between different versions. Say the data returned by the API changes. That's a good reason to change the fixture's data.


问:
Under what scenarios will an App's localStorage get cleared?
I am developing an Hybrid android app using HTML5 which will work completely offline.

Today morning when I opened the app, I saw that all the data stored in localStorage was cleared.

Under what scenarios can the localStorage get cleared?

Given these scenarios, is it a good idea to use localStorage?

答:
This will look different/appear differently on browsers but with the example of Google Chrome, these are the different ways in which localStorage for your application can be erased:

1. Individually deleting localStorage keys in the Developer Tools menu:

2. Clearing browser history/cache/cookies/etc.

3. Un-installing the browser itself.


问:
Should a DR & CR entry both be created or a single-entry accounting is fine
A new project has an amount. It is always related to a client.

One client can have many projects. And he may pay in steps for a particular project.

In order to keep track of client payments, I've created a table namely client_ledger which contains information about date, time, amount, mode of payment & related project.

But then in one of the software screens, I have to reports pertaining to a client's debit & credit.

So there are 2 things that can be done :

Either I can get the total amount of all projects of that client and his total payments & then can show how much balance is left to be paid.

Or if I'd created an entry in the client_ledger table for DR, then as soon as a project is created, an entry is made in the table for DR and subsequent payments received
will be CRed into the data-base. In this case, if a project's amount is modified/edited later, then either the original DR entry has to be modified, or a new CR entry followed by the new project amount's DR entry should be made.

Which of these processes should be followed ?

答:
Talk to the accountant.

Whether or not you create a DR when a project gets created depends on when the revenue is recognised. It's simple for sale of goods, when the title has been transferred, revenue is recognised. But with a project, it's not clear that the money received is revenue because no work has been done yet at the start of the project.

If the client pay before project start, then it becomes Prepayment (liability). If they pay after project finished, it becomes Receivable (asset).

It's not wrong to recognised project value as revenue at the start of project, but
if this is used as base for taxation, then they'll also be prepaying the tax, which is bad for cash flow. If the total project value is not recognised as revenue, then you might need to record the unrecognised part somewhere else, not in ledgers because they only record transaction that's already happened.

My guess is, if you go with number 2, then it should be recorded as Prepayment, which is a Liability not Income. Then as project milestones hit, the prepayment becomes revenue.


问:
Rich Domain Models -- how, exactly, does behavior fit in?
In the debate of Rich vs. Anemic domain models, the internet is full of philosophical advice but short on authoritative examples.  The objective of this question is to find definitive guidelines and concrete examples of proper Domain-Driven Design models. (Ideally in C#.)

For a real-world example, this implementation of DDD seems to be wrong:

The WorkItem domain models below are nothing but property bags, used by Entity Framework for a code-first database.  Per Fowler, it is anemic.

The WorkItemService layer is apparently a common misperception of Domain Services; it contains all of the behavior / business logic for the WorkItem. Per Yemelyanov and others, it is procedural. (pg. 6)

So if the below is wrong, how can I make it right?

The behavior, i.e. AddStatusUpdate or Checkout, should belong in the WorkItem class correct?

What dependencies should the WorkItem model have?

```<code>public class WorkItemService : IWorkItemService {
    private IUnitOfWorkFactory _unitOfWorkFactory;

    //using Unity for dependency injection
    public WorkItemService(IUnitOfWorkFactory unitOfWorkFactory) {
        _unitOfWorkFactory = unitOfWorkFactory;
    }

    public void AddStatusUpdate(int workItemId, int statusId) {

        using (var unitOfWork = _unitOfWorkFactory.GetUnitOfWork<IWorkItemUnitOfWork>()) {
            var workItemRepo = unitOfWork.WorkItemRepository;
            var workItemStatusRepo = unitOfWork.WorkItemStatusRepository;

            var workItem = workItemRepo.Read(wi => wi.Id == workItemId).FirstOrDefault();
            if (workItem == null)
                throw new ArgumentException(string.Format(@"The provided WorkItem Id '{0}' is not recognized", workItemId), "workItemId");

            var status = workItemStatusRepo.Read(s => s.Id == statusId).FirstOrDefault();
            if (status == null)
                throw new ArgumentException(string.Format(@"The provided Status Id '{0}' is not recognized", statusId), "statusId");

            workItem.StatusHistory.Add(status);

            workItemRepo.Update(workItem);
            unitOfWork.Save();
        }
    }
}
</code>```

(This example was simplified to be more readable. The code is definitely still clunky, because it's a confused attempt, but the domain behavior was: update status by adding the new status to the archive history. Ultimately I agree with the other answers, this could just be handled by CRUD.)

Update

@AlexeyZimarev gave the best answer, a perfect video on the subject in C# by Jimmy Bogard, but it was apparently moved into a comment below because it didn't give enough information beyond the link.  I have a rough draft of my notes summarizing the video in my answer below.  Please feel free to comment on the answer with any corrections. The video is an hour long but very worth watching.

Update - 2 Years Later

I think it's a sign of DDD's nascent maturity that even after studying it for 2 years, I still can't promise that I know the "right way" of doing it. Ubiquitous language, aggregate roots, and its approach to behavior-driven design are DDD's valuable contributions to the industry. Persistence ignorance and event sourcing causes confusion, and I think philosophy like that holds it back from wider adoption. But if I had to do this code over again, with what I've learned, I think it would look something like this:

I still welcome any answers to this (very active) post that provide any best-practices code for a valid domain model.

答:
The most helpful answer was given by Alexey Zimarev and got at least 7 upvotes before a moderator moved it into a comment below my original question....

His answer:

I would recommend you to watch Jimmy Bogard's NDC 2012 session "Crafting Wicked Domain Models" on Vimeo. He explains what rich domain should be and how to implement them in real life by having behaviour in your entities. Examples are very practical and all in C#.

http://vimeo.com/43598193

I took some notes to summarize the video for both my team's benefit and to provide a little more immediate detail in this post. (The video is an hour long, but really worth every minute if you have time. Jimmy Bogard deserves a lot of credit for his explanation.)

"For most applications... we don't know that they're going to be complex when we start. They just become that way."

Complexity grows naturally as code and requirements are added. Applications can start out very simple, as CRUD, but behavior/rules can become baked in.

"The nice thing is we don't have to start out complex. We can start with the anemic domain model, that's just property bags, and with just standard refactoring techniques we can move towards a true domain model."

Domain models = business objects. Domain behavior = business rules.

Behavior is often hidden in an application -- it can be in PageLoad, Button1_Click, or often in helper classes like 'FooManager' or 'FooService'.

Business rules that are separate from domain objects "require us to remember" those rules.

In my personal example above, one business rule is WorkItem.StatusHistory.Add(). We're not just changing the status, we're archiving it for auditing.

Domain behaviors "eliminate bugs in an application a lot more easily than just writing a bunch of tests." Tests require you to know to write those tests. The domain behaviors offer you the right paths to test.

Domain services are "helper classes to coordinate activities between different domain model entities."

Domain services != domain behavior. Entities have behavior, domain services are just intermediaries between the entities.

Domain objects shouldn't have possession of the infrastructure they need (i.e. IOfferCalculatorService). The infrastructure service should be passed in to the domain model that uses it.

Domain models should offer to tell you what they can do, and they should only be able to do those things.

The properties of domain models should be guarded with private setters, so that only the model can set its own properties, through its own behaviors. Otherwise it's "promiscuous."

Anemic domain model objects, that are just property bags for an ORM, are only "a thin veneer -- a strongly typed version over the database."

"However easy it is to get a database row into an object, that's what we've got."

'Most persistant object models are just that. What differentiates an anemic domain model versus an application that doesn't really have behavior, is if an object has business rules, but those rules are not found in a domain model.'

"For a lot of applications, there's no real need to build any kind of real business application logic layer, it's just something that can talk to the database and perhaps some easy way to represent the data that's in there."

So in other words, if all you're doing is CRUD with no special business objects or behavior rules, you don't need DDD.

Please feel free to comment with any other points that you feel should be included, or if you think any of these notes are off the mark. Tried to quote directly or paraphrase as much as possible.

OwnerDisplayName: RJB


问:
Javascript Use of Window Object through alternate means
Disregard your usual paradigms for a mere moment here....

I've seen a few sites who have used the following logic:

```<code>a=[];
b=a["sort"];
c=(b)();
c["alert"](1); // intended output: Alert displaying "1"...
</code>```

supposedly to access (I'm guessing here) the primitive of the sort function to gain access to the window object, and then using that to access "alert"...

I've tried executing this ages ago, and it worked a charm... But some twelve months or so later, I tried to run it again... and it's failed to execute, and given the following error:

```<code>TypeError: can't convert undefined to object
</code>```

My question is, why wouldn't this logic work? It seems quite sound... Or is it?

And yes, I know that I could just do alert(1) and be done with it, but I'm trying to get an understanding of alternate ways of coding... I work in IT security and I know certain people have ways of using XSS to find alternative ways to perform generic functions to compromise systems...

答:
I'm not sure why it wouldn't work in a given environment but it works in a Chrome console.

Let's walk through it:

```<code>a=[];
</code>```

a is defined without a var declaration so it implicitly becomes a member of the global object which in browsers is the window object. This wouldn't work in strict mode (look for 'use strict'; - could be double-quoted), which would throw an error rather than do the implicit global thing, which yes, is one of few JS design warts that I actually agree was a bad idea with no redeeming qualities whatsoever. But strict mode will defeat the whole thing right here.

```<code>b=a["sort"];
//b=a.sort; // to make it even more clear. bracket notation is for obfuscation purposes
</code>```

We assign the sort method of arrays to the var b. Called as b(), it's no longer called as a property/method of the array.

```<code>c=(b)();
//c=b(); // no need for (b) since b is already an evaluated function you can call
</code>```

So, b is the array method sort but now it's just a loose function. What does that generic func do? It takes the function it's passed as an arg to sort whatever is represented by the 'this' keyword, sorts it in place and then returns 'this'. Since b is now just a loose function, 'this' should be the window object. In order to break at this point, passing undefined would have to break the sort method (which might make the most sense given your error) or the sort method would have to be behaving as if it had been permanently applied to Array.prototype as if the function bind method had been used (see "bind" on MDN).

Note: I use words like "seem" because sort returns as a [native code] method in Chrome which means it could be doing all kinds of things in the details as long as it technically fulfills ECMA spec which all browser vendors have been taking seriously since IE5.

```<code>c["alert"](1); // intended output: Alert displaying "1"...
//c.alert(1); //works too.
//alert(1); //and yes the same exact thing but easier to obfuscate from the top one
</code>```

At this point, nothing magic is happening. We have the global object. We fire alert from it as a property of the global object.

Body:
I'm not sure why it wouldn't work in a given environment but it works in a Chrome console.

Let's walk through it:

a=[];

a is defined without a var declaration so it implicitly becomes a member of the global object which in browsers is the window object. This wouldn't work in strict mode (look for 'use strict'; - could be double-quoted), which would throw an error rather than do the implicit global thing, which yes, is one of few JS design warts that I actually agree was a bad idea with no redeeming qualities whatsoever. But strict mode will defeat the whole thing right here.

b=a["sort"];
//b=a.sort; // to make it even more clear. bracket notation is for obfuscation purposes

We assign the sort method of arrays to the var b. Called as b(), it's no longer called as a property/method of the array.

c=(b)();
//c=b(); // no need for (b) since b is already an evaluated function you can call

So, b is the array method sort but now it's just a loose function. What does that generic func do? It takes the function it's passed as an arg to sort whatever is represented by the 'this' keyword, sorts it in place and then returns 'this'. Since b is now just a loose function, 'this' should be the window object. In order to break at this point, passing undefined would have to break the sort method (which might make the most sense given your error) or the sort method would have to be behaving as if it had been permanently applied to Array.prototype as if the function bind method had been used (see "bind" on MDN).

Note: I use words like "seem" because sort returns as a [native code] method in Chrome which means it could be doing all kinds of things in the details as long as it technically fulfills ECMA spec which all browser vendors have been taking seriously since IE5.

c["alert"](1); // intended output: Alert displaying "1"...
//c.alert(1); //works too.
//alert(1); //and yes the same exact thing but easier to obfuscate from the top one

At this point, nothing magic is happening. We have the global object. We fire alert from it as a property of the global object.


问:
How to Deal With The "Automation is Easy" Mindset?
The title says it all. Some employees in our company believe that automated tests are "easy" and that it "should take a day" to write suites of COM and UI tests. What can be done to counter this? </p>

<p>Note: I'm not asking about how to promote automation. That isn't the problem. Automated testing and processes are being promoted and requested all the time here. The issue is that some individuals don't understand that automation is not "easy" nor is it "fast". </p>

答:
There are two sides to this question.

On your side, you appear to think that you are doing a good job, and that the "Automation is easy" group don't know what they are talking about.

On their side, from what you say, they see automated tests taking (in their view) a long time to produce.

From this distance, with the little we have to go on, we don't know who is "right", or if anyone is "right".

How to deal with the automation is easy mindset

Talk to them. Honestly ask for their ideas on how it can be done better. Get them engaged and involved. It's the only way to find out if they really have anything positive to offer. Maybe they do have some worthwhile contributions to make, and you can achieve a win / win.

If they don't have any real idea how programming and automated testing works, or realistic ideas for how to improve productivity, then having engaged them positively you can show how it's done and where the time goes. Be humble and positive, thanking them for their input / ideas. Think about what they've said: maybe their suggestions will trigger a different way of thinking for you. If so, give them that feedback. By being humble and positive you can make it a win / win also.

Before you talk to them think about how you build, run and manage your tests. What framework(s) are you using? Are there others that could be better? Do you have "standard" boilerplate that you adapt? Could building the tests be more automated? What's holding you back?


问:
Is there a license that forbids distribution and gives a Github repo owner full rights?
I created a Chrome browser extension, and I want to post the code on Github so developers can contribute to the project.

My goal is to keep this as one single project though, and I fear that a lot of nearly identical extensions would start showing up in the Chrome Web Store if I released the code without restriction.

I would like to find a license that:

Allows modification

Forbids any distribution other than pull requests back to the original repo

Gives me (the repo owner) the right to distribute code from pull requests on the Chrome Web Store

I would think this would be a common problem, but I can't seem to find a license that fits. Do any licenses like this exist?

答:
It's a common problem and lawyers frequently solve that problem by being paid money to do so.

In the open source world there an interest into standardizing licenses. If you don't go that road, you usually have to write your own license or pay someone to do so.


答:
The code below gives a compile failure for an explicit pass of 0, and a run-time failure for a char* with value 0.

Note that I do not imply that one should normally do this, but no doubt there may be cases where protection from the caller error is justified.

```<code>struct Test
{
    template<class T> void myMethod(T s);
};

template<> inline void Test::myMethod(const std::string& s)
{
    std::cout << "Cool " << std::endl;
}

template<> inline void Test::myMethod(const char* s)
{
    if (s != 0)
        myMethod(std::string(s));
    else
    {
        throw "Bad bad bad";
    }
}

template<class T> inline void Test::myMethod(T  s)
{
    myMethod(std::string(s));
    const bool ok = !std::is_same<T,int>::value;
    static_assert(ok, "oops");
}

int main()
{
    Test t;
    std::string s ("a");
    t.myMethod("b");
    const char* c = "c";
    t.myMethod(c);
    const char* d = 0;
    t.myMethod(d); // run time exception
    t.myMethod(0); // Compile failure
}
</code>```

Title: How to best protect from 0 passed to std::string parameters?

Body:
I have just realized something disturbing.  Every time I have written a method that accepts a std::string as a paramater, I have opened up myself to undefined behaviour.

For example, this...

```<code>void myMethod(const std::string& s) {
    /* Do something with s. */
}
</code>```

...can be called like this...

```<code>char* s = 0;
myMethod(s);
</code>```

...and there's nothing I can do to prevent it (that I am aware of).

So my question is: How does someone defend themself from this?

The only approach that comes to mind is to always write two versions of any method that accepts an std::string as a parameter, like this:

```<code>void myMethod(const std::string& s) {
    /* Do something. */
}

void myMethod(char* s) {
    if (s == 0) {
        throw std::exception("Null passed.");
    } else {
        myMethod(string(s));
    }
}
</code>```

Is this a common and/or acceptable solution?

EDIT:  Some have pointed out that I should accept const std::string& s instead of std::string s as a parameter.  I agree.  I modified the post.  I don't think that changes the answer though.

Body:
The code below gives a compile failure for an explicit pass of 0, and a run-time failure for a char* with value 0.

Note that I do not imply that one should normally do this, but no doubt there may be cases where protection from the caller error is justified.

struct Test
{
    template<class T> void myMethod(T s);
};

template<> inline void Test::myMethod(const std::string& s)
{
    std::cout << "Cool " << std::endl;
}

template<> inline void Test::myMethod(const char* s)
{
    if (s != 0)
        myMethod(std::string(s));
    else
    {
        throw "Bad bad bad";
    }
}

template<class T> inline void Test::myMethod(T  s)
{
    myMethod(std::string(s));
    const bool ok = !std::is_same<T,int>::value;
    static_assert(ok, "oops");
}

int main()
{
    Test t;
    std::string s ("a");
    t.myMethod("b");
    const char* c = "c";
    t.myMethod(c);
    const char* d = 0;
    t.myMethod(d); // run time exception
    t.myMethod(0); // Compile failure
}


答:
So the thing I referenced in my comment above is the Javascript Garden, with its note about EcmaScript 5 in the sidebar.  From there I was able to actually do some searches and find better references.

Basically, this has a couple different ways that it can be set.  The one that matters here, I believe, is down under "Common Pitfalls":

```<code>Foo.method = function() {
    function test() {
        // this is set to the global object
    }
    test();
}
</code>```

and "Assigning Methods":

```<code>var test = someObject.methodTest;
test();
</code>```

Due to the first case, test now acts like a plain function call; therefore, this inside it will no longer refer to someObject.

So when you're retrieving sort off of the Array object, you're turning it into an "aliased" function, where this no longer points at the array.  When strict mode is turned off/in older browsers/EcmaScript versions, that was window, due to being in the global scope.  However when in strict mode, that is now undefined:

Why is “this” in an anonymous function undefined when using strict? explains what led to this.

Getting a reference to the global object in an unknown environment in strict mode includes an actual quote that explains the change.

That said, Chrome's Developer Console is doing something weird, which makes it incorrect to test there.  Your example code "succeeds" by returning window, however, if I copy that to a file and run it (with or without "use strict";), I get this in Chrome:

```<code>Uncaught TypeError: Array.prototype.sort called on null or undefined
</code>```

And this comes from Firefox, either from a page or from within Firebug:

```<code>TypeError: can't convert undefined to object
</code>```

Both of which are expected if this is now undefined, because it's essentially the same as doing:

```<code>Array.prototype.sort.call(undefined);
</code>```

whereas because of the context under "Common Pitfalls" mentioned above, it used to do:

```<code>Array.prototype.sort.call(window);
</code>```

Title: Javascript Use of Window Object through alternate means

Body:
Disregard your usual paradigms for a mere moment here....

I've seen a few sites who have used the following logic:

```<code>a=[];
b=a["sort"];
c=(b)();
c["alert"](1); // intended output: Alert displaying "1"...
</code>```

supposedly to access (I'm guessing here) the primitive of the sort function to gain access to the window object, and then using that to access "alert"...

I've tried executing this ages ago, and it worked a charm... But some twelve months or so later, I tried to run it again... and it's failed to execute, and given the following error:

```<code>TypeError: can't convert undefined to object
</code>```

My question is, why wouldn't this logic work? It seems quite sound... Or is it?

And yes, I know that I could just do alert(1) and be done with it, but I'm trying to get an understanding of alternate ways of coding... I work in IT security and I know certain people have ways of using XSS to find alternative ways to perform generic functions to compromise systems...

Body:
So the thing I referenced in my comment above is the Javascript Garden, with its note about EcmaScript 5 in the sidebar.  From there I was able to actually do some searches and find better references.

Basically, this has a couple different ways that it can be set.  The one that matters here, I believe, is down under "Common Pitfalls":

Foo.method = function() {
    function test() {
        // this is set to the global object
    }
    test();
}

and "Assigning Methods":

var test = someObject.methodTest;
test();

Due to the first case, test now acts like a plain function call; therefore, this inside it will no longer refer to someObject.

So when you're retrieving sort off of the Array object, you're turning it into an "aliased" function, where this no longer points at the array.  When strict mode is turned off/in older browsers/EcmaScript versions, that was window, due to being in the global scope.  However when in strict mode, that is now undefined:

Why is “this” in an anonymous function undefined when using strict? explains what led to this.

Getting a reference to the global object in an unknown environment in strict mode includes an actual quote that explains the change.

That said, Chrome's Developer Console is doing something weird, which makes it incorrect to test there.  Your example code "succeeds" by returning window, however, if I copy that to a file and run it (with or without "use strict";), I get this in Chrome:

Uncaught TypeError: Array.prototype.sort called on null or undefined

And this comes from Firefox, either from a page or from within Firebug:

TypeError: can't convert undefined to object

Both of which are expected if this is now undefined, because it's essentially the same as doing:

Array.prototype.sort.call(undefined);

whereas because of the context under "Common Pitfalls" mentioned above, it used to do:

Array.prototype.sort.call(window);


问:
Which is better: for valid buffer length?
This is a basic question. But, I think understanding this would be helpful to play with buffers in 'C'. Thanks.

Scenario

Just a sample snippet

```<code>char *test_buff = (char *) malloc(512); //allocate 512 bytes in heap memory.
bzero(test_buff, 512); //Reset buffer instead of Junk/garbage.
/* random code here to fill-in the buffer called "test_buff"...*/
...
/* Send data to another host/system [this doesn't matter though]
 * using buffer "test_buff".
 */
 sendto(sock_descriptor, test_buff /*buffer to send data*/, sizeof(*test_buff) ,...,...);  // option-1
/* OR */
 sendto(sock_descriptor, test_buff /*buffer to send data*/, 512 /* actual malloced size*/ ,...,...); // option-2
</code>```

Question

Which one of the two is better [between option-1/option-2] way of using buffer? I hope option-1 makes sense, as it has length/size of valid data bytes of send buffer or "test_buff" in this case.

Thanks for your time and input.

答: In as much as sizeof(*test_buff) will be sizeof(char), i.e. 1, I'd go with the 512.


问:
Coding styles when using several disparate libraries
I am working on some C++ code that uses several libraries, including some C libraries, that all have different coding styles.  It will be open sourced once it reaches a usable stage.  Which would cause the least confusion for a short-term contributor who checks out the code to fix one bug or add one feature?

Have one consistent coding style throughout the entire application, even if it occasionally doesn't match the typical coding style of the libraries used.

When a library is heavily used in a certain module, conform to the typical coding style of that library (i.e. the coding style used in the library's own code and documentation) in that module.

My thought is that the latter will make it easier for experts in that particular library to make one-off contributions, and make it easier to incorporate tutorial/example code during development.  However, it also makes the coding style inconsistent throughout the application.  What are the pros and cons of each approach?

答:
Sounds like there are multiple layers to consider, at least:

The existing libraries and any modifications to them.

New unit test code for those libraries.

The abstraction layer.

The API presented by the abstraction layer.

Example and test code using the abstraction layer.

I'm going to assume that it does not make sense to just refactor all code to a common style up front - if it did you would not have asked the question.

Taking in each in turn:

For the existing code-base, then you'll likely want to stick to that style.

New unit test code for existing code stands in a grey area, particularly depending on how much it is integrated with older code. But most likely, I'd try to make it in the 'preferred style'.

The new code in the abstraction layer. By ensuring that this is really a separate code layer, there should be no difficulty in using a preferred style even it the code is doing a lot of interfacing with a legacy style or styles. Most code needs to interface with other styles, and I have never found this a problem.

Obviously the API itself needs the most thought and meet maximum usability needs.

Any example or test code should likewise be able to be be written in the preferred style. Depending on the completeness of the abstraction (i.e. whether is completely hides the lower layers), this may be easy or difficult. Of course, making sure that future client code is readable will be one of your key objectives.

Some things I have found personally is that with a large legacy code base:

Setting a preferred style and enforcing for code changes it does not
magically result in the all old code migrating to the new style.

Most engineers tend to like to code in (more or less) the existing style in a given
library. Requiring otherwise results in a lot of enforcement.

Requiring a preferred style in a legacy library tends to result in a
lot of inconsistency in style in that library. So for standards which
are purely around presentation, as opposed to code robustness it's
hard too see a lot of benefit in requiring them.

As a final issue (slightly off topic but I think relevant), the truth is that some engineers struggle to stick to any style standard other than they one they know best. I strongly recommend engaging the team in style decisions and making sure there is buy in. Having done so you are in a much better position to actually apply a standard in mixed code.


答:
No, there aren't any popular licenses that do that.  But this is largely because a license is NOT required to allow simple use; licenses are a stipulated contract, wherein you give someone permission to use your property (the software) in exchange for some combination of renumeration and behavior.

The GPL, for instance, is a trade of "you must license anything you derive form this with the GPL and provide source code" for "here's my code."  Conversely, Microsoft's usual license is "you paid $X, and gain one copy, and you can't sue us or do X with our software."

(It's likely that unless your extension is extremely clever and novel, someone will just make a copy of it themselves, though, without even looking at your code.)

Title: Is there a license that forbids distribution and gives a Github repo owner full rights?

Body:
I created a Chrome browser extension, and I want to post the code on Github so developers can contribute to the project.

My goal is to keep this as one single project though, and I fear that a lot of nearly identical extensions would start showing up in the Chrome Web Store if I released the code without restriction.

I would like to find a license that:

Allows modification

Forbids any distribution other than pull requests back to the original repo

Gives me (the repo owner) the right to distribute code from pull requests on the Chrome Web Store

I would think this would be a common problem, but I can't seem to find a license that fits. Do any licenses like this exist?