问:
How to manage a winforms application installed in many PCs connected to a single sql database?
I have a winforms application that connects to a single sql server 2012 database and is executed in many PCs of a company.

I'm having several problems with some transactions inside the application, deadlocks and timeouts so the refactor idea comes to my head.

Actually the app is using DbConnection object (the app starts with Framework 2.0 and recently was updated to Framework 3.5 but the data access layer was not changed) to perform the sql calls to the database and in the Program.cs the connection is opened and until the user doesn't close the app the connection maintains opened.

What are my options to refactor this app?

Entity Framework? => With this I must to say that the SQL database
has not Foreign Keys

Refactor the Data Access Layer to use a more efficient connection? Maybe using TransactionScope?

Is the always connected app efficient?

答:
Migrating to a different technology will not necessarily prevent deadlocks and timeouts and other "application-level" problems. You'll just be rearranging the deckchairs.

There are many cases where this client-server model works, it is efficient generally - as long as your clients don;t do things like read a big query and keep the lock on the DB resultset (as some "edit results" controls can do).

The trick is to read what you need, work with it and update what you changed afterwards, allowing others to play nicely with the same DB resource. If you moved to, say a 3-tier architecture where the DB connection is held by a central service, then you'll have to adopt this approach anyway.

Apart from that, I can't really help- it depends on your program its usage and the bad things it does. A 3-tier approach is a good thing though, and if you design it so it is not tied to a specific winforms client, you'll be able to reuse the central server with future clients (eg a web one)


问:
Theoretically bug-free programs
I have read lot of articles which state that code can't be bug-free, and they are talking about these theorems:

Halting problem

Gödel's incompleteness theorem

Rice's theorem

Actually Rice's theorem looks like an implication of the halting problem
and the halting problem is in close relationship with Gödel's incompleteness theorem.

Does this imply that every program will have at least one unintended behavior?
Or does it mean that it's not possible to write code to verify it?
What about recursive checking? Let's assume that I have two programs. Both of them have bugs, but they don't share the same bug. What will happen if I run them concurrently?

And of course most of discussions talked about Turing machines. What about linear-bounded automation (real computers)?

答:
Running two or more variants of the same program is a well-known fault tolerance technique called N-variant (or N-version) programming. It is an acknowledgement of the presence of bugs in software.

Usually these variants are coded by different development teams, using different compilers, and sometimes are executed on different CPUs with different OSes. Outcomes are voted before being output to the user. Boeing and Airbus love this kind of architecture.

Two weak links remain, leading to common mode bugs:

There is only one specification.

the voting system is either unique or complex.

ContentLicense: CC BY-SA 3.0

Title: Theoretically bug-free programs


问:
how can we have a person to allot and track tasks in agile development
I understand that Agile team should be self organized and self driven,

but is there a provision that I can have someone who will allot tasks to developers and ensure that all user stories will be completed on time??

For example if there are two persons in an agile team who are not self motivated to take up tasks and they will work only when task is assigned to them with a deadline, how can we deal this in Agile?

The problem I face is that no one is fixing the deadlines for the tasks and the team is under delivering for the last two sprints.
It will be better if we can have someone who can fix deadlines. IS there a provision for this in Agile

答:
There should be someone who educates and helps the programmers on the team to understand and adhere to the team's agile practices and then holds them accountable for it.

This is the only way to have a true self sustaining, self-managing agile team.

Don't address the symptom, address the problem instead.


问:
What is the responsibility or benefit of a Tokenizer?
Suppose I had a grammar like:

```<code>object
    { members }
members
    pair
pair
    string : value
value
    number
    string
string
    " chars "
chars
    char
    char chars
number
    digit
    digit number
</code>```

I could parse the following example: { "one" : 1234 }

As far as I understand, I should have the tokens object, members, pair, value, string and chars.

Tokenizing the example should produce

```<code>object
    ->members
        ->pair
            ->"one"
            ->"1234"
</code>```

Parsing the tokens should produce

```<code>object
    ->pair
        ->"one"
        ->1234
</code>```

It seems to me like the tokenizer is either useless or I don't fully understand what a it should do.

What is the responsibility of a tokenizer?
What is the benefit of a tokenizer over parsing the original string?

答:
You bring up an excellent point.  I'm going to disagree with the other answers here, and say that the main goal of a tokenizer is to get better performance during parsing -- i.e., tokenizers are an optimization: an implementation detail of parsing, but not a fundamental one.  A large part of the time spent parsing is breaking the input string up into pieces.  By optimizing this, the parser's performance can be greatly increased.

So that's a pretty vague definition I just gave, and that's why it's hard to precisely define what a tokenizer should do.

Many languages are defined using two separate grammars: one for tokens, and one for hierarchical syntax elements.  You could argue that the purpose of a tokenizer is to implement the token grammar, but this misses the point: splitting a grammar into token and hierarchical grammars is arbitrary and unnecessary from the point of view of expressiveness (although, again, useful as a performance optimization).

It's perfectly reasonable and practical to implement parsers without separate tokenizers, although it's likely the performance will be worse.

It is important to note that there are drawbacks to using a separate tokenizer.  One is that the token grammar can become restricted (example, another example).
In my personal experience, avoiding separate tokenization reduces the overall complexity (LOC, interfaces between subsystems, etc.) of a parser.


问:
What is the most efficient method in converting AutoLISP legacy code to C#?
I am engaged in a project that works mainly in AutoCAD to design and manufacture prefabricated building components such as roofing trusses.  One of our goals is to redesign a program that was written in LISP that functions in designing roofing trusses.  We are to rewrite the LISP code in C# and incrementally implement it into the current libraries that they have set up.

My problem is that I have been tasked with building a rudimentary LISP to C# converter.  After some research (as Google results quickly show that such a thing does not readily exist on hand), I have come to the question of which way of converting this legacy code would be more efficient.  Would it be better to take chunks of the LISP code to analyze and rewrite in C#, or should I continue on with developing a rudimentary converter for the AutoLISP code?

答:
Hopefully the problem domain that you just described is relatively small.  That is, the code you are converting is constrained to a small handful of specific AutoLISP functions, and you don't have to represent the entirety of AutoLISP semantics in C#.

If that's the case, the first thing I would do is find some AutoLISP code that's fairly representative of the code that you want to convert, and convert it by hand.  Ideally, you'll find a pattern that allows you to perform a simple transliteration; that is, code in AutoLISP that maps directly to some functions that you write in C#.

It is a good idea to perform the manual conversion at least once.  It will give you better insight into how the translation process works.  What you are attempting is not at all the same thing as, say, a VB.NET to C# converter, since that kind of converter is mapping very similar semantics to what amounts to syntax variations.

In other words, converting between two languages that are so different is normally done by hand.  When it is done in an automated fashion, it is usually done by writing some functions in the target language that mimic the functions in the source language, and then stitching those functions together.


问:
How to employ amatuer knowledge of software architecture and design in an agile manner?
I have a problem when designing any application that is either greenfield or a refactored brownfield due to often finding a potential flaw or an uncertainty with the design or architecture that I think up. I waste a lot of time trying to construct a design that I am confident in without a lot of time invested from the beginning. I feel that mistakes early on lead to big issues later in development (especially when refactoring brownfield apps).

I want to minimize this, but am unsure how to do it without an optimal solution or bothering the senior devs or the architect. For example, there is a legacy application that needs to be refactored. I can rewrite it in a new project and reduce the lines of code from 12k to 2-3k. The application's purpose is to generate HTML pages, but is done in a console application in C#. I have not done any web development until now, but I am unsure if ASP.NET MVC would be a good choice, and even if so, if my design or architecture is a good choice.

I understand when working in a team I can receive good and solid advice, but how do I become less reliant on my team's thinking and more on my own without wasting the company's time researching every technological possibility? Does this just come with time and experience? If trial and error is the true and tried way, can architecture and design really be done in an agile way with minimal time wasted?

答:
Agile methods generally start and end with the customer.  The customer may be internal to your company or an external consumer.  Either way you need to understand their requirements and you achieve that through conversation - talk to them, discus your solutions with them, listen to their feedback and suggestions.  This all indicates that getting feedback from your team and the users of your software is, rather than being a waste of their time, an indispensable investment of their time; not only in the quality of the software itself, but also in your value as a team member.  If your managers and senior engineers are half-decent and familiar with Agile paradigms they will appreciate this, otherwise you have an opportunity to improve the company culture.

The architecture of the system will often be heavily dependant on the IT infrastructure in which your software has to operate: ASP .NET is not the best choice if the target webserver is running Linux.  If it's Windows then ASP .NET is great and MVVM (rather than MVC) is a good way to structure your application and assemblies.  This means that the architecture choice shouldn't take more than a few minutes to decide!

The design of your solution is the bit that takes the time and experience, and this is where Agile methodologies really do help, because they effectively allow you to improve your design as you go along.  Do one little bit at a time, make it work, get feedback from the customer and move on to the next bit, refactoring what you did before if you need to.  The 'design' is what you end up with, rather than what you start with.  Providing you test thoroughly at every stage and incorporate your customer feedback as you go along, what you end up with will work and if it works then it is a good design.  "Only just good enough is good enough."  Of course, you do have to consider the 'habitability' and maintainability of the source code.

Test Driven Development is a popular way of managing both the functionality and quality of the code you produce.  It's particularly well suited to Pair Programming, but is easy to use when you have to work alone.  This is certainly a technique that I would strongly recommend, even if you don't use anything else from the Agile portfolio.  When combined with MCDC test coverage you can get a very high confidence level in your software.

Implementing your selected architecture effectively does require trial and error (and research, SO, coffee, cussing, late nights, etc.) but even experienced developers still spend their time going through that.  Good development practices help you get to your goal quicker and the whole point of Agile is that it is a collection of "better ways of developing software".

So, to answer your question: stop worrying and start coding (and have fun!)  :-)


