问:
Advantages of Strategy Pattern
Why is it beneficial to use the strategy pattern if you can just write your code in if/then cases?

For example: I have a TaxPayer class, and one of its methods calculates the taxes using different algorithms. So why can't it have if/then cases and figure out what algorithm to use in that method, instead of using the strategy pattern? Also, why can't you just implement a separate method for each algorithm in the TaxPayer class?

Also, what does it mean for the algorithm to change at runtime?

答:
For one thing, big clumps of if/else blocks are not easily testable. Each new "branch" adds another execution path and thus increases the cyclomatic complexity. If you want to test your code thoroughly, you'd have to cover all execution paths, and each condition would require you to write at least one more test (assuming you write small, focused tests). On the other hand, classes which implement strategies typically expose just 1 public method, which is easy to test.

So, with nested if/else you'll end up with many tests for a single part of your code, while with Strategy you'll have few tests for each of multiple simpler strategies. With the latter, it's easy to have better coverage, because it's harder to miss execution paths.

As for extensibility, imagine you are writing a framework, where users are supposed to be able to inject their own behavior. For example, you want to create some kind of tax calculations framework, and want to support tax systems of different countries. Instead of implementing all of them, you just want to give framework users a chance to provide an implementation of how to calculate some particular taxes.

Here is the strategy pattern:

You define an interface, e.g. TaxCalculation, and your framework accepts instances of this type to calculate taxes

A user of the framework creates a class which implements this interface and passes it to your framework, thus providing a way to perform some part of calculations

You cannot do the same with if/else, because that would require changing the code of the framework, in which case it would not be a framework anymore. Since frameworks are often distributed in compiled form, this may be the only option.

Still, even if you just write some regular code, Strategy is beneficial because it makes your intents clearer. It says "this logic is pluggable and conditional", i.e. there can be multiple implementations which may vary depending on user actions, configuration, or even platform.

Using the Strategy pattern may improve readability because, while a class which implements some particular strategy typically should have a descriptive name, e.g. USAIncomeTaxCalculator, if/else blocks are "nameless", in best cases just commented, and comments can lie. Also, fr my personal taste, just having more that 3 if/else blocks in a row is not readable, and it gets pretty bad with nested blocks.

The Open/Closed principle is also very relevant, because, as I described in the example above, Strategy allows you to extend a logic in some parts of your code ("open for extension") without rewriting those parts ("closed for modification").

Title: Advantages of Strategy Pattern


答:
[...] if you can just write your code in if/then cases?

That is exactly the greatest benefit of strategic pattern. Not having conditions.

You want your classes/methods/functions to be as simple and short as possible. Short code is very easy to test and very easy to read.

Conditions (if/elseif/else) make your classes/methods/functions long, because usually the code where one decision evaluates to true is different from the part where the decision evaluates to false.

Another great benefit of the strategy pattern is, it is reusable throughout your whole project.

When using the strategy design pattern, you are very likely to have some kind of an IoC container, from which you are obtaining the desired implementation of an interface, perhaps by an getById(int id) method, where the id could be an enumerator member.

This means, the creation of the implementation is only in one place of your code.

If you wish to add more implementations, you add the new implementation to the getById method and this change is reflected everywhere in the code where you call it.

With if/elseif/else this is impossible to do. By adding a new implementation, you have to add a new elseif block and do it everywhere where the implementations were used, or you might end up with a code which is invalid, because you forgot to add the implementation to its structure.

Also, what does it mean for the algorithm to change at runtime?

In my example, the id could be a variable which is populated based on a user input. If the user clicks on a button A, then id = 2, if he clicks on a button B, then id = 8.

Because of the different id value, a different implementation of an interface is obtained from the IoC container and the code performs different operations.

ContentLicense: CC BY-SA 3.0

Title: Advantages of Strategy Pattern

Body:
Why is it beneficial to use the strategy pattern if you can just write your code in if/then cases?

For example: I have a TaxPayer class, and one of its methods calculates the taxes using different algorithms. So why can't it have if/then cases and figure out what algorithm to use in that method, instead of using the strategy pattern? Also, why can't you just implement a separate method for each algorithm in the TaxPayer class?

Also, what does it mean for the algorithm to change at runtime?


问:
Ambiguity in method overloading
The book I am reading on Java states something confusing and unacceptable.

Learning About Ambiguity

When you overload methods, you risk creating an ambiguous situation - one which the compiler cannot determine which method to use. For example, consider the following overloaded computeBalance() method declarations:

```<code>public static void computeBalance(double deposit)
public static void computeBalance(double withdrawal)
</code>```

If you declare a double variable named myDeposit and make a method call such as computeBalance(myDeposit);, you will have created an ambiguous situation. Both methods are exact matches for your call.  You might argue that a call using a variable named myDeposit "seems" like it should go to the version of the method with the parameter named deposit, but Java makes no assumptions based on variable names.  Each version of computeBalance() could accept a double, and Java does not presume which one you intend to use.

This violates the rules for overloading a method. How can a method be overloaded with the same parameter list? Isn't it impossible or am I not getting something? I have tried and compiled such a code, it returns the following error (which makes sense):

```<code>method computeBalance() is already defined in class XXX
</code>```

答:
Obviously two methods in example are ambiguous and that code cannot be compiled because both methods have same name and same parameters.

```<code>public static void computeBalance(double deposit)
public static void computeBalance(double withdrawal)
</code>```

Author does not claim that you can compile and use above as stated in

When you overload methods, you risk creating an ambiguous situation -
  one which the compiler cannot determine which method to use.

and then

and make a method call such as computeBalance(myDeposit);, you will
  have created an ambiguous situation. Both methods are exact matches for your call.

and later in

but Java makes no assumptions based on variable names. Each version of
  computeBalance() could accept a double, and Java does not presume
  which one you intend to use.

The only thing author didn't explicitly say in text you quoted is that ambiguous code cannot be compiled.

Personally, I don't think that is mistake on his part and that his text is in any way misleading or confusing, because that should be obvious from "compiler cannot determine which method to use" at least.

Author is just creating hypothetical situation where person reading the code might be able to determine right method based on variable and parameter names, trying to explain that compiler has no such abilities and cannot see broader context.

Just as additional note. Different languages have different definitions what represents ambiguous call. For instance, while Java compiler is not able to overload methods that have same parameter list but different return type Swift compiler can.

Title: Ambiguity in method overloading

Body:
Obviously two methods in example are ambiguous and that code cannot be compiled because both methods have same name and same parameters.

public static void computeBalance(double deposit)
public static void computeBalance(double withdrawal)

Author does not claim that you can compile and use above as stated in

When you overload methods, you risk creating an ambiguous situation -
  one which the compiler cannot determine which method to use.

and then

and make a method call such as computeBalance(myDeposit);, you will
  have created an ambiguous situation. Both methods are exact matches for your call.

and later in

but Java makes no assumptions based on variable names. Each version of
  computeBalance() could accept a double, and Java does not presume
  which one you intend to use.

The only thing author didn't explicitly say in text you quoted is that ambiguous code cannot be compiled.

Personally, I don't think that is mistake on his part and that his text is in any way misleading or confusing, because that should be obvious from "compiler cannot determine which method to use" at least.

Author is just creating hypothetical situation where person reading the code might be able to determine right method based on variable and parameter names, trying to explain that compiler has no such abilities and cannot see broader context.

Just as additional note. Different languages have different definitions what represents ambiguous call. For instance, while Java compiler is not able to overload methods that have same parameter list but different return type Swift compiler can.


问:
Why Garbage Collection if smart pointers are there
These days, so many languages are garbage collected. It is even available for C++ by third parties. But C++ has RAII and smart pointers. So what's the point of using garbage collection? Is it doing something extra?

And in other languages like C#, if all the references are treated as smart pointers(keeping RAII aside), by specification and by implementation, will there still be any need of garbage collectors? If no, then why is this not so?

答:
Number one limitation of smart pointers is they don't always help against circular references. For example you have object A storing a smart pointer to object B and object B is storing a smart pointer to object A. If they are left together without resetting either of the pointers they won't ever be deallocated.

This happens because a smart pointer has to perform a specific action which won't be triigered in the above scenario because both objects are unreacheable to the program. Garbage collection will cope - it will properly identify that objects are not reachecable to the program and they will be collected.

ContentLicense: CC BY-SA 2.5


答:
Why is it beneficial to use the strategy pattern if you can just write your code in if/then cases?

Sometimes you should just use if/then. It is simple code that is easy to read.

The two key problems with simple if/then code is that it can violate the open closed principle. If you ever have to go in and add or change a condition, you're modifying this code. If you expect to have more conditions, just adding a new strategy is simpler/cleaner/less-likely-to-break-stuff.

The other problem is coupling. By using if/then, all of the implementations are tied to that implementation, making them harder to change in the future. By using the strategy, the only coupling is to the interface of the strategy.

Title: Advantages of Strategy Pattern


问:
Laravel Algorithm for taxi app
I am trying to write a backend for a taxi service (university assignment) and I am stuck on the algorithm.

whenever a new client posts a request, all the taxi drivers nearby get an email notification and, for five minutes, I have to collect the positive answers (the ones who are willing to give a lift).

After five minutes, I have to match the customer with the best taxi driver who answered, based upon feedback and distance.

I have set up everything in Laravel 5.1, but don't know how to implement the "pool" of answers from drivers. Should I use a temporary MySQL table or opt for a temp file storage? Or design a different way of tackling with it?

答:
Using the database has a bunch of benefits.  Some of these benefits don't apply to a school project, but I'll list them anyhow.

If a driver is notified about two fares, make sure the driver isn't assigned both.

The state of the system is represented in fewer places.

Storing business rules makes changing business rules without a recompile more feasible.  This isn't necessarily a win (it can encourage cowboy coding), but in the case of a project which will never have a version 2, that's moot.

A database schema is easier to create/adapt than a file system, which requires a file names and serialization.

Inspecting the current state of your system is easier with a database.  Creating sophisticated queries (e.g., for debugging or to assist a help desk) is easier if the data is in the database.

A database will scale up more easily.

The main benefit of using a file system is that it may have a slightly lower start-up cost.  This lower cost introduces a bunch of problems (which a database is designed to solve), but such problems may be unimportant in the case of a school project.  Taking on a big chunk of technical debt to save a small amount of time isn't a big deal if you're creating a project that will never be maintained.

Title: Laravel Algorithm for taxi app


问:
How much Code Coverage is "enough"?
We are starting a push for code coverage here at my work, and it has got me to thinking.... How much code coverage is enough?

When do you get to the point of diminishing returns on code coverage?  What is the sweet spot between good coverage and not enough?  Does it vary by the type of project your are making (ie WPF, WCF, Mobile, ASP.NET)  (These are C# classes we are writing.)

答:
I really like @RevBingo's answer because he suggests that the struggle toward 100% can cause you to clean up or delete unused code.  What I haven't seen in the other answers is a sense of when you need high coverage and when you don't.  I took a stab at starting this.  I think adding detail to a chart like this would be a more useful pursuit than finding one test coverage number that was right for all code.

100%

For a public API, like the java.util Collections, that's not coupled to a Database and doesn't return HTML, I think 100% coverage is a noble starting goal, even if you settle for 90-95% due to time or other constraints.  Increasing test coverage after you are feature complete forces a more detailed level of scrutiny than other kinds of code review.  If your API is at all popular, people will use it, subclass it, deserialize it, etc. in ways you can't expect.  You don't want their first experience to be finding a bug, or design oversight!

90%

For business infrastructure code, that takes in data structures and returns data structures, 100% is still probably a good starting goal, but if this code isn't public enough to invite a lot of misuse, maybe 85% is still acceptable?

75%

For code that takes in and returns Strings, I think unit testing is much more brittle, but can still be useful in many situations.

50% or less

I hate writing tests for functions that return HTML because it's so brittle.  What if someone changes the CSS, the JavaScript, or the whole blob of HTML and English you return makes no sense to human end users?  If you can find a function that uses a lot of business logic to produce a little HTML, this may well worth testing.  But the reverse situation may not be worth testing at all.

Near 0%

For some code, the definition of "correct" is "makes sense to the end user."  There are non-traditional tests you can perform against this code like automated grammar-checking or HTML validating the output.  I've even set up grep statements for little inconsistencies we commonly fall prey to at work, like saying "Login" when the rest of the system calls it, "Sign In".  This man not strictly be a unit test, but a helpful way to catch issues without expecting specific output.

Ultimately though, only a human can judge what is sensible to humans.  Unit testing can't help you there.  Sometimes it takes several humans to judge that accurately.

Absolute 0%

This is a sad category and I feel like less of a person for writing it.  But in any sufficiently large project there are rabbit holes that can suck person-weeks of time without providing any business benefit.

I bought a book because it claimed to show how to automatically mock data for testing Hibernate.  But it only tested Hibernate HQL and SQL queries.  If you have to do a lot of HQL and SQL, you really aren't getting the advantage of Hibernate.  There's a form of Hibernate in-memory database, but I haven't invested the time to figure out how to use it effectively in tests.  If I had that running, I'd want to have high (50%-100%) test coverage for any business logic that calculates stuff by navigating an object graph causing Hibernate to run some queries.  My ability to test this code is near 0% right now and that's a problem.  So I improve test coverage in other areas of the project and try to prefer pure functions over ones that access the database, largely because it's easier to write tests for those functions.  Still, some things cannot, or should not be tested.

Title: How much Code Coverage is "enough"?


问:
the future of commercial products
I'm seeing that the open source solutions are growing rapidly & many companies use them now.  What do you think the future for commercial products or solutions will be?</p>

答:
I think the answer can be found in terms of making a copy of your DVDs so you can watch them on your portable device of choice.

You can do this with open source software - mostly - but obtaining same and the instructions for use can tax the patience and the grey cells of someone who theoretically is both competent and comfortable with the technology. This before you try and work out what all the settings mean...

Or you can pay a small amount of money for a commercial piece of software that more or less reduces the exercise to: 1) Load Disk 2) Click.

Most people want stuff that "just works" and continues to do so - they've no more interest in how it works than in how an internal combustion engine functions or why planes stay up - just so long as it does.

Title: the future of commercial products


问:
Is recursion a bad idea for large input sizes due to the limited call stack size?
Call stack size in JavaScript:

```<code>Three results:
- Node.js: 11034
- Firefox: 50994
- Chrome: 10402
</code>```

It seems like it would be a bad idea to use recursion for things like BST insertion, because there's a chance you may be dealing with input sizes in the millions or billions.

答:
Unbounded recursion is generally a bad idea if you know the recursive calls could get very deep. But if you have some way of ensuring a relatively small maximum depth for your recursive algorithm, or your language supports tail recursion and your algorithm is one that can take advantage of it, then you can safely ignore this issue.

P.S. ECMAScript 6 has tail recursion, so for Javascript at least, this will be significantly less of an issue in the future.


问:
Why aren't data structures like BSTs part of the core libraries of more languages?
For example, why doesn't JavaScript provide a BST as a native data structure you could use?

```<code>var bst = new BST();
bst.insert('5');
bst.insert('3');
bst.find('5'):
</code>```

Alternative question: what are the costs and benefits to including such structures in a language? I don't see what the costs are, other than the time it takes to implement. Would having an additional data structure slow other things down?

Basically, I'm asking this from the perspective of someone who is familiar with the basics of data structures and is a JavaScript developer, but knows very little about compilers and language design. The way I see it, by adding an additional data structure, it's there if you want it, but won't hurt those who don't want to use it. But I'm sure that there are important things I'm not considering, and what I'm really asking is "what are they"?

答:
When you are designing a programming language, you generally want the core of the language to be as simple as possible but as general as possible and as expressive as possible, while still fulfilling its core design objectives.  When you add a feature to a language, you have to consider how it fits with the overall design and philosophy of the language.  Anything that doesn't meet that esthetic belongs in an external library, not in the language.

The purpose of binary trees is to provide a fast way to lookup something given a key.  Because Javascript has lists with key/value pairs as one of its core features, there is a potential use for binary trees in the the language itself.  But the designer of Javascript didn't choose a binary tree as his backing store; he picked a hash table.  So the binary tree is left with no potential use case in the language itself.

If you're going to add binary trees to a language, why not also add b-trees?  Red-black trees? Skip lists?  Why a binary tree specifically?  Each of these data structures does essentially the same thing, but with different performance characteristics.  Having such data structures in a library allows the programmer to choose what he needs from the library without adding dead weight to the language.

For all of these reasons, binary trees are a better fit in an external library rather than the programming language, in most cases.


问:
Implementing a pay-per-user business model

Introduction

I'm working on an application where organisations pay for each user they add to their 'environment'. Organisations have a credit/balance, and as long as the user is not removed, the organisation pays a small hourly fee per user. Organisations can choose between recurring and one-time payments. An invoice will be made for every payment.

I'm trying to find the best way to implement this. So far, I've come up with two possible solutions:

Option A

The first possible solution is to 'log' every change of state in the system regarding users, payments and pricing.

When an organisation adds or removes a user, a log entry will be written. When a payment is being made, a log entry will be written. When the price changes, a log entry will be written. Every relevant state will be recorded.

Using these these logs, the application can calculate the credit/balance.

Option B

The second possible solution is to implement a physical credit/balance. Instead of logging everything, an hourly cron job will run that subtracts the fee per user from the organisation's credit/balance.

This second option seems much simpler to me. It avoids making all kinds of complex calculations using multiple tables and records. I'll probably need to log payments and stuff anyway, but I'm not using those logs to determine the credit/balance.

Any thoughts? What's the best way to implement this kind of system?

Edit

After considering @Ewan's answer, I do believe he brings up a good point. That's why I'm going with option A, or something that looks like option A.

Here's a simplified DB schema I created:

Does this look like it could work?

答:
Have you considered something like a combination of the two?

Once per hour, compute the charge, and record everything that comprises that charge in a write-only table.   Then once/month (or however long) an invoice can be generated off that data.  If there's any disputes or discrepancies, it should be relatively easy to track down.

This doesn't take the place of having good logs, which is what you would get in Option A.


问:
ID in class diagram
As far as i know, we do not add an attribute like id to the classes in the class diagram. right?

But when we create a database, or when we want to call an instance, we need its id, so why do not we have this attribute in our diagrams?

答:
The meaning of a class diagram depends on the level of abstraction at which you are modeling.

For example, you could create a class diagram of the real world. In that case, class 'Shark' obviously doesn't have an 'id', because sharks don't have ids in nature. It would maybe have attribute 'length' and operation 'eatFish'.

But maybe you are creating a class diagram to define the schema of a relational database containing a Shark table, in which each shark has a unique id. In that case, you must show 'id' as an attribute of class 'Shark'. Maybe you want to model its stored procedures as operations of the class.