问:
How is the Decorator Pattern actually used in practice?
I understand completely how to implement the Decorator pattern, and I also understand what it's intent is.

The Decorator is used in one of two cases:

As an alternative to subclassing - when there are multiple characteristics that an object can have, one could use inheritance in order to create subclasses for all the possible combinations. For example, three characteristics A, B and C will results in lots of classes: A, B, C, ABC, AB, AC, BC. This results in a 'class explosion'. With Decorator, one would have three decorators A, B and C, and a class D to 'decorate' - and that's it.

As a way to expand an object's functionality during runtime - we can decide which decorators to 'wrap' an object with during runtime, thus 'customizing' an object dynamically.

This was just to show that I do understand what Decorator is (I also totally understand how it's implemented). Now my question:

I'm familiar with theoretical examples of when and how to use Decorator. And as you can see I know what is it's intent. But I'm still not sure when to actually use this in practice, in an actual application. Telling me "it's used as an alternative to subclassing", or "it's used to dynamically add functionality to an object" won't be helpful since I'm familiar with it's intent.

Also telling me "think of a UI window for example. It can have a border, or not, and can be resizable, or not" isn't helpful, I'm already familiar with these theoretical examples.

So what I'm asking for is a concrete real world example of Decorator, in a practical, real-world scenario, with a brief explanation of the benefits of using a Decorator pattern there over other techniques.

Just to clarify, I'm not looking for a list of applications where Decorator was utilized. I'm looking for an example of where and how Decorator was used in a design, why it was a good design choice and the concrete problem that it solved. When I'll see concrete problem solved with Decorator hopefully I'll understand it better.

答:
This was essentially answered by kdgregory in a comment on the question, but ...

A stream is something that can benefit from multiple attributes being added to it, independent of one another.  I want a big dump of application data in a stream.  Great.  I also want it encrypted.  Oh, in this case I also want it zipped.  From this particular client, I want to change the style of line breaks they use as well.

This is an example of the alternative to subclassing your question mentions.  Rather than having LineBreakFixingEncryptingZippingStream (which won't be able to inherit all 3 behaviors and so would lead to code duplication if you already have a LineBreakFixingStream, an EncryptingStream, and a ZippingStream), you can use composition of classes that share a stream interface.

So, LineBreakFixingStream decorates BoringStream, and is implemented by reading from BoringStream and forwarding the reads on to the caller of LineBreakFixingStream, except it changes the line breaks.  Then EncryptingStream, which can decorate any stream, can decorate an instance of LineBreakFixingStream that, in this case, is decorating BoringStream.  Then ZippingStream can decorate that EncryptingStream.  Any combination of your stream classes can be put together pretty easily, even at run time if that is needed (though it isn't in my example - but you can imagine a scenario where clients call an API to put them together as one possible real world scenario that would use run time composition).

Though this is still a little abstract about the purpose, it is a real world scenario.  I've composed streams before in real applications.  Zipping and encrypting come up frequently, and doing a bit of custom formatting of a client data stream is common as well.


答:
First, let's establish what context you wish to discuss this in. The Programmers Q&A at Stack Exchange suggests that you are most likely interested in the real world existence of tools / languages rather than theoretical results and Computer Science theorems.

I have read lot of articles which state that code can't be bug-free

I hope not, because such a statement is incorrect. Though it is commonly accepted that most large-scale applications are not bug-free to the best of my knowledge and experience.

More commonly accepted is that there does not exist (i.e. existence, not possibility) a tool that perfectly determine whether a program written in a Turing-complete programming language is completely bug free.

A non-proof is a intuitive extension of the Halting Problem, combined with the observation data of everyday experience.

There does exist software that can do "proofs of correctness" that verify that a program meets the corresponding formal specifications for the program.

Does this imply that every program will have at least one unintended behavior?

No. Though most applications have been found to have at least one bug or unintended behavior.

Or does it mean that it's not possible to write code to verify it?

No, you can use formal specifications and proof assistants to verify following the specification, but as experience has shown mistakes can still exist in the overall system, such as factors outside the specification - the source code translator & hardware, and most frequently mistakes are made in the specifications themselves.

For more gory details, see Coq is such a tool / language / system.

What about recursive checking?

I don't know. I'm not familiar with it, and I'm not sure if it is a computability problem or a compiler optimization problem.

Title: Theoretically bug-free programs

Body:
I have read lot of articles which state that code can't be bug-free, and they are talking about these theorems:

Halting problem

Gödel's incompleteness theorem

Rice's theorem

Actually Rice's theorem looks like an implication of the halting problem
and the halting problem is in close relationship with Gödel's incompleteness theorem.

Does this imply that every program will have at least one unintended behavior?
Or does it mean that it's not possible to write code to verify it?
What about recursive checking? Let's assume that I have two programs. Both of them have bugs, but they don't share the same bug. What will happen if I run them concurrently?

And of course most of discussions talked about Turing machines. What about linear-bounded automation (real computers)?


问:
When one thread out of four is executing first line in run() then at the same time what will remaining three threads do?
I have four thread instances and they are executing run() code given below:

```<code>public void run (){
   System.out.println("1st line :"+Thread.CurrentThread().getName());
   System.out.println("2nd line :"+Thread.CurrentThread().getName());
   System.out.println("3rd line :"+Thread.CurrentThread().getName());
   System.out.println("4th line :"+Thread.CurrentThread().getName());
   System.out.println("5th line :"+Thread.CurrentThread().getName());
   System.out.println("6th line :"+Thread.CurrentThread().getName());
}
</code>```

When one thread out of four is executing first line then at the same time what will remaining three threads do?

Either they are waiting for executing first line or will they proceed other lines of code?

答:
Every thread will always start from the first line.  No thread will start at the second or third line just because some other thread has executed the first or second; in fact, none of the threads know where any of the other threads are in executing code.

You shouldn't rely on just running multithreaded code to understand what it does, since it is possible for the implementers of the runtime system to change the details of how it works, and the order and length of time each thread runs is unpredictable.

It might be helpful to think of separate threads as separate programs that have shared access to a global memory space.


问:
What language do companies like NASA use to create their applications?
So obviously NASA need programmers to develop applications for them, be it VOIP applications, applications for control of machines and AI, etc. But in what language do they actually use for this?

I am thinking of learning how to program an Arduino, or Engduino as we may be witnessing in my Computer Science classes, but is this at all related to the type of programming NASA do. I understand that NASA will be programming MUCH, MUCH, MUCH more advanced programs than I, but to just get the sense of bringing a inanimate object to life would be an achievement to me.

答:
Armstrong Flight Research Center uses C, C++, C#, Fortran, MATLAB, Python and other languages, based on their specific software requirements.  Some of their software development involves legacy systems.  Some of it involves spacecraft systems, and some of it involves ground control systems.  The control rooms run custom software written in C, C++ and C#, running on Dell computers.

ADA is seldom used anywhere in the military-industrial complex anymore, probably at least in part due to the Ariane 5 accident.  There's a wide variety of software development that takes place at NASA, some of which involves exotic embedded systems.  It never hurts to learn Arduino, and have some fundamental knowledge of electrical signals and digital data systems.

See Also

What is the Mars Curiosity Rover's software built in?

They Write the Right Stuff


问:
How robust are Git commits when the power goes out?
One day I was using Git (I'm still using it) and the electricity went down while I was committing.

When I (actually, the electricity) came back, the git repo was corrupt. I don't remember the exact name, but it was something like "invalid refs" or something like that.

It's easy to guess that the commit was broken in the middle of the operation (I was committing through IntelliJ, which does the index additions automatically). It was also easy to guess that, actually, 'commit' is not as ACID as the DBMS operation with the same name.

Q: Is there a way to ensure repo-altering operations respect atomicity? i.e. if the electricity goes down again, and I'm committing, I'd like my filesystem to not be in a corrupt state.

答:
Git's storage system isn't transactional, so there's definitely a chance that a hardware problem could leave things in an inconsistent state. On the other hand, Git is also really fast so you'd have to be really unlucky to be hit by problems of the “power failure” kind (systematic problems with the disk are something else). The speed comes in part precisely from the fact that it isn't transactional; transactions are really quite expensive since they have to wait for confirmation back from the disk that it has written the data. (Databases do all sorts of things to try to conceal this cost, but ultimately they still pay the price. Some of the competitor DVCSes are transactional, and yes, they're quite a bit slower on the same hardware as git.)

In the worst case — a total catastrophic disk failure (which I've seen happen) — the only way for any DVCS to recover is to use the fact that it is distributed. If you've pushed your changes up until very recently to another system and they've shared them to many different hosts, recovery is just a matter of using one of these other places as an artefact source, a place to pull your branches from (even if just temporarily). Like that you'll pull the history of the interesting branches back in and you'll be able to get working again very quickly; anything that wipes out lots of distributed copies of your repo at once is either a disaster of the kind where you don't worry about programming afterwards (think major meteorite impact) or is outright enemy action. (Try not to make such enemies…) This is in total contrast to non-distributed systems, where losing the central server that hosts everything is a fatal blow.


问:
C++ raw pointers for storage
I'm seeing a lot of people say you should never use raw pointers. What about in the case where you store the raw pointer in a class but how they get populated is from getting the pointer of an object that wasn't dynamically created? I'm curious about if this is bad practice and if so how to make it better. This seems ideal to me as I'm not required to delete anything myself so limited/no chance for a memory leak? The idea of "if you didn't create it you don't delete it".

I can control everything by the scope of the variable I'm passing in right? If it goes out of scope then what it points to won't be valid anymore and it'll throw an exception if I try to access it and I'll be able to catch it and handle it. Curious on thoughts/comments/concerns on this.

```<code>class Object
{
private:
   Object* object;
public:
   void Object() { object = NULL; }
   void AddObject(Object* obj)
   {
      object = obj;
   }

  Object* GetObject()
  {
     return object;
  }
};

int main()
{
   Object obj1;
   Object obj2;

   // obj2 wasn't dynamically created so no need to use a smart pointer
   obj1.AddObject(&obj2);

   return 0;
}
</code>```

答:
By doing this, you have effectively tied these two objects together.  You will now have to ensure that any time you destroy obj1 either explicitly or implicitly, you also destroy obj2.  You've created a data structure where all elements have to be destroyed simultaneously.

If you use something like shared_pointer, you can get the same ease without this problem.  You'll be able to do the same thing, letting scope clean up for you, but you don't have to worry about things going to hell if you later realize it makes sense to create objects in different scopes.

Is this really harder?

```<code>class Object
{
private:
   shared_ptr<Object> object;
public:
   void Object()
   void AddObject(shared_ptr<Object> obj)
   {
      object = obj;
   }

   shared_ptr<Object> GetObject()
   {
      return object;
   }
};

int main()
{
   shared_ptr<Object> obj1(new Object);
   shared_ptr<Object> obj2(new Object);

   obj1.AddObject(&obj2);

   return 0;
}
</code>```

It is essentially the same as your code, but without the requirement to ensure that obj1 and obj2 share scope.

Title: C++ raw pointers for storage

Body:
By doing this, you have effectively tied these two objects together.  You will now have to ensure that any time you destroy obj1 either explicitly or implicitly, you also destroy obj2.  You've created a data structure where all elements have to be destroyed simultaneously.

If you use something like shared_pointer, you can get the same ease without this problem.  You'll be able to do the same thing, letting scope clean up for you, but you don't have to worry about things going to hell if you later realize it makes sense to create objects in different scopes.

Is this really harder?

class Object
{
private:
   shared_ptr<Object> object;
public:
   void Object()
   void AddObject(shared_ptr<Object> obj)
   {
      object = obj;
   }

   shared_ptr<Object> GetObject()
   {
      return object;
   }
};

int main()
{
   shared_ptr<Object> obj1(new Object);
   shared_ptr<Object> obj2(new Object);

   obj1.AddObject(&obj2);

   return 0;
}

It is essentially the same as your code, but without the requirement to ensure that obj1 and obj2 share scope.


答:
There is no problem using raw pointers to, well, point to things—provided that you know the lifetimes of the objects you’re pointing to, and that you have some externally provided guarantee that the objects won’t expire while you’re referring to them.

What raw pointers should not be used for is ownership, because their type conveys nothing about ownership or lifetime semantics.

Most of the time, you can use a unique_ptr to own an object, and references or raw pointers to borrow from it; in the rarer case that you need shared ownership, you can use a shared_ptr with weak_ptr for borrowing.

A bit more on lifetimes. Say you have something like:

```<code>struct Base { virtual ~Base() {} };
struct Derived : Base {};

vector<Base*> bases;
Base* base = new Base();
bases.push_back(base);
delete base;
function(dynamic_cast<Derived&>(*bases[0]));  // won't necessarily throw
</code>```

Dereferencing a pointer whose referent has been deleted is undefined, which is exactly what’s happening here. The memory to which it referred may still contain a valid object, or it may not—you can’t rely on any particular behaviour. Whereas if you had this:

```<code>vector<shared_ptr<Base>> bases;
shared_ptr<Base> base(make_shared<Base>());
bases.push_back(base);
base.reset();
function(dynamic_cast<Derived&>(*v[0]));  // will throw
</code>```

The vector’s shared_ptr retains the object, making it safe to dereference even after base expires in the reset() call. It’s safe to use a raw pointer only when you know that the object will be alive when you dereference the pointer:

```<code>vector<unique_ptr<Base>> bases;
bases.emplace_back(new Base());
bases.emplace_back(new Derived());
{
  vector<Derived*> deriveds;
  for (const auto& base : bases)
    if (const auto derived = dynamic_cast<Derived*>(base.get()))
      deriveds.push_back(derived);
  function(deriveds);  // safe; lifetimes guaranteed by 'bases'
}
</code>```

Title: C++ raw pointers for storage

Body:
I'm seeing a lot of people say you should never use raw pointers. What about in the case where you store the raw pointer in a class but how they get populated is from getting the pointer of an object that wasn't dynamically created? I'm curious about if this is bad practice and if so how to make it better. This seems ideal to me as I'm not required to delete anything myself so limited/no chance for a memory leak? The idea of "if you didn't create it you don't delete it".

I can control everything by the scope of the variable I'm passing in right? If it goes out of scope then what it points to won't be valid anymore and it'll throw an exception if I try to access it and I'll be able to catch it and handle it. Curious on thoughts/comments/concerns on this.

```<code>class Object
{
private:
   Object* object;
public:
   void Object() { object = NULL; }
   void AddObject(Object* obj)
   {
      object = obj;
   }

  Object* GetObject()
  {
     return object;
  }
};

int main()
{
   Object obj1;
   Object obj2;

   // obj2 wasn't dynamically created so no need to use a smart pointer
   obj1.AddObject(&obj2);

   return 0;
}
</code>```

Body:
There is no problem using raw pointers to, well, point to things—provided that you know the lifetimes of the objects you’re pointing to, and that you have some externally provided guarantee that the objects won’t expire while you’re referring to them.

What raw pointers should not be used for is ownership, because their type conveys nothing about ownership or lifetime semantics.

Most of the time, you can use a unique_ptr to own an object, and references or raw pointers to borrow from it; in the rarer case that you need shared ownership, you can use a shared_ptr with weak_ptr for borrowing.

A bit more on lifetimes. Say you have something like:

struct Base { virtual ~Base() {} };
struct Derived : Base {};

vector<Base*> bases;
Base* base = new Base();
bases.push_back(base);
delete base;
function(dynamic_cast<Derived&>(*bases[0]));  // won't necessarily throw

Dereferencing a pointer whose referent has been deleted is undefined, which is exactly what’s happening here. The memory to which it referred may still contain a valid object, or it may not—you can’t rely on any particular behaviour. Whereas if you had this:

vector<shared_ptr<Base>> bases;
shared_ptr<Base> base(make_shared<Base>());
bases.push_back(base);
base.reset();
function(dynamic_cast<Derived&>(*v[0]));  // will throw

The vector’s shared_ptr retains the object, making it safe to dereference even after base expires in the reset() call. It’s safe to use a raw pointer only when you know that the object will be alive when you dereference the pointer:

vector<unique_ptr<Base>> bases;
bases.emplace_back(new Base());
bases.emplace_back(new Derived());
{
  vector<Derived*> deriveds;
  for (const auto& base : bases)
    if (const auto derived = dynamic_cast<Derived*>(base.get()))
      deriveds.push_back(derived);
  function(deriveds);  // safe; lifetimes guaranteed by 'bases'
}


问:
C++ returning references
Looking at making a GUI library for a game engine. I generally avoid pointers if I don't need them and in my below example I find that I don't and it works, but just curious if this design is generally considered good practice or if anyone has comments on it.

```<code>int main()
{
    // all widgets are positioned and sized according to the window size
    Window wndOptions("wndOptions");

    Button cmdExit("cmdExit");

    // the window doesn't own the widgets nor does it create the widgets so it's not responsible for deleting the widgets
    wndOptions.AddWidget(&cmdExit);

    // this is how you can find a control and get it casted also. make your variable a reference
    Button& test = wndOptions.FindWidget<Button>("cmdExit");

    test.SetPosition(50, 25);

    return 0;
}
</code>```

As you can see the idea is that you create your controls (button in this case) and pass a pointer to them to the Window. Then you can find the control by name returning a reference to that control in which you can manipulate the control. It's a bit pointless to use FindWidget() in this example since I have the cmdExit variable, but if I was to pass the window around this would be a way to find and use controls.

The biggest issue I have is that FindWidget() might not find a widget. Right now I throw an exception as not finding a control I would deem as a true exception and not something that should happen much if at all.

Any comments about the usage being done this way?

答:
Looks good so far, although I'm wondering about one thing:

Why would a Window not own the widgets? Seems perfectly reasonable to me, since it already has the capability to store and return them. Who else would own them?

If widgets actually have multiple owners, I'd suggest using std::shared_ptr - it makes the ownership explicit and prevents mistakes like passing pointers to local stack variables etc. In fact, I'd generally use smart pointers as much as possible.

Returning references and throwing exceptions are both good choices in my eyes.

Title: C++ returning references


问:
What would be the most efficient way to reduce the complexity of a set of rotations to a cube?
Despite the long title, my question is fairly simple. Let's say you have a cube in 3D-space and you want to rotate it along the three axes based on the set of instructions provided by a user or elsewhere in the program. How would you simplify, if you will, that set of rotations?

For simplicity's sake, we'll use the notation involved in rotating a Rubik's cube. (And also because that's what I'm programming.. But that's unimportant.) So, X would be a clockwise rotation along the X axis, X' would be a counterclockwise rotation along the X axis, and X2 would be two clockwise rotations rotations along the X axis.

Now, let's say I have a set of instructions X Y X'. That set of instructions did the same thing that the single instruction of Z would have done. Or, in a simpler case, if I had X X' or X2 X2, those rotations cancel out.

My question is, what is the best way - from a programming perspective - to simplify these sets of instructions?

答:
Instead of representing a rotation with "# degrees around the ? axis" you should use a Rotation Matrix.

Rotation matrices have a nice property that if you multiple them you'd get a rotation matrix that has the same effect as applying all the rotations one after another(order is important here!)

Another nice property that you might need later is that if you apply a rotation matrix to a Translation Vector, apply the rotation matrix to an object and then the rotated translation vector to the result, it'll have the same effect as applying the original translation vector to the object and then applying the rotation matrix. This means that if later you'd want to add translations to that set of yours you could easily convert such a set to a single rotation and a single translation.


问:
How to promote code reuse and documentation?
As a team lead of about 10+ developers, I would want to promote code reuse. We have written a lot of code-- a lot of them are repetitive over the past few years. The problem now is that a lot of these code are just duplicate of some other code or a slight variation of them.

I have started the movement ( discussion) on how to make code into components so that they can be reused for the future projects, but the problem is that I afraid the new developers or other developers who are ignorant of the components will just go forward and write their own thing.

Is there anyway to remind the developers to reuse the components/ improve the documentation/ contribute to the underlying component instead of duplicating the existing code and tweaking on it or just write their own?

How to make the components easily discover-able, easily usable so that everyone will use it?

I think every developer knows about the benefit of reusable components and wants to use them, it's just that we don't know how to make them discoverable. Also, the developers when they are writing code, they know they should write reusable code but lack of the motivation to do so.

答:
We've faced this problem on a big project I'm currently working on. We've had some rotation of developers over the last few months, it's also quite a large code base and even the ones who have been on the project since the very beginning don't know every inch of it.

While the code is often well-written and split into small parts with single responsibilities and the documentation is there, it's quite easy to miss something that has been done. Consistent naming conventions help a lot because it's easy to look something up in any IDE. Documentation may be comprehensive but as it grows longer, it's a bit of a pain to read through it.

One thing we did that, in my opinion, improved the situation greatly was the introduction of a thing we call Lightning talks. Whenever someone writes a piece of code that he or she believes should be known to the team, a short (usually 5-15 minutes) presentation is arranged. We try to do this once every week. The subjects tend to vary, from new features and ways of handling complex problems that have recently come up, through testing/coding approaches, reusable component, to talks about the foundations of the app and refactoring thereof.

Certain subjects are mentioned on similar, company-wide talks. We've found it a pretty efficient ways to spur knowledge sharing. It's much easier to see and remember a short presentation and know where to look for additional documentation or whom to address for help than to participate in very long and rarely held training sessions or to just sit there, reading the docs cover to cover.

The company-wide talks actually came first. We just adopted this approach for project-specific knowledge sharing and I think it's working pretty well.

Pair programming also makes the knowledge circulation a lot faster.


问:
Generating PDF files using individual template components
EDIT:  Updated flow diagram to better explain the (likely unnecessary) complexity of what I'm doing.

We at the company I work for are attempting to create complex PDF files using Java iText (the free version 2.1 line).  The documents are built piece-by-piece from individual "template" files, which are added to the final document one after another using the PdfStamper class, as well as filled using AcroForms.

The current design performs a loop which runs for each template that needs to be added in order (as well as the custom logic needed to fill each).  In each iteration of the loop, it does the following:

Creates a PdfReader to open the template file

Creates a PdfStamper that reads from the PdfReader and writes to a "template buffer"

Fills AcroForm fields, as well as measures the height of the template by getting the location of an "end" AcroField.

Closes the PdfReader and PdfStamper

Creates a PdfReader to read a "working buffer" that stores the current final document in progress

Creates a PdfStamper that reads from the PdfReader and writes to a "storage buffer"

Closes the PdfReader, opens a new PdfReader to the "template buffer"

Imports the page from the "template buffer," adds it to the ContentByte of the PdfStamper

Closes the PdfReader and PdfStamper

Swaps the "storage buffer" with the "working buffer" in order to be ready to repeat.

Here is a diagram visually explaining the above process, which is performed for each iteration of the "loop" that performs each template:

However, as discovered through this Stack Overflow question (where example code can also be viewed) and the response by iText author Bruno Lowagie, this methodology of using the PdfStamper can cause significant issues.  "Abusing" the PdfStamper by creating and closing the stamper too many times can cause corruptions in the resulting file that only effect some programs, generating a seemingly good document that may fail in certain contexts.

What is the alternative?  Mr. Lowagie's response suggests that there is a simpler or more direct way to use PdfStampers, though I do not quite understand it myself yet.  Could this be done using only a single stamper?  Could it be done without using a rotating series of buffers?

答:
A co-worker of mine was able to understand how to remove the extraneous uses of stampers and buffers, and open them to the correct combination of places such that the final document remains open for the entirety of the process and is closed only once, thus creating the underlying tables and such in the file correctly as Mr. Lowagie suggested was the issue.

Here is a revised version of the previous test example with these modifications:

```<code>public class PDFFileMakerRevised {

    private static final int INCH = 72;

    final private static float MARGIN_TOP = INCH / 4;
    final private static float MARGIN_BOTTOM = INCH / 2;

    private static final String DIREC = "/pdftest/";
    private static final String OUTPUT_FILEPATH = DIREC + "coolerdoc_%d.pdf";
    private static final String TEMPLATE1_FILEPATH = DIREC + "template1.pdf";
    private static final Rectangle PAGE_SIZE = PageSize.LETTER;
    private static final Rectangle TEMPLATE_SIZE = PageSize.LETTER;

    private static final int DEFAULT_NUMBER_OF_TIMES = 200;

    private float currPosition;
    private int currPage;

    public static void main (String [] args) {

        System.out.println("Starting...");

        PDFFileMakerRevised maker = new PDFFileMakerRevised();

        File file = null;
        try {
            file = maker.createPDF(DEFAULT_NUMBER_OF_TIMES);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        if (file == null || !file.exists()) {
            System.out.println("File failed to be created.");
        }
        else {
            System.out.println("File creation successful.");
        }
    }

    public File createPDF(int numTimes) throws FileNotFoundException, IOException, DocumentException, InterruptedException {

        currPosition = 0;
        currPage = 1;

        String sFilepath = String.format(OUTPUT_FILEPATH, numTimes);

        Document d = new Document(PAGE_SIZE);
        PdfWriter w = PdfWriter.getInstance(d, new FileOutputStream(sFilepath));
        d.open();

        PdfContentByte cb = w.getDirectContent();
        ByteArrayOutputStream stampedBuffer;
        for (int i = 0; i < numTimes; i++) {
            PdfReader templateReader = new PdfReader(new FileInputStream(TEMPLATE1_FILEPATH));

            stampedBuffer = new ByteArrayOutputStream();

            PdfStamper stamper = new PdfStamper(templateReader, stampedBuffer);

            stamper.setFormFlattening(true);
            AcroFields form = stamper.getAcroFields();

            // Get Size
            float[] area = form.getFieldPositions("end");
            float size = TEMPLATE_SIZE.getHeight() - MARGIN_TOP - area[4];

            // Requires Page Break
            if (size >= PAGE_SIZE.getHeight() - MARGIN_TOP - MARGIN_BOTTOM + currPosition) {
                currPosition = 0;
                currPage += 1;
                d.newPage();
            }

            form.setField("field1", String.format("Form Text %d", i+1));
            form.setField("page", String.format("Page %d", currPage));
            stamper.close();
            templateReader.close();
            form = null;

            PdfReader stampedReader = new PdfReader(stampedBuffer.toByteArray());
            PdfImportedPage page = w.getImportedPage(stampedReader, 1);

            cb.addTemplate(page, 0, currPosition);
            currPosition = currPosition - size;

        }
        d.close();
        w.close();

        return new File(sFilepath);
    }
}
</code>```

Body:
A co-worker of mine was able to understand how to remove the extraneous uses of stampers and buffers, and open them to the correct combination of places such that the final document remains open for the entirety of the process and is closed only once, thus creating the underlying tables and such in the file correctly as Mr. Lowagie suggested was the issue.

Here is a revised version of the previous test example with these modifications:

public class PDFFileMakerRevised {

    private static final int INCH = 72;

    final private static float MARGIN_TOP = INCH / 4;
    final private static float MARGIN_BOTTOM = INCH / 2;

    private static final String DIREC = "/pdftest/";
    private static final String OUTPUT_FILEPATH = DIREC + "coolerdoc_%d.pdf";
    private static final String TEMPLATE1_FILEPATH = DIREC + "template1.pdf";
    private static final Rectangle PAGE_SIZE = PageSize.LETTER;
    private static final Rectangle TEMPLATE_SIZE = PageSize.LETTER;

    private static final int DEFAULT_NUMBER_OF_TIMES = 200;

    private float currPosition;
    private int currPage;

    public static void main (String [] args) {

        System.out.println("Starting...");

        PDFFileMakerRevised maker = new PDFFileMakerRevised();

        File file = null;
        try {
            file = maker.createPDF(DEFAULT_NUMBER_OF_TIMES);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        if (file == null || !file.exists()) {
            System.out.println("File failed to be created.");
        }
        else {
            System.out.println("File creation successful.");
        }
    }

    public File createPDF(int numTimes) throws FileNotFoundException, IOException, DocumentException, InterruptedException {

        currPosition = 0;
        currPage = 1;

        String sFilepath = String.format(OUTPUT_FILEPATH, numTimes);

        Document d = new Document(PAGE_SIZE);
        PdfWriter w = PdfWriter.getInstance(d, new FileOutputStream(sFilepath));
        d.open();

        PdfContentByte cb = w.getDirectContent();
        ByteArrayOutputStream stampedBuffer;
        for (int i = 0; i < numTimes; i++) {
            PdfReader templateReader = new PdfReader(new FileInputStream(TEMPLATE1_FILEPATH));

            stampedBuffer = new ByteArrayOutputStream();

            PdfStamper stamper = new PdfStamper(templateReader, stampedBuffer);

            stamper.setFormFlattening(true);
            AcroFields form = stamper.getAcroFields();

            // Get Size
            float[] area = form.getFieldPositions("end");
            float size = TEMPLATE_SIZE.getHeight() - MARGIN_TOP - area[4];

            // Requires Page Break
            if (size >= PAGE_SIZE.getHeight() - MARGIN_TOP - MARGIN_BOTTOM + currPosition) {
                currPosition = 0;
                currPage += 1;
                d.newPage();
            }

            form.setField("field1", String.format("Form Text %d", i+1));
            form.setField("page", String.format("Page %d", currPage));
            stamper.close();
            templateReader.close();
            form = null;

            PdfReader stampedReader = new PdfReader(stampedBuffer.toByteArray());
            PdfImportedPage page = w.getImportedPage(stampedReader, 1);

            cb.addTemplate(page, 0, currPosition);
            currPosition = currPosition - size;

        }
        d.close();
        w.close();

        return new File(sFilepath);
    }
}


答:
Lexing and Parsing lend themselves to different formalisms. The goal is to make both tasks easier to program and maintain, as well as faster at runtime.

If you look at (f)lex, the usual lexer-generator, it uses regular expressions to express the lexical rules. This is notationally much more compact than a grammar expressed as BNF or some similar parser specification.

At runtime, a lexer can be baked down to a finite automaton. A parser cannot. So splitting the job speeds up the process. A parser has to be something like LR(k) or LL(1) or LALR to deal with the ambiguity.

The 'dragon book' has been the classic undergraduate-level text on compilation techniques for nearly 30 years.

Title: What is the responsibility or benefit of a Tokenizer?

Body:
Suppose I had a grammar like:

```<code>object
    { members }
members
    pair
pair
    string : value
value
    number
    string
string
    " chars "
chars
    char
    char chars
number
    digit
    digit number
</code>```

I could parse the following example: { "one" : 1234 }

As far as I understand, I should have the tokens object, members, pair, value, string and chars.

Tokenizing the example should produce

```<code>object
    ->members
        ->pair
            ->"one"
            ->"1234"
</code>```

Parsing the tokens should produce

```<code>object
    ->pair
        ->"one"
        ->1234
</code>```

It seems to me like the tokenizer is either useless or I don't fully understand what a it should do.

What is the responsibility of a tokenizer?
What is the benefit of a tokenizer over parsing the original string?


答:
IMMO the key its not documentation or tools, the key is COMMUNICATION. 10+ developers its not a lot of people, some things that improve this communication:

pair programming: with two people there are more changes that one of the two knows that the problem its already solved in another part of the project and reuse it.

Collective code ownership: All the people works with the different parts of the systems, this way its much easier that they know that something its already done in another part of the project, for me this is fundamental practice in a team.

Give time to work of horizontal projects: for example, one friday or two in a month, and the developers in this time can work in his own projects that has some applicability to your company project. This way the developers can write reusable libraries and components, sometimes its code thats already exists but need some cleaning and documentation.

Make talks and workshops: Reserve a time for developers talks and workshops, the developers can talk about his libraries or perhaps you can do refactor workshops and take some duplicated code and remove the duplication creating a reusable component.

Documentation probably its needed but its only a small part of the real thing you need: improve the communication inside your team.

Title: How to promote code reuse and documentation?

Body:
As a team lead of about 10+ developers, I would want to promote code reuse. We have written a lot of code-- a lot of them are repetitive over the past few years. The problem now is that a lot of these code are just duplicate of some other code or a slight variation of them.

I have started the movement ( discussion) on how to make code into components so that they can be reused for the future projects, but the problem is that I afraid the new developers or other developers who are ignorant of the components will just go forward and write their own thing.

Is there anyway to remind the developers to reuse the components/ improve the documentation/ contribute to the underlying component instead of duplicating the existing code and tweaking on it or just write their own?

How to make the components easily discover-able, easily usable so that everyone will use it?

I think every developer knows about the benefit of reusable components and wants to use them, it's just that we don't know how to make them discoverable. Also, the developers when they are writing code, they know they should write reusable code but lack of the motivation to do so.


答:
What about using a local search engine such as Lucene (or something more specific to source code) to index your code? When someone starts writing a new class or a new function (for example) he must try (as internal policy) a couple of searches before writing his own code. This way you can avoid too much communications and you can rely on good comments, methods and classes names.
I find myself doing this with open source search engines available on internet: I don't know who wrote what or what is the name of a method or a class, but with a couple of searches or synonyms I always find what I need.</p>


问:
How does key-based caching work?
I recently read an article on the 37Signals blog and I'm left wondering how it is that they get the cache key.

It's all well and good having a cache key that includes the object's timestamp (this means that when you update the object the cache will be invalidated); but how do you then use the cache key in a template without causing a DB hit for the very object that you are trying to fetch from the cache.

Specifically, how does this affect One to Many relations where you are rendering a Post's Comments for example.

Example in Django:

```<code>{% for comment in post.comments.all %}
   {% cache comment.pk comment.modified %}
     <p>{{ post.body }}</p>
   {% endcache %}
{% endfor %}
</code>```

Is caching in Rails different to just requests to memcached for example (I know that they convert your cache key to something different). Do they also cache the cache key?

答:
For caching a straight dump of a single already-loaded object, yes, you gain nothing or next-to-nothing.  That's not what those examples are describing - they're describing a hierarchy, where any change to something lower should also trigger an update to everything higher up in the hierarchy.

The first example, from the 37signals blog, uses Project -> Todolist -> Todo as the hierarchy.  A populated example might look like this:

```<code>Project: Foo (last_modified: 2014-05-10)
   Todolist:  Bar1 (last_modified: 2014-05-10)
       Todo:  Bang1 (last_modified: 2014-05-09)
       Todo:  Bang2 (last_modified: 2014-05-09)

   Todolist:  Bar2 (last_modified: 2014-04-01)
       Todo:  Bang3 (last_modified: 2014-04-01)
       Todo:  Bang4 (last_modified: 2014-04-01)
</code>```

So, let's say Bang3 was updated.  All its parents also get updated:

```<code>Project: Foo (last_modified: 2014-05-16)
   Todolist:  Bar2 (last_modified: 2014-05-16)
       Todo:  Bang3 (last_modified: 2014-05-16)
</code>```

Then when it comes time to render, loading Project from the database is basically inevitable.  You need a point to start at.  However, because its last_modified is an indicator of all its children, that's what you use as the cache key before attempting to load the children.

While the blog posts use separate templates, I'm going to lump them together into one.  Hopefully seeing the complete interaction in one place will make it a little clearer.

So, the Django template might look something like this:

```<code>{% cache 9999 project project.cache_key %}
<h2>{{ project.name }}<h2>
<div>
   {% for list in project.todolist.all %}
   {% cache 9999 todolist list.cache_key %}
      <ul>
         {% for todo in list.todos.all %}
            <li>{{ todo.body }}</li>
         {% endfor %}
      </ul>
   {% endcache %}
   {% endfor %}
</div>
{% endcache %}
</code>```

Say we pass in a Project whose cache_key still exists in the cache.  Because we propagate changes to all related objects to the parent, the fact that that particular key still exists means the entire rendered contents can be pulled from the cache.

If that particular Project had just been updated - for example, as with Foo above - then it will have to render its children, and only then will it run the query for all Todolists for that Project.  Likewise for a specific Todolist - if that list's cache_key exists, then the todos inside it have not changed, and the whole thing can be pulled from the cache.

Also notice how I'm not using todo.cache_key in this template.  It's not worth it, since as you say in the question, body has already been pulled from the database.  However, database hits aren't the only reason you might cache something.  For example, taking raw markup text (such as what we type into question/answer boxes on StackExchange) and converting it to HTML may well take sufficient time that caching the result would be more efficient.

If that were so, the inner loop in the template might look more like this:

```<code>         {% for todo in list.todos.all %}
            {% cache 9999 todo todo.cache_key %}
               <li>{{ todo.body|expensive_markup_parser }}</li>
            {% endcache %}
         {% endfor %}
</code>```

So to pull everything together, let's go back to my original data at the top of this answer.  If we assume:

All the objects had been cached in their original state

Bang3 was just updated

We're rendering the modified template (including expensive_markup_parser)

Then this is how everything would be loaded:

Foo is retrieved from the database

Foo.cache_key (2014-05-16) does not exist in the cache

Foo.todolists.all() is queried:  Bar1 and Bar2 are retrieved from the database

Bar1.cache_key (2014-05-10) already exists in the cache; retrieve and output it

Bar2.cache_key (2014-05-16) does not exist in the cache

Bar2.todos.all() is queried:  Bang3 and Bang4 are retrieved from the database

Bang3.cache_key (2014-05-16) does not exist in the cache

{{ Bang3.body|expensive_markup_parser }} is rendered

Bang4.cache_key (2014-04-01) already exists in the cache; retrieve and output it

Savings from the cache in this tiny example are:

Database hit avoided: Bar1.todos.all()

expensive_markup_parser avoided 3 times: Bang1, Bang2, and Bang4

And of course, next time it's viewed, Foo.cache_key would be found, so the only cost to rendering is retrieving Foo alone from the database and querying the cache.

Title: How does key-based caching work?

Body:
For caching a straight dump of a single already-loaded object, yes, you gain nothing or next-to-nothing.  That's not what those examples are describing - they're describing a hierarchy, where any change to something lower should also trigger an update to everything higher up in the hierarchy.

The first example, from the 37signals blog, uses Project -> Todolist -> Todo as the hierarchy.  A populated example might look like this:

Project: Foo (last_modified: 2014-05-10)
   Todolist:  Bar1 (last_modified: 2014-05-10)
       Todo:  Bang1 (last_modified: 2014-05-09)
       Todo:  Bang2 (last_modified: 2014-05-09)

   Todolist:  Bar2 (last_modified: 2014-04-01)
       Todo:  Bang3 (last_modified: 2014-04-01)
       Todo:  Bang4 (last_modified: 2014-04-01)

So, let's say Bang3 was updated.  All its parents also get updated:

Project: Foo (last_modified: 2014-05-16)
   Todolist:  Bar2 (last_modified: 2014-05-16)
       Todo:  Bang3 (last_modified: 2014-05-16)

Then when it comes time to render, loading Project from the database is basically inevitable.  You need a point to start at.  However, because its last_modified is an indicator of all its children, that's what you use as the cache key before attempting to load the children.

While the blog posts use separate templates, I'm going to lump them together into one.  Hopefully seeing the complete interaction in one place will make it a little clearer.

So, the Django template might look something like this:

{% cache 9999 project project.cache_key %}
<h2>{{ project.name }}<h2>
<div>
   {% for list in project.todolist.all %}
   {% cache 9999 todolist list.cache_key %}
      <ul>
         {% for todo in list.todos.all %}
            <li>{{ todo.body }}</li>
         {% endfor %}
      </ul>
   {% endcache %}
   {% endfor %}
</div>
{% endcache %}

Say we pass in a Project whose cache_key still exists in the cache.  Because we propagate changes to all related objects to the parent, the fact that that particular key still exists means the entire rendered contents can be pulled from the cache.

If that particular Project had just been updated - for example, as with Foo above - then it will have to render its children, and only then will it run the query for all Todolists for that Project.  Likewise for a specific Todolist - if that list's cache_key exists, then the todos inside it have not changed, and the whole thing can be pulled from the cache.

Also notice how I'm not using todo.cache_key in this template.  It's not worth it, since as you say in the question, body has already been pulled from the database.  However, database hits aren't the only reason you might cache something.  For example, taking raw markup text (such as what we type into question/answer boxes on StackExchange) and converting it to HTML may well take sufficient time that caching the result would be more efficient.

If that were so, the inner loop in the template might look more like this:

         {% for todo in list.todos.all %}
            {% cache 9999 todo todo.cache_key %}
               <li>{{ todo.body|expensive_markup_parser }}</li>
            {% endcache %}
         {% endfor %}

So to pull everything together, let's go back to my original data at the top of this answer.  If we assume:

All the objects had been cached in their original state

Bang3 was just updated

We're rendering the modified template (including expensive_markup_parser)

Then this is how everything would be loaded:

Foo is retrieved from the database

Foo.cache_key (2014-05-16) does not exist in the cache

Foo.todolists.all() is queried:  Bar1 and Bar2 are retrieved from the database

Bar1.cache_key (2014-05-10) already exists in the cache; retrieve and output it

Bar2.cache_key (2014-05-16) does not exist in the cache

Bar2.todos.all() is queried:  Bang3 and Bang4 are retrieved from the database

Bang3.cache_key (2014-05-16) does not exist in the cache

{{ Bang3.body|expensive_markup_parser }} is rendered

Bang4.cache_key (2014-04-01) already exists in the cache; retrieve and output it

Savings from the cache in this tiny example are:

Database hit avoided: Bar1.todos.all()

expensive_markup_parser avoided 3 times: Bang1, Bang2, and Bang4

And of course, next time it's viewed, Foo.cache_key would be found, so the only cost to rendering is retrieving Foo alone from the database and querying the cache.


问:
Is the version problem a nightmare in programming?
Let say you are building an app and you are using the latest library verion from a third party (say ver2.jar). Then you saw an example written 2 years ago, but that example uses the ver1.jar

Now in ver1.jar, there is web.method1(), but in ver2.jar there is no such method. Instead, in ver2.jar you have web.getOtherMethod.method1();

You ran your app with ver2.jar and found a lot of missing classes, and lots of errors. So what are you going to do to solve the incompatibility?

I think the version problem is really a nightmare because it is unstructured and you do not actually understand what is going on.

Also, why changed the location of the method in ver2.jar so differently like that?

答: There are ways to protect yourself when using 3rd party libraries. One such method is to use the Adapter Pattern. This way you can use your class and keep it relatively the same in your code base and make any changes necessary with the library in your adapter class. It will also make unit testing much easier to verify version changes since you just need to test your adapter class rather than your entire code base to ensure that any changes in upgrading the library doesn't impact anything else.</p>


答:
This isn't a question of versioning or verison control -- this is a question of amaturish interface design.  In proper, professional utility code design, you never "make a new version" of the interface that's entirely incompatible with the old one, espcially without providing a compatability layer.

In the example you provided, the web interface contained in the ver1.jar file has a method like follows:

```<code>interface web {
   void method1()
}
</code>```

Once this is published and provided for public use, it is amaturish to ever, ever, ever break it.  Usually, the developers will define an additional interface, possibly with a back-reference to the old way of doing things

```<code>interface web2 {
    web getOtherMethod()
}
interface oldStuff {
   void method1()
}
</code>```

It also wouldn't be improper to add additional methods to an existing interface:

```<code>interface web {
   void method1()
   void method2()
}
</code>```

But if a simple version change breaks code you wrote against a library, it's either not a library worth using, or you were attemping to write directly to the internals instead of the interface.

For further reading on Java and interfaces, there are basic tutorials available for Java, and it's not to hard to find a seasoned programmer to extol the virtues of interfaces and encapsulation.

Title: Is the version problem a nightmare in programming?

Body:
Let say you are building an app and you are using the latest library verion from a third party (say ver2.jar). Then you saw an example written 2 years ago, but that example uses the ver1.jar

Now in ver1.jar, there is web.method1(), but in ver2.jar there is no such method. Instead, in ver2.jar you have web.getOtherMethod.method1();

You ran your app with ver2.jar and found a lot of missing classes, and lots of errors. So what are you going to do to solve the incompatibility?

I think the version problem is really a nightmare because it is unstructured and you do not actually understand what is going on.

Also, why changed the location of the method in ver2.jar so differently like that?

Body:
This isn't a question of versioning or verison control -- this is a question of amaturish interface design.  In proper, professional utility code design, you never "make a new version" of the interface that's entirely incompatible with the old one, espcially without providing a compatability layer.

In the example you provided, the web interface contained in the ver1.jar file has a method like follows:

interface web {
   void method1()
}

Once this is published and provided for public use, it is amaturish to ever, ever, ever break it.  Usually, the developers will define an additional interface, possibly with a back-reference to the old way of doing things

interface web2 {
    web getOtherMethod()
}
interface oldStuff {
   void method1()
}

It also wouldn't be improper to add additional methods to an existing interface:

interface web {
   void method1()
   void method2()
}

But if a simple version change breaks code you wrote against a library, it's either not a library worth using, or you were attemping to write directly to the internals instead of the interface.

For further reading on Java and interfaces, there are basic tutorials available for Java, and it's not to hard to find a seasoned programmer to extol the virtues of interfaces and encapsulation.


问:
Restricting object types that can be added to each other using the Composite Pattern
The Situation: I am building a custom PHP application framework. I have implemented a composite pattern so I can build a object tree representing the page to be rendered. Example:

```<code>abstract class \Block\BlockAbstract {
     protected _blocks = array();
     public function __construct($properties);
     public function getBlocks();
     public function addBlock($block);

     ...

     public function render();

}
</code>```

All of my "block" object inherit from this abstract class which is working out great and rendering has been a snap with the help of a little recursion.

The Problem:
I need a way to validate what classes of blocks can be added to other blocks. For example I have 4 distinct block types I have to consider. Keep in mind that ALL blocks inherit from a single block abstract, these are classifications of behavior of the concrete classes, not to be confused with additional abstracts:

Generic - Generics can have any other block type added to it

Final - Can not have any child blocks added to it.

Parent - A parent is a block that can only have a specific type child added to
it, but can be added to any Generic

Child  - Can only be added to a specific parent. This block can also share the properties of a Generic, Parent or Final

To sum the goal up: Given a concrete block class name, generate a list of all concrete block classes that can be added to it.

Solutions Proposed So Far:

Add a property called "blockClassification" to the block abstract that defines it as a Generic, Final, Parent or Child and hard code the logic into a validate function that gets called in the from the addBlock($block) method.

I don't like this solution for a number of reasons, but mainly it still doesn't give me a clear path for defining what the concrete parents and children are that can be allowed. For instance, I have a concrete class \Block\Tabs that is a parent. It can only have \Block\Tabs\Panel blocks added to it, and \Block\Tabs\Panel can only be added to \Block\Tabs. Additional properties would have to be added to build those relationships, and those properties could be examined to derive the "block classification" making this approach impractical.

Add allowedChildTypes property to the block that defines a list of concrete classes that can be added. For ease of use 2 values have specific meaning, a * that represents all block types, and NULL value that means no blocks can be added. For all other cases a coma delimited string of class names is provided and only those classes or classes that inherit from them are allowed

I'm leaning towards this direction because PHP gives me the InstaceOf operator. I can use this to do the checks, when I have new concrete classes that extend the base set, that check will return the same results as its parent class. My only hesitation is that while this method definitely solves the problem of "Given a concrete block class name, generate a list of", I feel like it limits me in the future in that I can only do the search down the tree and not back up. I.e. "Given a child block class name, generate a list of parent blocks it can be added to"

I'm sure that I am not the only one to ever run into the problem, so my question to the masses is: What is the best way to approach/solve this problem?

Additional Information:

If you where wondering how I'm getting a list of all the classes in the first place, the framework implements PSR-0 so I am scanning the directory tree to derive all of the class names, then dynamically instantiating them.

```<code>$allClassNames = scanDirectories(); // Returns array of strings ex: array('\Block\Classname1','\Block\Classname2');
foreach($allClassNames as $className){
  $object = new $className();
}
</code>```

答:
I don't really know PHP, but my understanding from the other comments is that it's not strongly typed. If I were trying to solve this problem in C# or Java, my preference would be to use inheritance over composition pattern. "Is a" instead of "has a."

What I would do is have a base class for each of your block classes; generic, final, parent, child. I would additionally create a helper class to do your checking for the types of concrete classes that can be added to each of the block classes. For example

public class GenericBlock implements BlockAbstract
  {
      _helper = new HelperClass();

```<code>  public function AddBlock(block)
  {
      _helper.CheckBlockType(block);
  }
</code>```

}

In the helper class, I would have helper methods for each of the block types you need. The benefit is that if you need to change or add more rules, it's easily extensible through a helper class. If I were dealing with a typed language, my rules for what classes could be added to the block class would be based on the type. It sounds like your rules are more open, so you might want to just have lists of class names in your helper methods. Not elegant, but will get the job done.

Body:
I don't really know PHP, but my understanding from the other comments is that it's not strongly typed. If I were trying to solve this problem in C# or Java, my preference would be to use inheritance over composition pattern. "Is a" instead of "has a."

What I would do is have a base class for each of your block classes; generic, final, parent, child. I would additionally create a helper class to do your checking for the types of concrete classes that can be added to each of the block classes. For example

public class GenericBlock implements BlockAbstract
  {
      _helper = new HelperClass();

  public function AddBlock(block)
  {
      _helper.CheckBlockType(block);
  }

}

In the helper class, I would have helper methods for each of the block types you need. The benefit is that if you need to change or add more rules, it's easily extensible through a helper class. If I were dealing with a typed language, my rules for what classes could be added to the block class would be based on the type. It sounds like your rules are more open, so you might want to just have lists of class names in your helper methods. Not elegant, but will get the job done.


问:
Should a user story be shared between developers?
I commonly see stories that have back-end and front-end development.  For example, consider a large dialog with a few tables and some dynamic controls.  We'll make several stories (maybe one for each table and another for the dynamic control system).

The dev team will then split with one person on the back-end and another on the front-end.  This makes it easy for the back-end person to just worry about the structure of the SQL layer while the front-end person focuses on stuff like layout.  After the initial interface between back- and front-end is agreed, the two developers can focus their attention to get their part done by the end of the sprint.

Then comes the chaos.  Who "owns" which story?  What does "in progress" mean or "done"?  Should we make two separate stories for back-end and front-end?  If so, doesn't that break the idea of user stories based on feature?  Our system has a notion of "sub-tasks", which eases some of these problems.  But sub-tasks add an extra complexity.  Is there a better way?  Is this a "bad" way to use Scrum?

I have been using some form of Agile over the past few years at a couple places.  I have no official training yet, so please forgive any wrong terminology or ideology.  I'm just trying to learn practical ways to improve our process.

答:
A "story" is so named because it represents a complete, well, story, from a customer's perspective. Without either the front-end or back-end, there is no use-case path for the customer to execute.

In your case, I think both front-end and back-end should be a single story. Divide it into tasks. The developers own their different tasks. These tasks can be individually tracked through their phases - In Progress, Coding Done, Module Testing Done, etc.

Make sure you include QA-assigned tasks in the same story - without validation a story is useless. The QA will test the end-to-end integrated story that a customer will see. Only then should the overall story be marked as Done. In an ideal Agile environment, a real customer or a customer proxy also tries out the story in a running application, and marks the story Accepted if it meets the agreed-upon requirements.

If you want quicker feedback loops, try breaking the use-case into smaller end-to-end features. For example, instead of a use-case like "A customer can buy stuff using a shopping cart", divide it into "A customer can add a product to a shopping cart" and so on... Then complete each smaller use-case end to end as described above.

EDIT:
I wanted to back up the points above with some sources. The characteristics of a good user story are represented concisely with an acronym called "INVEST". It was created by Bill Wake and popularized by the Scrum movement. Note especially the items on stories being Independent and Vertical.

Some more information here and here.


答:
Where I'm at today we call this larger project an "epic".  An epic is made up of multiple stories and it can span multiple sprints/iterations.  A story, for us, is always given to a single developer and should fit within a single sprint.  A single story is then subdivided into tasks.  Each of the tasks are completed by the same developer on that story.  The tasks are meant to give insight into the progress of the story during the sprint/iteration.  As each story is completed, by each developer, the epic shows progress.

The point of the epic is to have a larger goal that doesn't necessarily fit into a single sprint/iteration.  Over time all of the stories are completed and the epic is finished.  Epics are placed into a release.

Then comes the chaos. Who "owns" which story? What does "in progress"
  mean or "done"?

We demo code every two weeks where the stories for that sprint/iteration must be shown to stakeholders and approved.  In this context "done" for a story means that I can show you what it does.  A developer owns their story and is responsible for showing it (this part is kind of an over simplification, but good enough for this answer; we coordinate our demos through a single person).  "Done" means it can be successfully demonstrated.  "In progress" means I have tasks outstanding and the story is not complete.  An epic is complete when all of the stories for that epic have been successfully demonstrated.

Now this is the perfect case progression.  We have stories and demos that fail, users that want something else, etc.  Above is the goal and for the most part it works.

Title: Should a user story be shared between developers?

Body:
I commonly see stories that have back-end and front-end development.  For example, consider a large dialog with a few tables and some dynamic controls.  We'll make several stories (maybe one for each table and another for the dynamic control system).

The dev team will then split with one person on the back-end and another on the front-end.  This makes it easy for the back-end person to just worry about the structure of the SQL layer while the front-end person focuses on stuff like layout.  After the initial interface between back- and front-end is agreed, the two developers can focus their attention to get their part done by the end of the sprint.

Then comes the chaos.  Who "owns" which story?  What does "in progress" mean or "done"?  Should we make two separate stories for back-end and front-end?  If so, doesn't that break the idea of user stories based on feature?  Our system has a notion of "sub-tasks", which eases some of these problems.  But sub-tasks add an extra complexity.  Is there a better way?  Is this a "bad" way to use Scrum?

I have been using some form of Agile over the past few years at a couple places.  I have no official training yet, so please forgive any wrong terminology or ideology.  I'm just trying to learn practical ways to improve our process.


问:
How to handle errors best addressed in a higher abstraction layer and dependent on state inferred in current layer?
I have a use-case that can be repaired, but the logic for repairing it is best done in a higher level of abstraction.  Just throwing exception/failure is ugly because it's hard to pass back up through the stack the information needed for the parent-layer to know how to fix it.

To explain the the specifics, I have a program that controls multiple pieces of hardware.  The 'top' layer is responsible for calculating how to task each piece of hardware to work together, how to generate 'paths' of data across hardware etc.  My next layer includes threads for each individual device.  each device thread generates and caches device state (fetched from hardware and config files).  Devices process requests from the application, figure out how to update the hardware to make those requests happen, and then will modify the cached state to reflect the changes made.  Finally I have plugins which send physical requests to hardware.

This works fine usually, requests are sequential to avoid data race issues.  We only pass information down layers, we have no way of getting async updates back up the layer.  However, it's very unlikely, but possible, that someone could physically change the hardware without going through our control system.  We will wait until the plugin detects an error trying to handle a request, and only then try updating our state for that piece of hardware to see if a change caused the failure (constant monitoring is a later feature).

My problem is that when a change is detected on one device, that usually means a change was made to connected devices.  When I detect this, I want to trace the change to connected device, update their state etc until I found all changes (this doesn't require updating all devices, just connected ones).  Each device thread is only responsible for one device, so they can't trace the change through other devices without propagating the exception up a layer.  However, I need to know exactly what changes were detected on the device to know which connected devices I should be refreshing the state of.  If I just throw an exception, this knowledge is lost and must be recalculated, which is a small but real cost due to time it takes to communicate with hardware.

The tempting thing to do is to call a method in my application layer saying "this change was detected, go update everything else related to it".  However, this makes drivers aware of the layer above them, which is not good.  Another option is to simply propagate the error up and let my application layer notice the error and then go back to the same device to ask what changed and update all it's state, then re-calculate the changes to be made and make the request back down to the device level.  The first is an obvious code smell, the second seems like more code, redundant logic, and small speed penalties (it takes a little time to get state from hardware).  Are there some other options?

答:
This sounds like a job for the observer pattern.  Every device is being observed by it's connected devices.  Are you sure you need the parent layer to get involved?

Unless there is something else you need the parent layer to do then just handle these exceptions on the device by recovering, setting it as having changed, and looping through it's connected observers telling them what they need to know to recover.

If one hop recovery is enough you're done.  If you need to allow the recover to propagate some fixed n hops you'll need some stopping logic or it'll cascade to everything.  You already said you didn't need that.

After all that throw an exception to politely tell the parent layer that the request died because some goofball has been mucking with the hardware.  Log that you've recovered from their shenanigans and are ready for the next request.

You set all that up by making sure whenever there is a connection between two devices the two devices register as observers of each other.


问:
Calling static method from instance of class
As a developer I am fan of static methods.

Recently I come across difference between OOP languages about this static methods.

All OOP language use static method to access any method without creating instance of than class. So we can call this kind of method with just class name.

But some language allow to access static method from instance variable also like Java and some don't like Objective - C.

So what is the reason of this kind of difference between two OOP language? Which is correct OOP behaviour? I am just curious to know this.

答:
Static methods have nothing to do with OOP at its core. If Java had no instances of classes, this would be an example of modular programming with classes being modules and static methods being ordinary procedures.

The here relevant difference between Java and Objective-C is that the latter has a Smalltalk-like metaobject protocol: classes themselves are normal objects. A foo object may be an instance of a FooClass which eventually is an instance (!= subclass) of NSObject. When we invoke a method on a class, we send this message to the actual object representing that class. In Java, calling a static method does not involve objects at all, it's just a procedure call (and can be fully resolved before run time – no dynamic dispatch is needed).

In Java, classes are not reified beyond reflection. So instance.staticMethod() kind of makes sense, as it couldn't mean anything else (it just happens to share the syntax for ordinary method calls, but the static method is only looked up according to the static type of the instance variable.

Objective-C does not have such “static methods”, but it does have:

class methods, which resemble static methods if you squint your eyes. It would be very confusing if a method call on an instance would end up being a method call on a class (another object alltogether), so there is no syntactic shortcut like [instance staticMethod], which doesn't even save that much over [[instance class] staticMethod]. Such class methods are good for constructors and other factory methods. However, they are not “static” as they are subject to inheritance.

plain old C functions. These exist outside of objects and classes, and are not subject to dynamic dispatch – which also makes them interesting from a performance standpoint. These are “static” in the actual sense of that word, but they are not “methods”.

ContentLicense: CC BY-SA 4.0


问:
Only functions without a class in cpp file! good design or not?
When I was going through the project on which I am working, I came across a cpp file, which has only functions and static variables.I was wondering why they have not put everything into a class! Whenever the inside functions have to be called, the cpp file is included.

Is this a good design? what are the pros and cons of these type of design?

for ex.

```<code>//independent.cpp
#include "someclass.h"
static int var1;
static someclass object("hello");
static bool var2;

void foo(const char* dir, const char* filename){
...
}

somefile.cpp
#include "independent.cpp"
class sample{
public:
  void caller(){
  foo("c:\", "file.txt");
  }
}
</code>```

答:
They simply follow a singleton-object paradigm different from the C++ class offered one:

static variables in CPP file are invisible outside, while private member of a class have to be declared in the class (that must be given in an header).

If you want to make those variables just unreachable, the private access is good, but if you want to make them secret, they cannot be "members" of a class whose size must be known.

And if they have to exist just once, a class must be a singleton (that is a static hidden variable accessed by a global function) that's not that different in making the variable itself global in a very limited context.

Its is just the good-old C-based OOP implementation you can find in Win32, or in GTK+.

If it is a good or bad design is more a matter of context than idiom.


答:
What are the pros and cons of these type of design?

Pros: easy to write, easy to read, easy to call.

Cons: naming conflicts, risk of global variables, difficult to override.

I was wondering why they have not put everything into a class!

If your functions don't need a context (e.g. utility functions), you're going to have difficulties finding a meaningful place for them in a class.  As much as classes are a very useful way to organise code and instances, there are scenarios where they're not worth the hassle.

You could also argue it's not much of an effort to put it in a class.  That's a valid point, but the author(s) didn't see any added value to it.

Is this a good design?

I 100% agree with Emilio Garavaglia's take on that: Whether it is a good or a bad design depends on the context.  It's not wrong to do it this way, but it may be infeasible in the scope of some projects.

Title: Only functions without a class in cpp file! good design or not?

Body:
When I was going through the project on which I am working, I came across a cpp file, which has only functions and static variables.I was wondering why they have not put everything into a class! Whenever the inside functions have to be called, the cpp file is included.

Is this a good design? what are the pros and cons of these type of design?

for ex.

```<code>//independent.cpp
#include "someclass.h"
static int var1;
static someclass object("hello");
static bool var2;

void foo(const char* dir, const char* filename){
...
}

somefile.cpp
#include "independent.cpp"
class sample{
public:
  void caller(){
  foo("c:\", "file.txt");
  }
}
</code>```


问:
Using a Simple/Static Factory vs. instantiating directly: new Thing() vs. factory.createThing() - what's the benefit?
Here are two ways to instantiate an object:

Option 1:

```<code>Thing thing = new Thing();
</code>```

Option 2: (the factory is a Static Factory, but it could also be a Simple Factory).

```<code>Thing thing = ThingFactory.createThing();
</code>```

Where:

```<code>class ThingFactory(){
    public static Thing createThing(){
        return new Thing();
    }
}
</code>```

Option 2 is said to be better, because using a factory decouples the client code from the concrete implementation of the class it's instantiating.

However what difference does it actually make if I use new Thing() or factory.createThing()? The only difference between the two options is that the instantiation code is moved to a different place.

As I explained above I know the 'academic' explanation to why using a factory is 'better', but I don't actually see the practical benefit. In both cases, the client knows exactly what it wants: a Thing. The only difference is the exact line of code: new Thing() or factory.createThing().

More sophisticated factories, I can see their benefit. For example using the Abstract Factory pattern, I could create different Factory subclasses that instantiate different concrete implementations of Thing, and inject the suitable Factory to the client at runtime, without the client worrying about the concrete implementation it receives. BlueThingFactory instantiates BlueThing, RedThingFactory instantiates RedThing, but the client only cares that it receives a Thing.

This is with more sophisticated factories.

But I'm unable to see the benefit of using a simple factory as in the example I described. All it does is move new Thing() to a different place. I don't understand the benefit of this.

Please explain to me the actual benefits of using a simple factory.

答:
Suppose you later come up with a version 2 of class Thing, e.g. Thing2. Instead of finding all the "new Thing" and change all of them to "new Thing2" you only need to change one instruction inside the factory.

I find it usefull with unit test where I change the factory to create the mock class (e.g. "new ThingMock"). The rest of the code remains the same.

Maybe the content of class Thing is read by internet so the method "createThing" can make a download of an object, or the new class can be loaded by a file, have random contents, etc. In theese cases there are many instruction inside createThing and it would be hard to make such change in all the instructions "new Thing".


答:
fact.createThing(args) allows the factory to return a subclass of Thing (dependency injection), or a pooled object of Thing.

Both of these have their advantages; the subclass option allows Thing to be abstract or an interface, and allows it to be mocked in testing.

The pool option is only handy when Thing uses a limited resource or is expensive to allocate.

Title: Using a Simple/Static Factory vs. instantiating directly: new Thing() vs. factory.createThing() - what's the benefit?

Body:
Here are two ways to instantiate an object:

Option 1:

```<code>Thing thing = new Thing();
</code>```

Option 2: (the factory is a Static Factory, but it could also be a Simple Factory).

```<code>Thing thing = ThingFactory.createThing();
</code>```

Where:

```<code>class ThingFactory(){
    public static Thing createThing(){
        return new Thing();
    }
}
</code>```

Option 2 is said to be better, because using a factory decouples the client code from the concrete implementation of the class it's instantiating.

However what difference does it actually make if I use new Thing() or factory.createThing()? The only difference between the two options is that the instantiation code is moved to a different place.

As I explained above I know the 'academic' explanation to why using a factory is 'better', but I don't actually see the practical benefit. In both cases, the client knows exactly what it wants: a Thing. The only difference is the exact line of code: new Thing() or factory.createThing().

More sophisticated factories, I can see their benefit. For example using the Abstract Factory pattern, I could create different Factory subclasses that instantiate different concrete implementations of Thing, and inject the suitable Factory to the client at runtime, without the client worrying about the concrete implementation it receives. BlueThingFactory instantiates BlueThing, RedThingFactory instantiates RedThing, but the client only cares that it receives a Thing.

This is with more sophisticated factories.

But I'm unable to see the benefit of using a simple factory as in the example I described. All it does is move new Thing() to a different place. I don't understand the benefit of this.

Please explain to me the actual benefits of using a simple factory.


答:
Factory methods might allow for better named interfaces. new Range(0, n - 1) isn't as readable as Range.upto(n). Note also that in some languages (Perl, Python, Ruby), new isn't a keyword but at most a convention, so picking an appropriate method name for the constructor is preferable.

Factories (not singletons or similar constructs via static methods) simplify testing and increase flexibility. Here it is important to balance YAGNI with planning for change (and a DI container is so much easier to change than recompiling everything after running s/ClassA/ClassB/ over your whole source).

In some languages, the constructor can't be part of an interface. Here, we need to offer a method that wraps the constructor. This is important in some cases like a Monad pattern.

Factory methods are a great way of enforcing programming to an interface, not an implementation, as the user has no control over the specific class being returned.


问:
Do RESTful APIs tend to encourage anemic domain models?
I'm working on a project in which we are trying to apply both domain-driven design and REST to a service-oriented architecture. We aren't worrying about 100% REST compliance; it would probably be better to say we are trying to build resource-oriented HTTP APIs (~Level 2 of Richardson's REST maturity model). Nevertheless, we are trying to stay away from RPC-style use of HTTP requests, i.e. we attempt to implement our HTTP verbs according to RFC2616 rather than using POST to do IsPostalAddressValid(...), for example.

However, an emphasis on this seems to be at the expense of our attempt to apply domain-driven design. With only GET, POST, PUT, DELETE and a few other rarely used methods, we tend to build CRUDdy services, and CRUDdy services tend to have anemic domain models.

POST: Receive the data, validate it, dump it to the database. GET: Retrieve the data, return it. No real business logic there. We also use messages (events) between the services, and it seems to me that most of the business logic ends up being built around that.

Are REST and DDD at tension at some level? (Or am I misunderstanding something here? Are we maybe doing something else wrong?) Is it possible to build a strong domain model in a service-oriented architecture while avoiding RPC-style HTTP calls?

答:
REST API is just one type of presentation layer. It has nothing to do with the domain model.

The question you posted comes from your confusion that you somehow need to adapt one to another. You don't.

You map your domain model to your REST API the same way you map your domain model to an RDBMS via an ORM — there has to be this mapping layer.

Domain ← ORM → RDBMS

Domain ← REST Mapping → REST API


问:
How to bill time working around web hosting issues?
My client's web hosting company changed some web server security rules which made the site not work properly. I spent 4 hours diagnosing the problem and emailing their tech support back and forth.

I'm thinking of billing my client for this, but it could be counterproductive because it doesn't happen that often that I have to work around web hosting issues. On the other hand, I hate working without getting paid.

Should I:

bill them for working around web hosting issues (they chose the web hosting company)

threaten to bill them next time and advise them to change their hosting company

let it go and just incorporate any potential web hosting issues into the price for future jobs

How do you do it?

答:
Call or visit your personal contact at Client and let them know about the issues, their reasons and what you did. If Client values your work he will ask you to bill them (happened to me). If Client says "thanks for the freebie", start looking for Client 2.0.

Sometimes Client can't issue work orders after the fact, so they'll hint at the possibility of hiding these few hours in the next regular invoice.

But let me repeat: Let them know that you've been there for the problem that they did not even know about.