In between these two extremes, you may want to model at an intermediate level of abstraction. For example, you could create a conceptual data model for a shark game, i.e. a data model that defines how the user perceives the data of the application. In that case, if the application exposes the ids to the user, then you must model this as an attribute of class Shark. But if the application uses ids only internally, then you don't.

One final example: you may want to model your source code, written in an object-oriented language. In that case, if 'id' is a member of class 'Shark' in the source code, then 'id' is an attribute in your diagram and otherwise it isn't .

To summarize, if you create a class diagram, you must define at which level of abstraction you are modeling and what you mean by the concept of a 'class'. This will give you guidance on which attributes it should have.

Title: ID in class diagram


问:
One wide table or multiple themed tables?
I'm trying to design a database for a simple text based game where the player characters have a large number of statistics that I want to track. Currently I have a few groups of related statistics, skills, finances, basic attributes, and a few others. There are quite a few fields that are 1 to 1 with a character which is leading me to the following design dilemma: Do I put all of these 1 to 1 fields in one very wide table or do I split them into tables that are themed on their group?

If I put all of the fields into one table, I am looking at a table with at least 20 columns, potentially more as more features come up. This would give me only one place to go to for information on the character and would make loading the data into the application very easy. However I imagine that updating records in such a large table would be a hassle since I would need to ensure that updating one field doesn't break the rest of the data.

If I split the data I would have 3 or 4 tables linked by the character id, each with no more than 10 columns. I feel like this would make the data easier to see from a data viewer point of view and updates would be less volatile, but when I have to gather all the player information I have to make multiple queries to the different tables.

I am curious what those with more experience in database design think about this. I have read up a bit on database normalization but that seems to focus on splitting out data that is joined by relationships instead of data that is 1 to 1. If it makes a difference I am using ASP.NET Entity Framework Code First to create the database in SQL Server Express.

答:
It sounds like you are questioning if you need to split the master table up because there are so many columns.  The short answer is no.  I'll touch on a longer answer below.

In a simple way of looking at databases, it's about groups of datum and what those groups represent.  Relational databases being relationship, or links, between groups of datum.  So, when you think about what goes in a table, or group of tables, you are working out aspects of some "entity" by way of the data that represents this thing.  As you already know, this is done with a master table and one or more child tables.

As an example, an employee.  We have a name, dob, id number(s), address, phone number, hire date, and so on.  Some of these things are 1 to 1 some are 1 to n.  That's how we generally break out where things go from a design point of view.  That gives us a master table and some number of child tables.

Most modern databases will not have a problem with a master table having what you think of as a large number of columns. Ten, twenty, a hundred, none if that matters to the database.  So, from a logical design point of view there is no reason to break-up that master table.  However, the real world and theory do not get along all the time.  I must stress that these times are RARE, often a different way of looking at the data will allow you to express it in a different way and avoid the issue.  If you find yourself having really huge numbers of columns, ask why they are there and try to look at them from another point of view.

Back to the employee example, phone number.  There could be several numbers here.  So do I make a column for home phone another for cell phone and yet another for work extension?  I may, or I may make a child table for it.  That table would have three fields, id, category, number.  So, what looked like three columns in the master table is in fact moved to a child table.  Same data, different way of looking at it.

I think this maybe close to home for your case, but I admit that I am guessing here.  I could see a set of stats that represent a character looking like they are part of the master table but really, they could easily be express as a child table.  You mentioned basic attributes and skills, both of which would raise a red flag for me if they are part of the master table.  Again, I am making some assumptions based on my rpg experiences with both computer and pen&paper games.  As your game evolves you may well find a reason to add a new skill, you may even add a new base attribute.  You may change or throw out an existing skill or base attribute.  Do you want your database to change too?  Ideally, no your don't want to have to go back and change your database structure and then the code for the database layer and then system logic code layer and then the UI code layer.  You want to changes like that to affect as little code as possible.  So, maybe you have a skill table, in which each row is a skill.  Likewise, a base attribute table with each attribute as a row.  Note that I say row not column in these cases, just like with employee phone number.

I feel myself beginning to ramble, so now I stop.

So, that's a longer answer.  To summarize it, no you don't need to break up a master table because it has many columns HOWEVER you do want to analyze those columns to make sure they can't be expressed another way, like child table rows.

Hope that helps.


答: Thoughtless use of recursion can get you into trouble. However, quite often the maximum depth of recursion can be kept small. If you have recursion with one recursive call, it can often be easily replaced with iteration. If you have two or more recursive calls, usually most of the calls are doing greatly reduced work. For example in quicksort, you split an array into two parts, one is bigger, one is smaller. Do the smaller parts with recursion, and the bigger part with iteration.

Title: Is recursion a bad idea for large input sizes due to the limited call stack size?

Body:
Call stack size in JavaScript:

```<code>Three results:
- Node.js: 11034
- Firefox: 50994
- Chrome: 10402
</code>```

It seems like it would be a bad idea to use recursion for things like BST insertion, because there's a chance you may be dealing with input sizes in the millions or billions.


答:
Most smart pointers are implemented using reference counting. That is, each smart pointer that refers to an object increments the objects reference count. When that count goes to zero, the object is released.

The problem there is if you have circular references. That is, A has a reference to B, B has a reference to C and C has a reference to A. If you're using smart pointers, then in order to free the memory associated with A, B & C you need to manually get in there an "break" the circular reference (e.g. using weak_ptr in C++).

Garbage collection (typically) works quite differently. Most garbage collectors these days use a reachability test. That is, it looks at all of the references on the stack and the ones that are globally accessible and then traces every object that those references refer to, and objects they refer to, etc. Everything else is garbage.

In that way, circular references don't matter any more - as long as neither A, B and C are reachable, the memory can be reclaimed.

There are other advantages to "real" garbage collection. For example, memory allocation is extremely cheap: just increment the pointer to the "end" of the memory block. Deallocation has a constant amortized cost as well. But of course languages like C++ allow you to implement memory management pretty much any way you like, so you could come up with an allocation strategy that's even faster.

Of course, in C++ the amount of heap-allocated memory is typically less than a reference-heavy language like C#/.NET. But that's not really a garbage-collection vs. smart pointers issue.

In any case, the issue isn't cut-and-dry one is better than the other. They each have advantages and disadvantages.

Title: Why Garbage Collection if smart pointers are there

Body:
These days, so many languages are garbage collected. It is even available for C++ by third parties. But C++ has RAII and smart pointers. So what's the point of using garbage collection? Is it doing something extra?

And in other languages like C#, if all the references are treated as smart pointers(keeping RAII aside), by specification and by implementation, will there still be any need of garbage collectors? If no, then why is this not so?


答: If by BST you mean a balanced search tree, then recursion is perfectly fine, because the balancing ensures that the recursion depth is O(log n). That's why we do it in the first place. But using recursion to implement a linked list - really bad, unless you have tail call elimination.</p>


答:
Option A is far superior.

Imagine your cron job crashes and doesnt run over a weekend. Or you find a bug and its been calculating the price slightly wrong for ages. You would have no way to figure out the correct bills.

In any system like this you have to consider how you would check the results. so you need to be able to not only bill correctly, but go back and explain the bill calculation and prove it is correct.

Title: Implementing a pay-per-user business model

Body:
Introduction

I'm working on an application where organisations pay for each user they add to their 'environment'. Organisations have a credit/balance, and as long as the user is not removed, the organisation pays a small hourly fee per user. Organisations can choose between recurring and one-time payments. An invoice will be made for every payment.

I'm trying to find the best way to implement this. So far, I've come up with two possible solutions:

Option A

The first possible solution is to 'log' every change of state in the system regarding users, payments and pricing.

When an organisation adds or removes a user, a log entry will be written. When a payment is being made, a log entry will be written. When the price changes, a log entry will be written. Every relevant state will be recorded.

Using these these logs, the application can calculate the credit/balance.

Option B

The second possible solution is to implement a physical credit/balance. Instead of logging everything, an hourly cron job will run that subtracts the fee per user from the organisation's credit/balance.

This second option seems much simpler to me. It avoids making all kinds of complex calculations using multiple tables and records. I'll probably need to log payments and stuff anyway, but I'm not using those logs to determine the credit/balance.

Any thoughts? What's the best way to implement this kind of system?

Edit

After considering @Ewan's answer, I do believe he brings up a good point. That's why I'm going with option A, or something that looks like option A.

Here's a simplified DB schema I created:

Does this look like it could work?


问:
try-catch in javascript... isn't it a good practice?
There is a provision for try-catch block in javascript. While in java or any other language it is mandatory to have error handling, I don't see anybody using them in javascript for greater extent. Isn't it a good practice or just we don't need them in javascript?

答:
A lot of these answers are a bit old and do not take into account the new ES7 features async and await.

Using async/await you can now get asynchronous control flow like you want:

```<code>async function email(address) {
  try {
    // Do something asynchronous that may throw...
    await sendEmail({ to: address, from: 'noreply@domain.com', subject: 'Hello' })
  } catch(err) {
    if (err instanceof SomeCustomError) {
      elegantlyHandleError(err)
    } else {
      throw err
    }
  }
})
</code>```

You can learn more about async/await here, and you can use async/await now using babel.

Body:
A lot of these answers are a bit old and do not take into account the new ES7 features async and await.

Using async/await you can now get asynchronous control flow like you want:

async function email(address) {
  try {
    // Do something asynchronous that may throw...
    await sendEmail({ to: address, from: 'noreply@domain.com', subject: 'Hello' })
  } catch(err) {
    if (err instanceof SomeCustomError) {
      elegantlyHandleError(err)
    } else {
      throw err
    }
  }
})

You can learn more about async/await here, and you can use async/await now using babel.

ContentLicense: CC BY-SA 4.0


问:
C automatic variables
I'm designing 2 functions, I'm trying to be sure I doing correctly. The idea is that in the first function , a struct pointer is created and passed to a function that might or might not fill the said struct. In the event the struct is not filled I was hoping that the pointer in the first function would get removed by automatic variable rule. Will this result in code that is difficult to understand or maintain?

Here is first function :

```<code>static void read_cb(struct bufferevent *bev, void *ctx) {
    /* This callback is invoked when there is data to read on bev. */

    struct header_t *header;.

    int result;
    result = checkForHeader(bev, header);

    if (result == 0) {
        return;
    }
    // More code here...
    // Here would be safe to assume header is filled and usable...
}
</code>```

and here is second / filling function :

```<code>int checkForHeader(struct bufferevent *bev, header_t *header) {

    struct evbuffer *input = bufferevent_get_input(bev);
    struct evbuffer *output = bufferevent_get_output(bev);

    size_t buffer_len = evbuffer_get_length(input);
    ev_uint32_t record_len;

    if (buffer_len < CS_HEADER_SIZE)
        return 0; /* The size field hasn't arrived. */

    // We have an actual header (parsing)
    header = calloc(1, sizeof(*header));

    if (!header) {
        perror("calloc");
        return 0;
    }
    header->filled = 1; // Just an example.
    return 1;
}
</code>```

答: The parameter header is a local variable in the second function. Whatever you store in it will be lost when the function returns. Since you stored a pointer to memory allocated with calloc, that pointer is lost, and the allocated memory stays allocated forever without any possibility to ever use it or free it. </p>

Title: C automatic variables


问:
Is the usage of internal scope blocks within a function bad style?
There are some (quite rare) cases where there is a risk of:

reusing a variable which is not intended to be reused (see example 1),

or using a variable instead of another, semantically close (see example 2).

Example 1:

```<code>var data = this.InitializeData();
if (this.IsConsistent(data, this.state))
{
    this.ETL.Process(data); // Alters original data in a way it couldn't be used any longer.
}

// ...

foreach (var flow in data.Flows)
{
    // This shouldn't happen: given that ETL possibly altered the contents of `data`, it is
    // not longer reliable to use `data.Flows`.
}
</code>```

Example 2:

```<code>var userSettingsFile = SettingsFiles.LoadForUser();
var appSettingsFile = SettingsFiles.LoadForApp();

if (someCondition)
{
    userSettingsFile.Destroy();
}

userSettingsFile.ParseAndApply(); // There is a mistake here: `userSettingsFile` was maybe
                                  // destroyed. It's `appSettingsFile` which should have
                                  // been used instead.
</code>```

This risk can be mitigated by introducing a scope:

Example 1:

```<code>// There is no `foreach`, `if` or anything like this before `{`.

{
    var data = this.InitializeData();
    if (this.IsConsistent(data, this.state))
    {
        this.ETL.Process(data);
    }
}

// ...

// A few lines later, we can't use `data.Flows`, because it doesn't exist in this scope.
</code>```

Example 2:

```<code>{
    var userSettingsFile = SettingsFiles.LoadForUser();

    if (someCondition)
    {
        userSettingsFile.Destroy();
    }
}

{
    var appSettingsFile = SettingsFiles.LoadForApp();

    // `userSettingsFile` is out of scope. There is no risk to use it instead of
    // `appSettingsFile`.
}
</code>```

Does it look wrong? Would you avoid such syntax? Is it difficult to understand by beginners?

答: Using a scope is technically right. But if you want to make your code more readable then you should extract that part in another method and give that a meaning full name. In this way you can give a scope of your variables and also give a name of your task.</p>


问:
Overwriting a C system after exec?
So I used wrap to override the malloc call in my program, I didn't think that if I exec'd another it would work, and it didn't. I figure this is because it wasn't linked with my program. How could I overwrite a C call in another program?
Sample:</p>

```<code>void* __wrap_malloc(size_t size) {
    void* mal = __real_malloc(size);
    printf("malloced %i @ %i\n", size, mal);
    return mal;
}
int main(int argc, char *argv[]) {
    malloc(1024);
    execl("/bin/bash", "/bin/bash", (char *) NULL);
    return 0;
}
</code>```

答:
Define an environment variable LD_PRELOAD to point to a shared library overriding required functions.

See http://hackerboss.com/overriding-system-functions-for-fun-and-profit/

Title: Overwriting a C system after exec?


答:
There are two big differences, to my mind, between garbage collection and smart pointers as used for memory management:

Smart pointers can't collect cyclic garbage; garbage collection can

Smart pointers do all the work at the moments of referencing, dereferencing, and deallocation, on the application thread; garbage collection need not

The former means that GC will collect garbage that smart pointers won't; if you're using smart pointers, you have to avoid creating this kind of garbage, or be prepared to deal with it manually.

The latter means that no matter how smart smart pointers are, their operation will slow down the working threads in your program. Garbage collection can defer work, and move it to other threads; that lets it be more efficient overall (indeed, the runtime cost of a modern GC is less than a normal malloc/free system, even without the extra overhead of smart pointers), and do what work it still needs to do without getting in the way of the application threads.

Now, note that smart pointers, being programmatic constructs, can be used to do all sorts of other interesting things - see Dario's answer - which are completely outside the scope of garbage collection. If you want to do those, you will need smart pointers.

However, for the purposes of memory management, i don't see any prospect of smart pointers replacing garbage collection. They simply aren't as good at it.


问:
What is time complexity of update in binary heap?
For a binary heap we have O(log(n)) for insert, O(log(n)) for delete min and heap construction can be done in O(n).

In the context of using a binary heap in Djikstra, my exam paper involved an "update" in the heap where the priority of a vertex is changed.

I assumed that the time complexity of this update would be O(n) since it seemed to me that locating the vertex in the heap would require something in the order of a linear search, followed by an upheap or downheap. This would be O(n + log(n)) which is simply O(n).

Unfortunately I think this lead me to the wrong answer.

So, what is the actual time complexity of a priority update in a binary heap?

答:
The key to resolving your problem is to return a special object on the insertion of a element. When you move the real object in the heap, you update the position in this object.

To call decrease-priority you pass this object so you can go right to the position in the heap and bubble up the element if necessary.

In this way it's O(log(n)). In fact finding the element is O(1) and restoring the heap property is O(log(n)).

P.s. You should check whether the new priority actually decreases.


答:
Currently I have a few groups of related statistics, skills, finances,
  basic attributes, and a few others.

Well, actually it depends. I highlighted the key word in your sentence.

If those groups are really "groups", why not to split them into tables? But the reason should not be "because the table went large" (at least when performance is not yet your primary concern), but because you see them as groups, that can be independently worked on.

Splitting data between tables slows access (because to aggregate it you will need several queries). But it gives you ability to independently work on this data, to view it, evaluate it and develop it independently.

Title: One wide table or multiple themed tables?

Body:
I'm trying to design a database for a simple text based game where the player characters have a large number of statistics that I want to track. Currently I have a few groups of related statistics, skills, finances, basic attributes, and a few others. There are quite a few fields that are 1 to 1 with a character which is leading me to the following design dilemma: Do I put all of these 1 to 1 fields in one very wide table or do I split them into tables that are themed on their group?

If I put all of the fields into one table, I am looking at a table with at least 20 columns, potentially more as more features come up. This would give me only one place to go to for information on the character and would make loading the data into the application very easy. However I imagine that updating records in such a large table would be a hassle since I would need to ensure that updating one field doesn't break the rest of the data.

If I split the data I would have 3 or 4 tables linked by the character id, each with no more than 10 columns. I feel like this would make the data easier to see from a data viewer point of view and updates would be less volatile, but when I have to gather all the player information I have to make multiple queries to the different tables.

I am curious what those with more experience in database design think about this. I have read up a bit on database normalization but that seems to focus on splitting out data that is joined by relationships instead of data that is 1 to 1. If it makes a difference I am using ASP.NET Entity Framework Code First to create the database in SQL Server Express.


问:
How can I target both Windows 10 UWP and Windows Phone 8.1 in the same app?

Background

From a developer's viewpoint, the main selling point of Windows 10 is its new Universal* Windows Platform (UWP).

* Where "Universal" really means "universal to all devices that run Windows 10", and not "universal to devices that run not only Windows 10, but also Windows 8.1 and maybe Windows 7". So if you're building a UWP app, you're really just building a "Windows 10 app". UWP apps will not run even on Windows 8.1 and Windows Phone 8.1 devices, i.e. they're not backward-compatible at all.

As of Q3 2015, Windows 10 is available for PCs and IoT devices. It'll be at least another few months before Windows 10 Mobile is released to the public, but probably no more than a year. This means that Windows Phone 8.1 will remain around for a while yet.

Question

I'm about to start developing a Windows Phone app, and I plan to publish it within the next month or so as it's a fairly simple app. Since Windows 10 Mobile won't be arriving anytime soon, let alone devices the world over getting upgraded, I have to target Windows Phone 8.1 for now. However, since it won't be that long before Windows 10 Mobile rolls out, I'm wondering if it'd be wise to prepare my solution for deployment to Windows 10 UWP as well as Windows Phone 8.1 (which will also allow me to continue supporting 8.1 for as long as I need).

I see that I can group a UWP project and an 8.1 project in the same solution, and share source files and assets via a Shared project as done with the Windows 8.1 Universal template in Visual Studio. Am I on the right track? If so, are there any additional guidelines I should follow to ensure everything (including XAML, as ideally I'd like to have the same or at least similar UI on both platforms) actually works correctly on both platforms accounting for any incongruities?

Alternatively, I could just not worry about Windows 10 Mobile for now and start with an 8.1 project, and migrate it to UWP later on, but I'd still have to maintain both versions of my app since I don't plan on ditching 8.1 users immediately. I'd still have to worry about feature/XAML parity in this case.

答:
As you say in one of your comments the best way to go about this is by using a shared project and adding several heads to it. In your case a windows phone 8.1 head and a uwp head. This position was also expressed in an MVA by Jerry Nixon and Andy Wigley (I think this is it, but it has been updated since), in the section about porting 8.1 apps to uwp.

In your shared project you may have to use conditional compilation directives to differentiate between code that runs in uwp and phone 8.1. (Like when creating universal windows 8.1/phone 8.1 apps)


问:
Question regarding actors in a Use Case diagram
OK, so I have this homework question whereby we are given a rather complex system description and need to create several UML diagrams that describe the system being described.

I'm having an issue with designing the Use-Case diagram for it.
Here is a very simplified description of the system:

The system being described is one that simulates jobs being performed by a multi processor machine. The simulation system is comprised of several components including:

Manager

Simulator

Scheduler

Parser

etc.

A user opens the simulation system by defining a configuration file (including job descriptions) into the manager, and hitting "run". When the simulation finishes, a statistics file is generated (and can be presented to the user)

The problem I have with the Use-Case diagram is what do I put as the Actors?
As far as I'm aware, an Actor should be a human user, an external piece of hardware, or an external piece of software.

Going with this logic, the use case for the above system is overly simple, it's just one Actor labeled "user" which interacts with one action which will be named "simulation".

But I feel as if maybe I'm supposed to put all the components of the system as actors.

Anyone have any ideas?
Thank you!

答: An actor does not have to be a human user, it can also be a system itself. In your case, the system actually running the simulations can be considered an actor itself because it will also interact with use cases ('the system' will run a simulation)</p>


问:
How narrow or broad should constant names be?
I always seem to come back to this question and cannot settle on a convention that I'm comfortable with or that I can concretely define: when naming a constant, how narrowly or broadly should it be named?

For instance, let's say I've written a workflow application that has workflow items (instances of the workflow) and those have, among other properties, a "stage name".  When a workflow item is being initiated, it will get the initial stage name, which should be a constant.  Should I name the constant, e.g., InitialStageName or should I name it LoanApplicationApproverStageName (assuming the first stage is the loan application approver" stage).  In both cases, the value might be something like "LoanAppApprvr".

I guess it boils down to this: is it more important to name the constant based on how it's used (e.g. as the initial stage name) or on what it means (e.g. the stage where the loan approver performs their work)?  Or should there be some marriage between the two -- possibly by having two separate constants that share the same value?

答:
I would use the LoanApplicationApproverStageName; it conveys more meaning when used:

```<code>setInitialState(LoanApplicationApproverStageName);
</code>```

as opposed to:

```<code>setInitialState(InitialStageName);
</code>```

Looking at the second example, you have no understanding of what the initial state is being set as.

Additionally, You might be tempted to use this value ("LoanAppApprvr") in other locations where you intend to refer to LoanApplicationApproverStageName - the stage, not it's place as the initial stage.

Body:
I would use the LoanApplicationApproverStageName; it conveys more meaning when used:

setInitialState(LoanApplicationApproverStageName);

as opposed to:

setInitialState(InitialStageName);

Looking at the second example, you have no understanding of what the initial state is being set as.

Additionally, You might be tempted to use this value ("LoanAppApprvr") in other locations where you intend to refer to LoanApplicationApproverStageName - the stage, not it's place as the initial stage.


答:
The place where your constants are defined is also important as that information enhances the constant, without making the name longer.

Compare a class Constants that holds all the constants and is in the namespace MyApp.Global. You can have constants in there called Width, Height and Radius that really don't mean a lot being in there. These constants benefit from having clearer names, such as DefaultSquareWidth, DefaultRectangleHeight and DefaultCircleRadius.

Compare this to a constant defined in the MyApp.Shapes namespace on the Circle object. The meaning of a constant named DefaultRadius would be very obvious because of where you can find it.

Ask yourself the question if typing the constant name in a certain place will make it immediately obvious what it means. Typing MyApp.Global.Constants.Radius is a lot less obvious than MyApp.Shapes.Circle.DefaultRadius or MyApp.Global.Constants.DefaultCircleShapeRadius.

Title: How narrow or broad should constant names be?

Body:
I always seem to come back to this question and cannot settle on a convention that I'm comfortable with or that I can concretely define: when naming a constant, how narrowly or broadly should it be named?

For instance, let's say I've written a workflow application that has workflow items (instances of the workflow) and those have, among other properties, a "stage name".  When a workflow item is being initiated, it will get the initial stage name, which should be a constant.  Should I name the constant, e.g., InitialStageName or should I name it LoanApplicationApproverStageName (assuming the first stage is the loan application approver" stage).  In both cases, the value might be something like "LoanAppApprvr".

I guess it boils down to this: is it more important to name the constant based on how it's used (e.g. as the initial stage name) or on what it means (e.g. the stage where the loan approver performs their work)?  Or should there be some marriage between the two -- possibly by having two separate constants that share the same value?


问:
Advantages of Strategy Pattern
Why is it beneficial to use the strategy pattern if you can just write your code in if/then cases?

For example: I have a TaxPayer class, and one of its methods calculates the taxes using different algorithms. So why can't it have if/then cases and figure out what algorithm to use in that method, instead of using the strategy pattern? Also, why can't you just implement a separate method for each algorithm in the TaxPayer class?

Also, what does it mean for the algorithm to change at runtime?

答:
Strategy is useful when the if/then conditions are based on types, as explained in http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html

Type-checking conditionals usually don't have a high cyclomatic complexity, so I wouldn't say that Strategy improves things necessarily there.

The main reason for Strategy is explained in the GoF book p.316 that introduced the pattern:

Use the Strategy pattern when

...

a class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.

As mentioned in other answers, if applied appropriately the Strategy pattern allows adding new extensions (concrete strategies) without necessarily requiring modifications of the rest of the code. This is the so-called Open-Closed principle or Protected Variations principle. Of course, you still have to code the new concrete strategy, and the client code has to recognize the strategies as plug-ins (this is not trivial).

With if/then conditionals, it's necessary to change the code of the class containing the conditional logic. As mentioned in other answers, sometimes this is OK when you don't want to add the complexity to support adding new functionality (plug-ins) without re-compiling.

Title: Advantages of Strategy Pattern


问:
Django Migrations: Binds data to code?

If you have custom code for models (custom validators and custom fields are examples), Django Migrations will import them directly into the migration files. An example:

file web/models.py

def validate_power(self, power):
    if power == 'fly':
        raise ValidationError('Heroes cannot fly!')

class Hero(Model):
    power = CharField(max_length=30, validators=[validate_power])
```

<p>In the migration file, there will be:</p>

<p><strong>file web/migrations/0001_initial.py</strong></p>

<pre class="lang-py prettyprint-override"><code>class Migration(migrations.Migration):

    operations = [
        migrations.CreateModel(
            name='Hero',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
                ('power', models.CharField(max_length=30, validators=[web.models.validate_power])),
            ],
        ),
    ]
</code>```

The validator is imported directly from the codebase. What this means is that if I ever change a validator, I have to make sure it is backwards-compatible, for as long as I keep that migration (which could be forever). Same happens to custom fields, which is worse to keep backwards-compatibility because sometimes you need to change (or just want to change) how you store data, handle it, etc. If you change how you store data, for example, it could make sense the change the validators and then all the previous migrations that relied on the validator will not work anymore (unless you change the migration code, and that could be many files, and also changing migration code should not be needed).

So, this idea of directly importing from the codebase binds data to code. Shouldn't we strive to keep them separate? Maybe we should stick to raw SQL migrations? Is this problem possible to be solved without using raw SQL migrations? Is binding data to code a price worth paying to keep SQL at a distance?

答: This is addressed in the Migrations overview of the Django documentation. You can remove obsolete references after squashing migrations.</p>

Title: Django Migrations: Binds data to code?


答:
Why is it beneficial to use the strategy pattern if you can just write your code in if/then cases?

The Strategy Pattern lets you separate your algorithms (the details) from you business logic (high level policy).  These two things are not only confusing to read when mixed, but also have very different reasons to change.

There is also a major teamwork scalability factor here. Imagine a large programming team where many people are working on this accounting package.  If the tax algorithms are all in the TaxPayer class or module, then merge conflicts become likely.  Merge conflicts are time-consuming and error-prone to resolve.  This time drain saps productivity from the team and the errors introduced by bad merges damage credibility with customers.

Also, what does it mean for the algorithm to change at runtime?

An algorithm that changes at runtime is one whose behavior is determined by configuration or context.  An if/then approach in place does not effectively enable this as it involves reloading existing actively used classes.  With the Strategy Pattern the strategy objects implementing each algorithm could be constructed on use.  As a result changes to these algorithms (bug fixes or enhancements) could be made and reloaded at runtime.  This approach could be used to enable continuous availability and zero-downtime releases.

Title: Advantages of Strategy Pattern


答:
The broader the scope the longer the name.  This is done because the further you get from a definition the less clear its intent becomes.

An example of the absurd narrow end is a method-level constant (or variable).  It could be a single character, although I tend to stick with the type name as a minimim personally.

On the far end you have a global constant.  It should be very detailed in its name.

Names of constants (and variables in general) should always be about what they are (noun or adjective-noun phrases) rather than what they do.


答:
Actors interact with use cases. So your user actor interacts with different tasks they can perform with the simulator (configure, run, generate report, export data, etc.).

The use case diagram should show how other actors (if they exist) interact with the use cases the user actor interacts with.

Title: Question regarding actors in a Use Case diagram

Body:
OK, so I have this homework question whereby we are given a rather complex system description and need to create several UML diagrams that describe the system being described.

I'm having an issue with designing the Use-Case diagram for it.
Here is a very simplified description of the system:

The system being described is one that simulates jobs being performed by a multi processor machine. The simulation system is comprised of several components including:

Manager

Simulator

Scheduler

Parser

etc.

A user opens the simulation system by defining a configuration file (including job descriptions) into the manager, and hitting "run". When the simulation finishes, a statistics file is generated (and can be presented to the user)

The problem I have with the Use-Case diagram is what do I put as the Actors?
As far as I'm aware, an Actor should be a human user, an external piece of hardware, or an external piece of software.

Going with this logic, the use case for the above system is overly simple, it's just one Actor labeled "user" which interacts with one action which will be named "simulation".

But I feel as if maybe I'm supposed to put all the components of the system as actors.

Anyone have any ideas?
Thank you!


答:
Since this is a homework assignment, the best thing that you can do is ask your instructor for input. The person grading you has expectations, just like in the workplace your coworkers, managers, and customers have expectations. The expectations need to be defined by the person receiving the work.

That said, I can provide my take on how to structure a use case diagram for this particular situation.

The first thing that I would do is to identify the external-facing operations that your simulator system exposes. The text of your question identifies a few - load a configuration file, run the simulation, view statistics. Are there others? Can you pause simulations? Or adjust configuration in the middle of a simulation? Or export the statistics to various formats? Anything else that your system exposes to a user or outside system should be given a use case "bubble".

Next, I would define relationships between the use cases. The three relationships that appear on a use case diagram are extends, includes, and inherits. The extend relationship allows one use case to continue beyond the base use case. If Use Case B extends Use Case A, then all of the steps in Use Case A are completed prior to executing Use Case B. The includes relationship captures dependencies and allows behavior from one use case to be included in another. If Use Case B includes Use Case A, then the operation of Use Case A is available as part of Use Case B but does not state where during the execution of Use Case B it is used or if it is required or not. Finally, inheritance allows for a use case that inherits some of the operations of a different use case but changes or adds additional steps.

Third, I'd identify all of the actors on the use case. These would be human users or external systems that interact with the system under design. It may be wise to consider roles. Humans of different roles may have different access to functions.

Finally, I'd identify relationships between actors. One actor may be a superset of another actor, and this can be indicated on the diagram, making it cleaner and easier to read.

Scott Ambler has a good article on the use of use case diagrams and an article on reuse in use case diagrams. I find much of his work helpful when considering modeling and documenting software systems.

After all of that, I would have to recommend once again going to the person who will be using your use case diagram - in this case, the instructor grading you - to find out exactly what they need from you. In UML Distilled, Martin Fowler almost discourages the use of Use Case Diagrams in favor of other tabular or textual representations of use cases. Diagrams don't have as much value as other more detailed descriptions. Use case diagrams aren't things that you tend to see or use in industry, but you should be aware of their existence and how to read and create them should you be asked to do so.


问:
Solutions for iOS collaborative sync (iCloud CoreData, CouchDB)?
I'm developing an iOS app where one of the features will be allowing users to share and collaborate on data (e.g. lists). From everything I've read and based on the way that iCloud CoreData sync works I assume that it would not be a good fit for the following reasons, but I wanted to make sure I wasn't missing anything, as I'd prefer not to use a 3rd party syncing solution if at all possible:

iCloud sync of any kind (CoreData, Document or Key / Value pairs) can only ever be between devices that use the same iCloud account, so it's designed for a single user syncing data over multiple devices. Any kind of collaborative sync (several people editing the same document / list) simultaneously would be limited to everyone have the same iCloud account. Cases of people sharing the same iCloud account is usually limited to, for example, husband and wife or similar close relationships for a small number of people.

iCloud Core Data sync is for ensuring that each sync'd device has the same data. It doesn't seem to allow syncing just a subset of the data, so scenarios in which each user has their own documents and is only sharing / collaborating on a subset of them are not supported.

And I'm not even mentioning the well document problems with iCloud CoreData syncing which may or may not have been resolved with iOS 7.

Given the above, it would seem that CouchDB (with TouchDB) would be a better option, as it seems to support everything I need. What other options are there that people can recommend?

UPDATE: Since posting this I've done more research and discovered that CouchDB as it stands would not be a good solution. Its filtered replication feature seems like it was made for syncing only a subset of data (e.g. data for one user) to a mobile device from a central server database that has all users' data on it. However, it's not a workable solution for both performance and security reasons. The guys at Couchbase are working on solutions for this, but they are all in early alpha stages.

For a solution that doesn't involve creating your own backend, the options seem to boil down to Simperium, Parse or something like Windows Azure mobile services. Of these, the only one that supports real time push sync (no need to refresh or poll for new data) seems to be Simperium. The one downside to Simperium is that it doesn't support binary data (eg images).

答:
You probably don't really want or need to share all of the internal app data into the cloud. I recommend you take a look at CloudKit. You can save your binary assets that need to be shared between all users by placing the information into the public CloudKit database.

For getting started with CloudKit check out this full tutorial. Now the basics are covered here but how you use them most efficiently is not. You may want to consider only downloading assets when they are needed. To accomplish this it might be useful to create a table referencing the share status for owners of other records along with users who have access to those records (including an option for sharing to public ~ other app users).

You could then simply post a local alert to a user when new data is available and allow them to control the download (using a fetched count of new share records available to a user and then using a local notification). Or you might want to process downloads only in the background mode. This all depends on your use case, but you will want to think about when to make the action happen as that might cause unnecessary issues with user bandwidth. Maybe only download over wifi, etc...


问:
Can "REST without PUT" support optimistic locking using ETags?
Rest without PUT models immutable, append-only (event-sourced) state changes by favouring POST-ing new reified change resources over PUT-ing updates to original. Example: making and then changing a coffee order...

Traditional REST:

POST /order {type: latte} → 201 Created /order/1234

PUT /order/1234 {type: mocha} → 200 OK

REST without PUT:

POST /order {type: latte} → 201 Created /order/1234

POST /order/1234/change-req {type: mocha} → 201 Created /order/1234/change-req/5678

Question: Can this work with optimistic locking using Etags and If-Match?

Traditional REST:

POST /order {type: latte} → 201 Created /order/1234, ETag: "1111"

PUT /order/1234 {status: delivered} If-Match "1111" → 200 OK ETag "2222" (barista is quick!)

PUT /order/1234 {type: mocha} If-Match "1111" → 412 Precondition failed

REST without PUT:

POST /order {type: latte} → 201 Created /order/1234, ETag: "1111"

POST /order/1234/deliver-req {} If-Match "1111" → 201 Created /order/1234/deliver-req/9012

POST /order/1234/change-req {type: mocha} If-Match "1111" → 412 Precondition failed

Does it make sense to allow the Etags sent and matched to refer to the original order resource, and not to the state of the reified changes resources (deliver-req, change-req) themselves?

答:
Update: Can etags + If-Match work? Yes, I'm sure it can be made to work. Your client will have to interpret the 412 error as an optimistic concurrency failure. As far as using it with POST, the spec does not restrict which methods it is allowed on.

The If-Match request-header field is used with a method to make it conditional.

I would also return 412 (with a different message) if there is no entity (and therefore no etag) found in the database. In other words, they are requesting modification for an entity that was never created.

The question remains as to whether you should use If-Match for optimistic concurrency. The main problem with it is that semantically, it allows the client to specify whether or not the resource should be updated. It is very possible that the business will want some optimistic concurrency failures to be allowed to continue anyway. F.ex. if CancelOrder is received, regardless of version mismatch, it should be processed. (It could be that the order is already shipped and cancellation fails, but at least we can respond with that information instead of just a version mismatch error!) This is not a decision you usually want on the client. However, you could subvert the spec and just use If-Match to send your version (e-tag), and ultimately let the business rules decide whether the operation should continue if the tags don't match and return the 412 otherwise.

Should you send the etag to the reified URI? Yes. In fact as part of modeling what is essentially messaging over HTTP, there should be no POST URI for an "original order resource". What you are really doing with that order URI is sending the "create order" command message. If you changed its name to fit that, then that would make it much more clear that POSTing to an Order resource doesn't make sense. In this type of API the POST URIs are message types, not resources.

By the way, I wholeheartedly disagree with the linked article at making these nouns instead of verbs. REST tries to represent operations (actions) as HTTP verbs, which fits fine for the 4 CRUD operations, but is far too limited for domain operations. Realizing this, the article's author moves the domain operation to be part of the URI, but tries to retain the REST principle of noun URIs (I assume) to stick to the REST spec in letter, even though it is not followed in spirit. Sometimes you just have to acknowledge that something doesn't fit and don't force it. Verbs definitionally include actions, and actions more closely represent business operations. Therefore, use POST /create-customer instead of POST /create-customer-req. Do you really want to add a superfluous -req on the end of every URI?

The read side

It makes complete sense to have a GET URI for Order. Actually, it makes sense to have multiple GET URIs for Order, one for each different perspective (view) on the order. F.ex. a customer is likely to want different information when looking at their orders than the sales manager. (This may actually lead to different bounded contexts, but that is a different discussion.)

Update

I see your edit changed the URIs to the form POST order/123/action instead of including the ID in the JSON body. Either way, this does not make sense in the context of REST. The URI is supposed to represent a resource, but here is a message type. The fact that you are communicating an ID via URI doesn't make it a resource. The same way that changing an action to a noun form doesn't make it a resource. Sticking to REST naming conventions without actually implementing a uniform interface is in no way helpful. The idea of following REST is to use HTTP in a standard and consistent way so that clients have a reasonable expectation for how it works.

In the case of a CRUD resource conforming to REST, if you gave the client a URI and object shape, it would already know how to perform all operations. In your case, the clients don't have knowledge of your custom operations until you tell them (via hypermedia perhaps, or hard-coding in the client).

Let me re-emphasize: It's okay that your use case doesn't fit in the REST box! It's okay to use HTTP in a different way that makes sense for your system!


问:
Sync SQLite using only HTTP
I currently have a SQLite DB on my server that is needed by an android app I am currently developing. I download the DB to the android device using HTTP each time the contents are changed.

Does anyone have any suggestions as to how to do this more efficient. ie. when the database gets large I don't want the android user to have to download the whole database again just because one record was added.

答:
Is it required to use HTTP? Can you use a TCP connection?

If so, you can use the litereplica library.

Make the server db file be the primary (writable) db and the mobile have the secondary (read-only) db.

If the mobile app needs to write to the db, it can use another file for its own content. You can even use another pair in the opposite direction, what serve as a backup and the server can even read it.

And the db updates are incremental. This means that only the changed pages are transferred instead of the whole database.

OwnerDisplayName: Keagan Ladds

Title: Sync SQLite using only HTTP


答:
First, identify the subject for which you want to describe use cases. From your description, I assume you need to draw use cases for the simulation system as a whole (and not for each of the components 'manager', 'simulator' etc.). In that case, the user is the only actor.

A use case must yield a result that is of value to the actor. So 'Create configuration' would not be a good use case. It seems to me that the only valuable result is the statistics file. In my view, there is only one use case, "Perform simulation", which covers all steps, including creating the configuration, running the simulation and viewing the statistics.

To summarize, I think you are completely right: one actor, one use case.


答:
Your application will always have an initial stage, but will not necessarily always have a loan application approver stage or, more likely, it may not always remain the initial stage.

For this reason, I would name the constant to reflect what it represents (the name of the initial stage) rather than on what it currently means


问:
Passing fields (instance variables) by arguments (parameters) inside an object - does it make sense?
I believe this is language agnostic question - if it's not then please correct me.

Let's say I have a class (code snippet is a kind of 'pseudo code')

```<code>class Car:
  private steering_wheel
  private engine
  public Car(steering_wheel, engine):
    this.steering_wheel = steering_wheel
    this.engine = engine

  public void service():
     clean_steering_wheel()
     repair_engine()

  private void clean_steering_wheel():
    this.steering_wheel.do_stuff()

  private void repair_engine():
    this.engine.do_stuff()
</code>```

which works well! But I could also change private methods a bit and let them use fields (i.e steering_wheel and engine) via arguments, not directly

```<code>   class Car:
  private steering_wheel
  private engine
  public Car(steering_wheel, engine):
    this.steering_wheel = steering_wheel
    this.engine = engine

  public void service():
     clean_steering_wheel(this.steering_wheel)
     repair_engine(this.engine)

  private void clean_steering_wheel(steering_wheel):
    steering_wheel.do_stuff()

  private void repair_engine(engine):
    engine.do_stuff()
</code>```

Let's assume that all parameters(arguments) are passed by reference.

What are the advantages and disadvantages of these solutions? Which is considered as better practice? Which one do you prefer?

答:
Sounds very much a judgement call to your specific situation, but a couple considerations come to mind.  If the methods are private, and you don't have any reason to pass the parameter, I would probably avoid it if for no reason other than it being less complex.  You could also argue that there is a performance reason to avoid it, as there is no reason to pass additional parameters on the stack if they aren't needed.

One time I do find that I do pass a member as a parameter is with protected members.   Let's say a child class does something like add a second steering wheel that also needs to be cleaned.  In that case, it could (presumably) re-use the clean_steering_wheel method from the base class and pass a different steering wheel member.


问:
Configuration Files For Web Applications
I am building a MVC application. This app has a core which is where all interfaces, abstract classes and operation logic are situated. It also contains a directory called module, this application is based in module. For example there is a module User which contains controllers, models and views (it does stuff related to user operations).

Am currently using json string for the configuration of my application. I have a route class that cheeks which controller belong to what model, it check is the module is active or if the controller is active and many other stuff.

So my question is? Apart from json and xml is there any other configuration formate out there?

答: Two other formats that spring to mind are YAML and INI. YAML is used by Google App Engine to control its routing, so you might want to look at that first. Lots of languages also have their own configuration formats, such as Perl's Config::Simple and Java's Properties.</p>


问:
How can a method handle validation and entity creation without output parameters?
I have 3 simple classes.  A Reference, a Parent, and a Child.  The Child knows the Reference and Parent instances it's associated with.  Here they are, initialization and other data/methods omitted:

```<code>class Reference
{
    public int ID { get; private set; }
}

class Parent
{
    public int ID { get; private set; }
}

class Child
{
    public int ID { get; private set; }
    public Reference Reference {get; private set; }
    public Parent Parent {get; private set; }
}
</code>```

Here is a class that maintains collections of them:

```<code>class SetOfThings
{
    private List<Reference> _refs;
    private List<Parent> _parents;
    private List<Child> _children;

    // ...
    // initialization, etc
    // ...
}
</code>```

It enforces constraints like

cannot add a Child unless its Parent and Reference already exists

cannot add a Child if another Child with the same Parent and Reference already exists

and so on.  Currently, the AddChild method enforces the constraints with ArgumentExceptions and returns the new Child with a new unique ID:

```<code>class SetOfThings  // continued
{
    public AddChild(Reference ref, Parent parent)
    {
        if (!_refs.Contains(ref))
            throw new ArgumentException($"{ref} not yet known");
        if (_children.Any(c => c.Parent == parent && c.Reference == ref))
            throw new ArgumentException($"{ref} and {parent} already referenced by a child");

        int newID = MakeNewChildID();
        var newChild = new Child(newID, ref, parent);

        _children.Add(newChild);
        return newChild;
    }
}
</code>```

All of my AddChild calls look like this:

```<code>Child newChild;
try
{
    newChild = AddChild(someReference, someParent);
}
catch (ArgumentException ex)
{
    UI.Alert(ex.Message);
    return;
}

// ...
// Trigger state change, update UI with new child, etc.
// ...
</code>```

However, this feels like an abuse of the exception mechanism.  It isn't really "exceptional" behavior when those ArgumentExceptions are thrown - it's just normal control flow.  But I don't know how to avoid this:

I could return a bool that indicates success/failure and use an output parameter to "return" the new child,

```<code>bool AddChild(Reference r, Parent p, out Child c)
</code>```

but I don't get any indication of why a failure occurred, and output parameters sacrifice readability.

I could return null to indicate a failure.  The method signature wouldn't change, but I still don't know why failures occur.  Moreover, a null reference probably shouldn't be expected behavior any more than exceptions should be.

I could return a custom Notification object (or list thereof) that indicates failures with severity and message strings.

```<code>Notification AddChild(Reference r, Parent p, out Child c)
</code>```

Lots of information, hooray!  But I still need an output parameter. D'oh.

I could return Notification, but construct the Child before passing it into AddChild, and expose the Child.ID property as a public settable so the SetOfThings can change it appropriately.

```<code>var newChild = new Child(someRef, someParent);
var notification = set.AddChild(newChild);
if (/* notification is failure */)
    // change state, discard newChild, display message
else
    // change state, use newChild, etc.
</code>```

But the public settable Child.ID property to make this work is confusing at best, and dangerous at worst.

Am I missing some obvious or common alternative?  I'm not breaking new ground here, but I can't come up with a clear, readable way for a collection class to have creation and validation in the same method.

答:
The alternative that immediately comes to my mind is to simply use more than one method.

```<code>Child newChild(someReference, someParent);
if(HasChild(newChild)) {
    // UI.Alert and whatnot
} else {
    AddChild(someReference, someParent);
}
</code>```

Now you aren't using exceptions for control flow, and if the AddChild method throws, that means something actually has gone quite horribly wrong.

Notice that the example I just gave does not check that someReference and someParent already exist in SetOfThings. That's deliberate. Maybe I already know for certain that they exist and it's only duplicate children I'm worried about. Maybe in some other code snippet it'll be the other way around and over there you'll write this instead:

```<code>if(!HasReference(someReference) || !HasParent(someParent)) {
    // UI.Alert and whatnot
} else {
    Child newChild = AddChild(someReference, someParent);
}
</code>```

In other words, having dedicated methods (as opposed to exceptions) for your validation checks lets you be much more explicit about what checks you believe are necessary. If an exception gets thrown from either of the above snippets, then you know that you've made a mistake somewhere.

Body:
The alternative that immediately comes to my mind is to simply use more than one method.

Child newChild(someReference, someParent);
if(HasChild(newChild)) {
    // UI.Alert and whatnot
} else {
    AddChild(someReference, someParent);
}

Now you aren't using exceptions for control flow, and if the AddChild method throws, that means something actually has gone quite horribly wrong.

Notice that the example I just gave does not check that someReference and someParent already exist in SetOfThings. That's deliberate. Maybe I already know for certain that they exist and it's only duplicate children I'm worried about. Maybe in some other code snippet it'll be the other way around and over there you'll write this instead:

if(!HasReference(someReference) || !HasParent(someParent)) {
    // UI.Alert and whatnot
} else {
    Child newChild = AddChild(someReference, someParent);
}

In other words, having dedicated methods (as opposed to exceptions) for your validation checks lets you be much more explicit about what checks you believe are necessary. If an exception gets thrown from either of the above snippets, then you know that you've made a mistake somewhere.


问:
Should one check for every little error in C?
As a good programmer one should write robust codes that will handle every single outcome of his program. However, almost all functions from the C library will return 0 or -1 or NULL when there's an error.

It's sometimes obvious that error checking is needed, for example when you try to open a file. But I often ignore error checking in functions such as printf or even malloc because I don't feel necessary.

```<code>if(fprintf(stderr, "%s", errMsg) < 0){
    perror("An error occurred while displaying the previous error.");
    exit(1);
}
</code>```

Is it a good practice to just ignore certain errors, or is there a better way to handle all the errors?

答:
However, almost all functions from the C library will return 0 or -1 or NULL when there's an error.

Yes, but you know which function you called, don't you?

You actually have a lot of information that you could put in an error message.  You know which function was called, the name of the function that called it, what parameters were passed, and the return value of the function.  That's plenty of information for a very informative error message.

You don't have to do this for every function call.  But the first time you see the error message "An error occurred while displaying the previous error," when what you really needed was useful information, will be the last time you ever see that error message there, because you're immediately going to change the error message to something informative that will help you troubleshoot the problem.


答:
In general, code should deal with exceptional conditions wherever it is appropriate. Yes, this is a vague statement.

In higher level languages with software exception handling this is often stated as "catch the exception in the method where you can actually do something about it." If a file error occurred, maybe you let it bubble up the stack to the UI code that can actually tell the user "your file failed to save to disk." The exception mechanism effectively swallows up "every little error" and implicitly handles it at the appropriate place.

In C, you do not have that luxury. There are a few ways to handle errors, some of which are language/library features, some of which are coding practices.

Is it a good practice to just ignore certain errors, or is there a
  better way to handle all the errors?

Ignore certain errors? Maybe. For example, it is reasonable to assume that writing to standard output will not fail. If it does fail, how would you tell the user, anyway? Yes, it is a good idea to ignore certain errors, or code defensively to prevent them. For example, check for zero before dividing.

There are ways to handle all, or at least most, errors:

You can use jumps, similar to gotos, for error handling. While a contentious issue among software professionals, there are valid uses for them especially in embedded and performance-critical code (e.g. Linux kernel).

Cascading ifs:

if (!<something>) {
  printf("oh no 1!");
  return;
}
if (!<something else>) {
  printf("oh no 2!");
  return;
}
```

Test the first condition, e.g. opening or creating a file, then assume subsequent operations succeed.

Robust code is good, and one should check for and handle errors. Which method is best for your code depends on what the code does, how critical a failure is, etc. and only you can truly answer that. However, these methods are battle-tested and used in various open source projects where you can take a look to see how real code checks for errors.

Title: Should one check for every little error in C?

Body:
As a good programmer one should write robust codes that will handle every single outcome of his program. However, almost all functions from the C library will return 0 or -1 or NULL when there's an error.

It's sometimes obvious that error checking is needed, for example when you try to open a file. But I often ignore error checking in functions such as printf or even malloc because I don't feel necessary.

```<code>if(fprintf(stderr, "%s", errMsg) < 0){
    perror("An error occurred while displaying the previous error.");
    exit(1);
}
</code>```

Is it a good practice to just ignore certain errors, or is there a better way to handle all the errors?

Body:
In general, code should deal with exceptional conditions wherever it is appropriate. Yes, this is a vague statement.

In higher level languages with software exception handling this is often stated as "catch the exception in the method where you can actually do something about it." If a file error occurred, maybe you let it bubble up the stack to the UI code that can actually tell the user "your file failed to save to disk." The exception mechanism effectively swallows up "every little error" and implicitly handles it at the appropriate place.

In C, you do not have that luxury. There are a few ways to handle errors, some of which are language/library features, some of which are coding practices.

Is it a good practice to just ignore certain errors, or is there a
  better way to handle all the errors?

Ignore certain errors? Maybe. For example, it is reasonable to assume that writing to standard output will not fail. If it does fail, how would you tell the user, anyway? Yes, it is a good idea to ignore certain errors, or code defensively to prevent them. For example, check for zero before dividing.

There are ways to handle all, or at least most, errors:

You can use jumps, similar to gotos, for error handling. While a contentious issue among software professionals, there are valid uses for them especially in embedded and performance-critical code (e.g. Linux kernel).

Cascading ifs:

if (!<something>) {
  printf("oh no 1!");
  return;
}
if (!<something else>) {
  printf("oh no 2!");
  return;
}

Test the first condition, e.g. opening or creating a file, then assume subsequent operations succeed.

Robust code is good, and one should check for and handle errors. Which method is best for your code depends on what the code does, how critical a failure is, etc. and only you can truly answer that. However, these methods are battle-tested and used in various open source projects where you can take a look to see how real code checks for errors.


答:
TLDR; you should almost never ignore errors.

The C language lacks a good error handling feature leaving for each library developer to implement its own solutions. More modern languages have exceptions built in which makes this particular problem a lot easier to handle.

But when you're are stuck with C you have no such perks. Unfortunately you'll simply have to pay the price every time you're calling a function which there is a remote possibility of failure. Or else you will suffer much worse consequences such as overwriting data in memory unintentionally. So as a general rule you have to check for errors always.

If you don't check for the return of fprintf you're very likely leaving a bug behind that will in the best case not do what the user expects and worse case explode the entire thing during flight. There's no excuse to undermine yourself that way.

However as a C developer it's also your job to make the code easy to maintain. So sometimes you can safely ignore errors for the sake of clarity if (and only if) they do not pose any threat to the overall behavior of the application..

It's the same problem as doing this:

```<code>try
{
    run();
} catch (Exception) {
    // comments expected here!!!
}
</code>```

If you see that with no good comments inside the empty catch block this is certainly an issue. There's no reason to think a call to malloc() will execute successfully 100% of the time.

Body:
TLDR; you should almost never ignore errors.

The C language lacks a good error handling feature leaving for each library developer to implement its own solutions. More modern languages have exceptions built in which makes this particular problem a lot easier to handle.

But when you're are stuck with C you have no such perks. Unfortunately you'll simply have to pay the price every time you're calling a function which there is a remote possibility of failure. Or else you will suffer much worse consequences such as overwriting data in memory unintentionally. So as a general rule you have to check for errors always.

If you don't check for the return of fprintf you're very likely leaving a bug behind that will in the best case not do what the user expects and worse case explode the entire thing during flight. There's no excuse to undermine yourself that way.

However as a C developer it's also your job to make the code easy to maintain. So sometimes you can safely ignore errors for the sake of clarity if (and only if) they do not pose any threat to the overall behavior of the application..

It's the same problem as doing this:

try
{
    run();
} catch (Exception) {
    // comments expected here!!!
}

If you see that with no good comments inside the empty catch block this is certainly an issue. There's no reason to think a call to malloc() will execute successfully 100% of the time.


问:
Enclosing main invocation of a function in an if
As a part of my school CS class, I am reading Python Programming by John Zelle.  In the book, Zelle talks about surrounding the invocation of a main method with

```<code>if <condition>:
    main()
</code>```

where the condition is something like __name__ == '__main__'.  My computer science teacher said that the necessity of this loop depends on if the program is importable and run-directly.  I know that because there are 2 variables, there can only be four combinations of importable and    run-directly.

I know from the book and my CS teacher that

If a program is importable and is run directly, then main must be conditional.

However, I do not know the cases, which is what I am trying to figure out:

If not importable and not run-directly

If importable and not run-directly

If not importable and run-directly

I think, but am not sure, that these are the correct answers.

If not importable and not run-directly, then it must be in a conditional

If importable and not run-directly, then it doesn't have to be in a conditional.

If not importable and run-directly, then it doesn't have to be in a conditional.

"Are the statements above correct?" is what I am trying to figure out.

I have tried finding this information in the book, but is unfortunately unavailable.

答:
You're very close, but are missing one aspect.

If a program is importable and is run directly, then main must be conditional.

If not importable and not run-directly, then main is irrelevant. Actually, the entire contents of the file are irrelevant.

If importable and not run-directly, then main should not exist.

If not importable and run-directly, then main does not have to be in a conditional. It's still a good idea, as it'll help avoid accidentally omitting it were needed, and it causes no harm.