问:
Would there be any benefit to writing synchronous code using the syntax of promises
Is there such a concept as a synchronous promise? Would there be any benefit to writing synchronous code using the syntax of promises?

```<code>try {
  foo();
  bar(a, b);
  bam();
} catch(e) {
  handleError(e);
}
</code>```

...could be written something like (but using a synchronous version of then);

```<code>foo()
  .then(bar.bind(a, b))
  .then(bam)
  .fail(handleError)
</code>```

答:
Yes and no. Your code sample will fail on ..

```<code>.then(bar.bind(a, b))
</code>```

You'd have to use

```<code>.then(function() {bar.bind(a,b);})
</code>```

.. unless foo()'s resolve() returns the arguments a,b in which case you'd use ..

```<code>.then(bar.bind)
</code>```

In any case, the real advantage of writing that code in that way is that it really isn't synchronous code. It's sequential, but not synchronous. It's asynchronous. The foo() invocation could invoke some filesystem activity that takes a while, if running on node.js/io.js, or it could run a background worker in a separate thread if running on a modern browser, and in either case the promise wouldn't resolve() and the next then() wouldn't execute until that task completes, but meanwhile Javascript's main thread is still running and processing other events.

The down side is that you must have a promise strategy in place and work with it. Where Neil said you should use a polyfill, which is true in that ECMAScript 6 isn't generally adopted yet, even if it was you must still work with its promise strategy. So your greater concern is that foo() and bar() and bam() must return promises. Those promises must be objects that intercept a resolve() or reject() and pass them on to .then() or .done() and to .fail(), and they must chain for .fail(). (There's more to promises than this, you'll need to do more research on this if you bake your own.) The existing promise frameworks including even jQuery's $.Deferred are pretty elegant but the point is you're adding more work to your code.

So, really as Neil said you should only write your code in the promises syntax manner when you feel you're sequentially invoking methods that are expected to be long-running tasks. However, YAGNI; don't do it if you think they might be long-running tasks in the future, only do it if you know they're long-running tasks now. Don't optimize early until you've identified a bottleneck. But you also must consider the cost of promises. Don't write asynchronous code if you can't handle supporting the promise strategy.

Body:
Yes and no. Your code sample will fail on ..

.then(bar.bind(a, b))

You'd have to use

.then(function() {bar.bind(a,b);})

.. unless foo()'s resolve() returns the arguments a,b in which case you'd use ..

.then(bar.bind)

In any case, the real advantage of writing that code in that way is that it really isn't synchronous code. It's sequential, but not synchronous. It's asynchronous. The foo() invocation could invoke some filesystem activity that takes a while, if running on node.js/io.js, or it could run a background worker in a separate thread if running on a modern browser, and in either case the promise wouldn't resolve() and the next then() wouldn't execute until that task completes, but meanwhile Javascript's main thread is still running and processing other events.

The down side is that you must have a promise strategy in place and work with it. Where Neil said you should use a polyfill, which is true in that ECMAScript 6 isn't generally adopted yet, even if it was you must still work with its promise strategy. So your greater concern is that foo() and bar() and bam() must return promises. Those promises must be objects that intercept a resolve() or reject() and pass them on to .then() or .done() and to .fail(), and they must chain for .fail(). (There's more to promises than this, you'll need to do more research on this if you bake your own.) The existing promise frameworks including even jQuery's $.Deferred are pretty elegant but the point is you're adding more work to your code.

So, really as Neil said you should only write your code in the promises syntax manner when you feel you're sequentially invoking methods that are expected to be long-running tasks. However, YAGNI; don't do it if you think they might be long-running tasks in the future, only do it if you know they're long-running tasks now. Don't optimize early until you've identified a bottleneck. But you also must consider the cost of promises. Don't write asynchronous code if you can't handle supporting the promise strategy.


问:
Implementing common logic in base class

Background

In the documentation of a project I'm working on I came across the following sentence which immediately triggered an alarm for me:

when having several concrete classes that inherits from the same base class, logic which is common for all sub classes should NOT be implemented in the base class.

This is a pretty bold statement which kind of conflicts with everything I think of OOP.

The reason stated was testability. It said that when writing unit tests, if a common logic is implemented in the base class, it will be tested multiple times for each concrete sub class and cannot be mocked out.

Question

Where or how can one implement a common logic for multiple sub classes so it can be easily mocked when they are being tested?

答:
Absolute nonsense.

A few thoughts:

You should not take OOP and it's principles too seriously. Many times functional or other software paradigms make more sense. Though the objects thing is cool... thinking in concrete components and all that.

Testing, and specifically Unit Testing is meant to serve the project, verify it's design, and assure its robustness not the other way around.

Composition is almost always better than inheritance

by the way, this principle also plays nicely with OOP, the huge OO
inheritance trees from the 90's were really just a bad
interpretation of OOP. I also suggest you look up the original Gang
of Four book on Design Patterns

To your question:

If several classes are essentially the same "thing" and they have a lot of common functionality you should make them inherit from the same class (assuming you are using an OO programming language of course...).

This in no way limits testability.

To test the parent class you create a subclass for the sake of the test (put it next to the tests class). this is exactly how the class is intended to be used, and what it's design dictates.

To test the children you can do two things:

The bad approach. this applies only to dynamic languages, C#, and maybe Java. you can create a Shim to pose as the supper-class and use it as a base class for the child.

Accept that the super-class is an essential part of what the sub-class is. By design. It must conform to behaviors defined in the supper class, and that you actually should test them together. A good example for these are the Strategy and Template Method design patterns. Now you can simply test the subclass as is. you also should refrain from testing the base class too much, because you already done it somewhere else.

ContentLicense: CC BY-SA 3.0

Title: Implementing common logic in base class


问:
Is it significantly costlier to fix a bug at the end of the project?
In a blog post by Andrew Hay, the following axiom was posited:

It costs significantly more to fix a bug at the end of the project that it does to fix the same bug earlier in the project.

However, this doesn't seem certain, especially after reading a blog post on Less Wrong, and the data I've seen to back it up is extremely old.

Is this still axiom accurate today?

答:
Sadly, like many things, it depends.

If a dialog message is misspelled, it may be 'trivial' to fix (update string, rebuild/package, redeploy). Or if a layout needs updating, a modification to a .css file may be sufficient.

If the bug is that the output of a critical method that has a 100+ page spec and proof is wrong, then the investigation itself may take hours or days. This is what the old 'axiom' refers to, and what, among other things, TDD and agile is trying to avoid (fail early and clearly, make safe incremental progress, yada).

From my recent experience with multi-scrum teams on a single project, the 'bugs' are usually merge/integration issues that only appear at the close of a release as feature branches are promoted to stable. These are the worst, as the conflicts often require cross team support while the teams are in a flurry to finish their own objectives, but I don't know that they are more expensive than other bugs, as they occur when they occur: late in the release, but at the earliest time they can. That's what makes them the worst.


问:
Peculiar architecture interfacing .NET to AutoCAD out-of-process
I have written a set of classes to interact with AutoCAD from an out-of-process .NET assembly, but it seems like my class architecture and interactions are unusual.  I am struggling to find a better way to design these.

Some background:

I am reading data from several thousand AutoCAD drawings, collecting data from bills of materials, title blocks, and other entities.  AutoCAD can be interfaced with from another process in several ways.  One way is to use the AutoCAD COM type library which marshals every call and is relatively slow (about 6 seconds per drawing).  A much faster way is to load a .NET dll into the AutoCAD process and execute the code there.  This .NET component exposes a COM interface (lets call it IAutoCADDataReader) which you can call from the outside world.  If you call a method on this interface, you can harvest the data and return an object that contains all your gathered data (call it IDomainObject).  This works well and takes about 200 ms (huge improvement) since the interaction with the AutoCAD database was all in-process and you only marshaled one complicated object at the very end.

The above part of the design I am happy with.  What bothers me is what I do with the IDomainObject when I get it back into my main .NET assembly.  It is of course a _COMObject that I can cast to a IDomainObject, but it does not really exist in my managed assembly, it is a stub or proxy.  When I read its data, it calls across the process boundary.  If AutoCAD gets shut down, I will get a RPC error.  I would really like this object to exist independently of its original source.  The natural solution is to clone it and discard the COM object.

Now, usually a Clone method is on the object itself.  This fits with SRP since who would know more about cloning than it would?  That is not a solution in this case since a Clone method on this IDomainObject interface would actually execute in the AutoCAD process and just give me another COM object.  So ignoring SRP, I wrote a private Clone function in the managed assembly that iterates over the various arrays and other data in the IDomainObject and returns a fully managed DomainObject (not an interface).  This new object can now exist independently of AutoCAD, can do whatever I want in the managed world and will not be subject to RPC errors.

I like the end result of this convoluted process since I ended up with what I wanted in a fairly fast manner, but I cannot help but think that this is a odd way to architect such a thing.  Do any of you have any suggestions on how this design can be refactored to make it less peculiar?

Another criticism that could be leveled at this type of cloning is that it fails the Open/Closed principle.  If I extend any of the subtypes within the IDomainObject, the clone operation will no longer be correct.  I would have to update this private clone function at that time.  This really just shows how this solution works for now, but it violates several principles that will probably bite me as this project continues to evolve.  As a developer of in-company software, this stuff will be used and evolved for years and it would not be good to have these bad practices at the beginning.

答:
A relatively simple and generic method to pass .NET objects over process boundaries is to use serialization. Make sure your DomainObject is serializable, then you can implement your Clone method by serializing your object to a memory stream, and deserialize it from there within you main component out-of-process.

We used that in conjunction with memory mapped files as a form of IPC to pass a complex object hierarchy, but I am pretty sure that will work in your situation as well without this additional technical detail (and if not: convert the memory stream to a string, then the COM mechanics for passing strings between processes can be applied). This solves exactly the problems you described above: you do not need to write any code for iterating over your internal arrays (the .NET serialization "magic" will do that for you), and when extending your subtypes, there is nothing to change in your clone method.


问:
Using exceptions as regular objects
I have views that handle different errors in my application. For example error 404, 403 and such, giving my errors a more user-friendly presentation. By assumption, they get passed in an exception, so this is what an example error-handling view looks like:

```<code><h1>Whooops! An error with code <?=$exception->getCode()?> has occurred.</h1>
<p><?=$exception->getMessage()?></p>
</code>```

But somewhere along the lines I met a need to display a certain error view as only a part of a page, so I decided why not do this

```<code>// somewhere in another view
echo $errorView->render(new \Exception('Message', 403));
</code>```

My question is whether in my particular case it is a good programming practice to be throwing exceptions? Or should I handle it differently than how I am handling it now?

答:
You've got a situation where an exception occurs for some reason or another. There's really no point going on and you need to start bailing out and rendering the corresponding web error page (this is a web application after all).

Now, to present some information to the end user, you need to somehow get some data to that error page.  And to that extent, an exception is a good place to put that data.

Other options are convoluted where one tries to stuff the data in a session context or somewhere that is 'anywhere but the exception'.  But why not the exception?  It can hold data (be it a message or the type of the exception or any other data that it is wrapping in other situations) and it is present when you are rendering the final response.

Using the exception to hold this data is the perfect place to put such information. It keeps it together, it makes it available to the parts of the application that need it and it clearly shows its intent and responsibility.

Should error pages only take exceptions? That is a bit of a trickier question. And that, it feels a bit awkward in that you are creating an exception object, but not throwing it and instead passing it as an argument. And that has some 'icky' feeling to it, but could be necessary for other parts of the application that aren't presented here.

Other parts of the application may behave specially when exceptions start floating around (like loggers or other cross cutting aspects taking action when an exception is created). But, again, without further information about the architecture this is pure speculation.

I would be tempted to make an interface of an Error (note that this is kind of hand wavy here and may not be applicable to all language paradigms).  Then have a specific exception type implement this interface... along with a non-exception object implementing it too.  Then have the Error object be sent to the rendering page.  This would allow one to create an ErrorException when needed, but also just creating an Error when you don't need an exception.

Title: Using exceptions as regular objects


问:
Object Storage where Object Type is variable
From time to time, we come across a problem where we must store an object, but we don't know in advance what kind of object we're going to store. I'm going to give a very simple example.

Requirement: All questions have answers. All answers have at least one part. Some answers have more than one part.

We're going to focus on how to store and retrieve multi-part answers. We want our view or possibly our controller to behave differently depending on whether the answer has one part or many parts.

Conceptually (without object storage) we might write the following:

Data Model:

```<code>class Answer
    Wording (string or Array of strings)
</code>```

Controller:

```<code>if ourAnswer.wording instanceof String:
    doSomethingWith(ourAnswer)
else
    foreach (answerPart in ourAnswer.wording)
        doSomethingElseWith(answerPart)
</code>```

So I think that would be the simplest possible way you could meet that functionality, but I'm not aware of any database that will let us store our objects like that, except maybe JSON. (No POJOs presumably because of static type checking.)

I'm actually using Node.js and Javascript with a NoSQL database here which is why I can get away in my pseudocode with not caring at compile time about whether my Answer.wording is a string or Array. But this is a very common problem when I've been using Java as well and I've not yet found the most elegant solution. For example, imagine trying to write that out in Java. We'd probably do:

```<code>public interface Answer {
    public String getAnswer();
}
public class SingleAnswer implements Answer {
    private String wording;
    public String getAnswer() {
         return this.wording;
    }
}
public class MultipartAnswer implements Answer {
    private String[] wording;
    public String getAnswer() {
         return doSomethingWithThisArray(this.wording);
    }
}
</code>```

... and of course that raises all kinds of weird issues with separation of concerns -- how do we know our Multipart Answer will do the right thing with its array, for example? What if we need to work with the array directly? And so on.

Well these are all implementational issues which we can fix. I'm really interested in the best practice for a language like Javascript where we can't use a hierarchy of objects and specificly, their storage in something like an NoSQL database or even worse, an actual SQL database. This problem is the kind of thing which pops up all the time for me with the LAMP stack.

There may be a simple solution for this specific example: we could assume ALL answers are multi-part answers, some of which have an answerPart array length of 1. Nice, simple, clear, easy and that is in fact what I ended up doing. But what if it isn't so simple and we really don't know what kind of thing we want to store, only that it is one of a finite set of well-defined things? What if our objects are preferredColour objects of either a centipede's shoes (16) or a car's wheels (4, different functionality from whatever it is the centipede's shoes do)?

Too contrived you say? Here's another real-world example I dealt with a few years ago.

Requirement: Ask the user if they suffer from a heart condition. If they do, they must give details of that condition.

Since I was using the LAMP stack, the easiest way to store that was in a database column named heart_condition_details, which may be null. In checks where has_heart_condition?() mattered we could simply return the whether heart_condition_details was null or not. Unfortunately, the framework I was using (cakephp) wouldn't allow me to extend the data model like that, with a boolean type has_heart_condition predicated upon whether heart_condition_details was empty.

In the end, I used separate columns for varchar heart_condition_details and boolean has_heart_condition. To this day, I think, I still regret it.

答:
But what if it isn't so simple and we really don't know what kind of thing we want to store, only that it is one of a finite set of well-defined things?

This is precisely what a tagged union is for. You can emulate them in Java using an abstract base class with a private constructor, and final inner subclasses. The inner subclasses can use the private constructor, but non-inner classes can't, so you end up with a finite number of subclasses (which can't be extended further because they're final).

```<code>public abstract class Answer {
    private Answer() { /* Prevent outside inheritance */ }

    public static final class SingleAnswer extends Answer {
        public final String answer;
        public SingleAnswer(String answer) { this.answer = answer; }
    }

    public static final class MultiPartAnswer extends Answer {
        public final String[] parts;
        public MultiPartAnswer(String[] parts) { this.parts = parts; }
    }
}
</code>```

(And of course you can add getters and properly format the braces.)

You can then branch on the kind of Answer in a type safe/foolproof way using the Visitor pattern, or if you have access to Java 8 you could accept two lambdas instead of a visitor, which would be much less boilerplate-heavy than creating anonymous objects.

Body:
But what if it isn't so simple and we really don't know what kind of thing we want to store, only that it is one of a finite set of well-defined things?

This is precisely what a tagged union is for. You can emulate them in Java using an abstract base class with a private constructor, and final inner subclasses. The inner subclasses can use the private constructor, but non-inner classes can't, so you end up with a finite number of subclasses (which can't be extended further because they're final).

public abstract class Answer {
    private Answer() { /* Prevent outside inheritance */ }

    public static final class SingleAnswer extends Answer {
        public final String answer;
        public SingleAnswer(String answer) { this.answer = answer; }
    }

    public static final class MultiPartAnswer extends Answer {
        public final String[] parts;
        public MultiPartAnswer(String[] parts) { this.parts = parts; }
    }
}

(And of course you can add getters and properly format the braces.)

You can then branch on the kind of Answer in a type safe/foolproof way using the Visitor pattern, or if you have access to Java 8 you could accept two lambdas instead of a visitor, which would be much less boilerplate-heavy than creating anonymous objects.


问:
Static functions vs classes
Let's say that I want to build some utility functions to do some basic maths with the BigDecimals, for example I want to have a function that computes the average of a List<BigDecimal>.

What is the best approach? A static function or a utility class?

```<code>public static BigDecimal computeAverage(List<BigDecimal> numbers)
</code>```

or

```<code>public class BigDecimalUtil

public computeAverage(List<BigDecimal> numbers)
</code>```

答:
How about a CalcAverageStrategy interface that is injected, and you can then have mean/median/mode implementations injected where necessary.

Each implementation is easy to test, and also easy to mock for testing.

Title: Static functions vs classes


问:
Clojure NameSpace Design
I am new to Clojure and trying to get a handle on organizing a project's namespaces. I am working on a solver for the knapsack problem. Currently, I have broken the modules into files, but everything lives in one namespace: my-project-name.core. I  am using load to manage access across files and it seems like a bit of a kludge. I've drawn a digram of how I think I want the various parts to interface:

My goal is to be able to work on each of the nodes in the diagram independently. I am trying to come up with a strategy for rational namespace design somewhere between everything in one and each in its own.

In particular I want to be able to swap out the solver and estimating components since these are the most tunable.

答:
bbatsov/clojure-style-guide suggests some good rules on how to use namespaces:

Use one namespace per file.

Use the ns form for representing namespace dependencies. You should almost never need to use load in regular code.

Prefer :require :as instead of :refer or :use. This makes it easier to see what you are using from which namespace, and your code ends up being easier to understand.

As for swapping out components, this is typically better solved using protocols or multimethods than namespaces.

Title: Clojure NameSpace Design


问:
What is a simple, correct and secure way of executing code stored in database?, that is also sandboxed
Webhooks can be a very powerful thing when you try to automate or integrate software, however, handling their deployment in a controlled environment can suck in terms of security and deployment alone.

I need a way of allowing anybody in the company —anybody that can be trusted with API access, that is— to be able to create, deploy, use (and perhaps even share) webhooks without requiring access to a server.

I have thought that a way of doing this is to create a small application that can store, route and run scripts. The best way I can think to implement such a thing is by taking code stored in a database and creating a temporary file to then run a system command for the given language.

However, I think there would be nothing that would prevent that code from, say, shutting down the machine, downloading and executing external dangerous code, etc.

Then I thought about Linux containers, but I would preferably want a portable solution. I looked for an equivalent in Windows and apparently the technology does not exist yet:

http://www.theregister.co.uk/2014/10/16/windows_containers_deep_dive/
http://www.theregister.co.uk/2014/11/18/windows_docker_client/

Is there a simpler approach that can still be regarded as secure?, I would want to at least be able to execute php, python, ssj and shell scripts.

P.S.: Free downvotes for whoever suggests PHP eval

答:
What it sounds to me like you are describing is what package managers do: they take files from a repository, copy them to the target machine, and run scripts within them. This is usually done for the purpose of installation of software, but it doesn't have to be, so long as you are OK with their idempotency. They typically use a remote filesystem full of compressed archive files instead of a database for the repository, but that's really just an implementation detail.

What it sounds like you want beyond this is safety and portability. As you mention, safety is best achieved with containers or virtual machines. You are correct to note that there is nothing preventing, say, a Debian package's postinst script from running rm -rf / as root. You are also correct that Docker is a great example of containers, but it requires all applications it manages to be 'dockerized'. Portability is a bit trickier, as some software is inherently portable (like basic web services), while other is not (like performance monitors), and some platforms support containers better than others.

It sounds like you would want something that creates a generic container and then installs/runs arbitrary code within it. To achieve this, you could create the container yourself by setting up chroots, cgroups, etc., but it might be easier to let Docker do most of the work for you: In your database (or whatever repository you choose), store the script, a command to invoke it, a base Docker image, and whatever interpreter dependencies you need. For convenience, all this could be stored under a simple identifier. You then write a script that pulls down the needed files and data and builds a Docker container on the fly and then runs it. Docker provides primitives for copying files from host to guest, and specifying the command to invoke when the container starts up.

Admittedly, since Windows doesn't yet support containers compatible with Docker, you might need to do something different there. I've been away from Windows for some time now, but I recall it has a lot of support for access control lists and other security features with which you (or someone) could create something like a container. Sorry I can't give you more here. When Windows eventually supports proper containers, your repository might need to have custom base Docker images for Windows and Linux, for example, which could be selected automatically at runtime by your master script.


问:
Micro-services and data replication
I am building a new application and was reading about micro-services architecture. The architecture itself makes lot of sense from a development, deployment and life cycle management point of view. However, one issue that came up was with regards to how to handle master data.

For example, I have 2 apps: say Sales app and a Ticketing app. Assume that both of these apps are built as independent micro-services. However both of these apps, when deployed (assuming that they are deployed separately say Sales uses MongoDB and Ticketing uses MariaDB), would need to have access to the same master data instances e.g. Accounts, Products. This would mean that there would be an owner app for a given master data entity (e.g. for Accounts it might be the Sales app) and an interested party (e.g. Ticketing app would need to have information about Accounts).

There are multiple ways in which this can be achieved:

Data replication from master to interested party

Synchronous read from interested party to master (sync dependency is not recommended by the micro-services architecture paradigm)

Own centralized repository

Also even within Accounts, there can be a core part which is common for both Sales and Ticketing (e.g. account name, address etc.). However some aspects of the Account might ONLY be relevant for Sales and others ONLY relevant for Ticketing.

Any thoughts / best-practices / opinions regarding any of the above mentioned options ?

答:
would need to have access to the same master data instances e.g.
  Accounts, Products

Not the same. Each micro service should do their own mapping for Accounts, Products, etc. We are assuming that each micro service will have a different way to work with the entities.

In Domain Driven Design this is common, where each bounded context (in the same app!) can map the same entity in a different way.

If you need more information, I recommend the book Building Microservices:
Designing Fine-Grained Systems

ContentLicense: CC BY-SA 4.0

Title: Micro-services and data replication


问:
What's the best way to handle slightly different exceptions?
My code right now looks something like this:

```<code>void throw_illegal_part_of_input_exception(char c) {}
void throw_invalid_input_length_exception(int position, int length) {}
void throw_invalid_subinput_length_exception(int position, int length, bool is_greater) {}
// Some other similar functions

// ... do some stuff inside a function
if (errorCondition1) {
    throw_invalid_character_exception(c);
} else if (errorCondition2) {
    throw_invalid_input_length_exception(position, length);
} // etcetera
</code>```

The content of the functions is largely the same; however, the error messages I want to use in the thrown exceptions are very different and depend on the arguments. Is there a better way to write this?

答: Looks like classic polymorphism.  Could you create an exception object that you can inherit variations like this from?</p>


答:
Whats wrong with:

```<code>// ... do some stuff inside a function
if (errorCondition1) {
    sprintf(gmsg,"Invalid character %c at %d",echar,epos)
    throw_general_exception(gmsg);
} else if (errorCondition2) {
    sprintf(gmsg,"Wrong length record position %d length %d",position,length)
    throw_general_exception(gmsg);
} // etcetera
</code>```

Unless you want to handle one of the errors in a completely different way having specific exceptions for each possible error is just lots of work for little reward.

Title: What's the best way to handle slightly different exceptions?

Body:
My code right now looks something like this:

```<code>void throw_illegal_part_of_input_exception(char c) {}
void throw_invalid_input_length_exception(int position, int length) {}
void throw_invalid_subinput_length_exception(int position, int length, bool is_greater) {}
// Some other similar functions

// ... do some stuff inside a function
if (errorCondition1) {
    throw_invalid_character_exception(c);
} else if (errorCondition2) {
    throw_invalid_input_length_exception(position, length);
} // etcetera
</code>```

The content of the functions is largely the same; however, the error messages I want to use in the thrown exceptions are very different and depend on the arguments. Is there a better way to write this?

Body:
Whats wrong with:

// ... do some stuff inside a function
if (errorCondition1) {
    sprintf(gmsg,"Invalid character %c at %d",echar,epos)
    throw_general_exception(gmsg);
} else if (errorCondition2) {
    sprintf(gmsg,"Wrong length record position %d length %d",position,length)
    throw_general_exception(gmsg);
} // etcetera

Unless you want to handle one of the errors in a completely different way having specific exceptions for each possible error is just lots of work for little reward.


问:
Beginner Decorator Pattern Question
I came across this article: http://sourcemaking.com/design_patterns/decorator

After reading it, I am having a little bit of difficulty understanding a concept. If you look in the Structure section in that article when it shows the UML class diagram, I am confused on why the Option Wrapper class extends the Interface class but the Option Wrapper class has an instance (composition) of the Interface class as well. Why are both of these relationships needed to in order to accomplish what the Decorator Pattern hopes to do? In other words, why is neither relationship good enough by its self?

答:
Decorators usually augment the original functionality in some way, not replace it altogether.  So they need to hold a reference to the original object.  For example, a decorator that adds memoization to a function will need to be able to call the original function if its result is not found in the cache.

However, the calling code should not need to know if it's working with a decorated  class or the original class.  That means the decorator needs to implement the same interface as what it decorates.

Title: Beginner Decorator Pattern Question


答: You're making this too complicated.  Just throw an InputValidationException, and find a way for the exception to carry some additional information (this could be as simple as an error message), so that you can identify the input validation error specifically.


问:
What makes Python more used as an implementation language than the others?
Perl and Python are often compared to each other (let's not forget Ruby), and almost always those discussions will come to the conclusion pretty much anything you can do in one or the other.

Without going into that, I've noticed that Python however, is often used as an implementation language (uhmm, maybe the term here is incorrect technically - a language you use to, for example, enable some degree of scripting in a large application ... Tecplot, Rhinoceros etc.; these are from the scientific area; there are others surely) and Perl never (well, to my knowledge at least).

So I was wondering - what makes Python more suitable for something like that? What particulars make a language more suitable to be implemented as part of a larger app. for scripting in general? Is it only that that wasn't so common 10 years ago (scripting in applications), and Python is just at its peak at the moment, ... or something else?

答:
If you're talking specifically about application scripting, it may simply be that Python is more approachable than Perl to a casual programmer, and thus the developer of the application decides Python would be a better experience for the application's users.  Lets face it, Perl, while powerful, can be... cryptic... at times.

VBScript is also used a lot in Windows applications for this reason.  Its something end users, not programmers, can cobble a small script together in without too much trouble.

ContentLicense: CC BY-SA 2.5


问:
Is storing data that rarely changes in-memory a good candidate for a singleton/cache?
I have a class called DataPoint that is defined like the following. Currently, it goes through each property on an object and based on the DataPoint, it does some formatting like padding, trimming, etc... before it will save the record to the database.  The current implementation makes a database call for each property which is slow, so my first step is to get everything at once into an in-memory collection.  What else can I do below?  Is this a good candidate for a singleton since the data rarely changes and/or is it possible to cache it (if so, how)?

```<code>public class DataPoint
{
    public string Name {get;set;}
    public string Justification {get;set;}
    public int MaxLength {get;set;}
    public string Format {get;set;}

    public DataPoint GetDataPoint(string name)
    {
        var dataPoint =
            db.Query<DataPoint>("SELECT * FROM DataPoint WHERE name = @name", new {name}).FirstOrDefault();

        return dataPoint;
    }

    public T FormatObj<T>(T obj)
    {
        foreach (var propertyInfo in typeof(T).GetProperties())
        {
            var dataPoint = GetDataPoint(propertyInfo.Name);

            //Do formatting on obj Properties such as setting values, etc...
        }

        return obj;
    }

}
</code>```

答:
You can use Memory Cache. I use memory cache to cache data rarely changes or at the specific time.

Here is example:

```<code>public static T GetCache<T>(string key, Func<T> initializer) where T : new() {
    if (!MemoryCache.Default.Contains(key)) {
        try {
            T data = initializer();
            AddData(key, data);
            return (T)MemoryCache.Default[key];
        } catch (Exception ex) {
            LogHelper.WriteError(MethodBase.GetCurrentMethod(), ex);
            return default(T);
        }
    }
    return (T)MemoryCache.Default[key];
}

public static void AddData(string key, object data) {
    if (data == null) {
        return;
    }
    var cacheTime = int.Parse(ConfigurationManager.AppSettings["CachingExpiredTime"]);
    AddData(key, data, cacheTime);
}

private static void AddData(string key, object data, int cacheMinute) {
    if (data == null) {
        return;
    }
    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(cacheMinute) };
    MemoryCache.Default.Add(new CacheItem(key, data), policy);
}
</code>```

Body:
You can use Memory Cache. I use memory cache to cache data rarely changes or at the specific time.

Here is example:

public static T GetCache<T>(string key, Func<T> initializer) where T : new() {
    if (!MemoryCache.Default.Contains(key)) {
        try {
            T data = initializer();
            AddData(key, data);
            return (T)MemoryCache.Default[key];
        } catch (Exception ex) {
            LogHelper.WriteError(MethodBase.GetCurrentMethod(), ex);
            return default(T);
        }
    }
    return (T)MemoryCache.Default[key];
}

public static void AddData(string key, object data) {
    if (data == null) {
        return;
    }
    var cacheTime = int.Parse(ConfigurationManager.AppSettings["CachingExpiredTime"]);
    AddData(key, data, cacheTime);
}

private static void AddData(string key, object data, int cacheMinute) {
    if (data == null) {
        return;
    }
    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(cacheMinute) };
    MemoryCache.Default.Add(new CacheItem(key, data), policy);
}


答:
I would say no. A singleton is rarely the answer. If you dont believe do a quick search on singleton anti pattern. The main problem being that it is hard to unit test code which uses a singleton.

A much more flexible approach is the inversion of control pattern. Basically you would would just make the class that would use your cache depend a IDataPoint instance in the constructor and then it is up the to calling point to decide how to create or reuse and which implementation of IDataPoint it wishes to provide.

Title: Is storing data that rarely changes in-memory a good candidate for a singleton/cache?

Body:
I have a class called DataPoint that is defined like the following. Currently, it goes through each property on an object and based on the DataPoint, it does some formatting like padding, trimming, etc... before it will save the record to the database.  The current implementation makes a database call for each property which is slow, so my first step is to get everything at once into an in-memory collection.  What else can I do below?  Is this a good candidate for a singleton since the data rarely changes and/or is it possible to cache it (if so, how)?

```<code>public class DataPoint
{
    public string Name {get;set;}
    public string Justification {get;set;}
    public int MaxLength {get;set;}
    public string Format {get;set;}

    public DataPoint GetDataPoint(string name)
    {
        var dataPoint =
            db.Query<DataPoint>("SELECT * FROM DataPoint WHERE name = @name", new {name}).FirstOrDefault();

        return dataPoint;
    }

    public T FormatObj<T>(T obj)
    {
        foreach (var propertyInfo in typeof(T).GetProperties())
        {
            var dataPoint = GetDataPoint(propertyInfo.Name);

            //Do formatting on obj Properties such as setting values, etc...
        }

        return obj;
    }

}
</code>```


问:
Any good data structure to perform efficient lookup and modification operations about what are the shapes containing the current cursor position
I think I'm facing a pretty common issue but cannot remember which solution is the most suitable one.

Let's put it that way: I can, in a, certain, given, language get some events anytime the user is moving the mouse. I therefore get the position the current cursor position in let's say in absolute coordinates based system.

Now considering that this system is also capable of containing up to thousands of thousands of shape objects (with a certain location point and size).
In a first rough approximation, we can think about them as their related bounding boxes in order to make the lookup operation and classification a bit more simpler, let's also add another simplification by omitting the fact that shapes can overlap each other.

What can be the best data structures to retrieve the shape(s) under the cursor position and allow relative fast insertion / deletion / modification operations?

Thanks,

ps: I was thinking about some sort of sorted trees but I think they are pretty demanding when it comes about maintaining their internal sort.

Additional curiosity: how it works in Winforms? I mean the Control class in the .NET Framework is related to the underlying HWANDLE in windows and capable of firing events when cursor is entering or leaving a Control. I do not really think that there is a thread allocated to perform some dummy hit tests... and trigger the related events.

答:
if space is not of concern and your application can afford to use as many space as you want, I'm thinking of 3-dimensional array (or to be more precise, 2-dimensional array of list) structure
2-dimensional array will represent the screen. Each pixel is an element in the array. Each location in array contains a pointer to a list of shape identifier

e.g. there are 2 shapes with id 4, 5 at location {10, 12}, so the element {10, 12} of the 2-dimensional array contains a list of 2 elements (4 and 5). Please note that shape id is a number that uniquely identify that shape instance. Even if 2 shapes are both square, they will have different shape id

To find at a specific mouse location, what shapes are present, just need 1 array lookup + list travel to get all shapes at that location

To insert: it will depend on how big is the shape, will need to go through all the pixels in the shape, add that shape id into the structure

To delete: for faster delete, I think can keep a lookup that has key is shape id, value is location of one pixel within that shape. when you want to delete the shape, look up the location of the pixel based on shape id, then use flood fill algorithm to remove the shape id from the structure

I hope I describe it well, here's an example of the 3x3 array. There are 2 squares of size 2x2 in the array with id 1, 2. THese 2 squares overlapping in the middle of the array

[1] - [ 1 ] - []

[1] - [1,2] - [2]

[]  - [ 2 ] - [2]


答:
Just think of a decorator as having 2 functions:

adds/modifies the functionality of the original class. In order to do so, it needs to have reference to the original class, and therefore need to have composition.

look the same as original class to the client. By look the same, I mean from the client's perspective, they will not know and don't need to know which class is decorator, which class is original class. In order to look the same, it needs to offer the same set of public functionality from the same contract like original class. That's why it needs inheritance

Title: Beginner Decorator Pattern Question

Body:
I came across this article: http://sourcemaking.com/design_patterns/decorator

After reading it, I am having a little bit of difficulty understanding a concept. If you look in the Structure section in that article when it shows the UML class diagram, I am confused on why the Option Wrapper class extends the Interface class but the Option Wrapper class has an instance (composition) of the Interface class as well. Why are both of these relationships needed to in order to accomplish what the Decorator Pattern hopes to do? In other words, why is neither relationship good enough by its self?


问:
Development Time: sql in UI code vs domain model with datamapper
First, sorry for my English guys.

Currently this is my first programming job. I am labeled as the most incompetent programmer in my company that's because they measure the performance and productivity of programmer by how fast you can get things done. I'm not really sure if I'm slow or not, because I always test(manual testing) my code before submitting it, and I'm pretty sure that most programmers here don't test their code the way I test mine. I don't do automated test because I admit that the concept is still complex to me. Since our software is not yet use by the user, we don't know which programmer has the most or fewer bugs. And also the system is for internal use only, so we don't have strict deadline. Time to ship is not that important.

We don't have best practices, automated testing, code reviews, and coding standard here in the company, so basically you are on your own, just make the code works and your fine. Almost all of the programmers here are fresh from college. Even me I'm a fresh graduate.

I think the reason why they are fast it's because they do all of the business logic in sql. So Basically they have all the UI code and Sql code in one .aspx file just like the code below

```<code>Patial class InvoiceView : Page
{
    protected void button_click(object sender, Eventargs a)
    {
     string sql = "Select * from some blah blah blah";
     DataTable tab = .....some Ado.net code here.
     Gridview.DataSouce = Tab;
     Gridview.DataBind();
    }
}
</code>```

Before I got my first job(although this is my first job), I don't code like this anymore I usually use a custom object just like the code below.

```<code>Public class Invoice
{
     public int InvoiceNo {get;set;}
     Public DateTime PaidDate {get;set;}
     Public List<Item> Items {get;set;}
     public decimal Amount {
     get
        {
         decimal amount = 0;
         foreach(var i in Items)
         {
            amount = amount + i.TotalPrice;
         }
         return amount;
        }
    }
}
</code>```

after that, I'm going to create a DataMapper class, and I'm pretty sure this is the reason why I'm slow, because I have to manually map the row table to objects and test the datamapper. So basically their is no ORM or micro ORM. Our database don't have referential integrety and tables always change. So I thought ORMs are not ideal for this project.

The person that labeled me as the most slowest is actually a junior programmer just like the rest. He has 2 years experience ahead of us, that's why he is our immediate superior. Sometimes I always think that the reason why he said that is because he is still a junior and no experience when it comes to managing a team of programmers.

I'm confident that I can do all the job they will throw at me.

Here is my question.

Should I use DataTable and shove it to gridview just like the rest of my team do?

When to use DataTable instead of custom objects or domain classes?

Currently I only know two Data Access pattern, ActiveRecord and DataMapper. What do    you call the pattern that my team uses?

How can I code faster?

Thanks guys, sorry for my English.

答:
Automated testing

Invest your time in automated testing. It will pay you off very quickly.

The basic idea is that if you do manual testing only, you'll be unable to handle the ever increasing number of tests. It is not unusual for even a relatively small application to have thousands of tests, not counting integration, system, functional, load and other tests. If this application is delivered daily, this means that you'll need to do thousands of tests by hand, every day. If it takes you more than 8 hours to run all of them, you won't have time to do anything else any longer.

Why running those thousands of tests in the first place?

Mostly to avoid regressions. When you write new code, no matter how much you thought about the consequences of the change, it may (and often will) break something else, somewhere else. If the architecture and the design are good, this will happen rarely and will affect only a few mostly related classes. If the architecture and the design are not so good, you can effectively change something in one place, and see features which look completely independent break.

Code

If you're convinced that your code is good and your coworker's code is less good, the time it takes to you to deliver features shouldn't be a concern. Once the product starts to be used by customers, they will report bugs. If your code is easy to maintain and have fewer bugs, your coworkers will spend most of their time correcting bugs, while you, on the other hand, will be delivering features, achieving a better score on the metric used in your company.

It might be (although it's not clear from your question, I don't think it's the case) that your coworker's code is fine, and yours' is over-architected. In this case, indeed, you are spending more time than needed by writing code which is unnecessary. Having your code being reviewed by your colleagues may give you a better image. If through the review, they achieve to simply and reduce it while keeping it maintainable, there is indeed a problem.

Tools

Make sure you know your tools. IDE, static checkers, code generators, whatever. For example, your Invoice class, aside Amount property could have been written automatically by a code generator. This may not make a huge difference for a single class, but if you have dozens of them, containing dozens of properties, code generators may have an impact.


答: Python is easy to embed in C programs and it is easy to add C modules to python.  Python has a lot of inroads in scientific computing with sci.py and numpy, so it is a natural fit for scientific apps.</p>

Title: What makes Python more used as an implementation language than the others?

Body:
Perl and Python are often compared to each other (let's not forget Ruby), and almost always those discussions will come to the conclusion pretty much anything you can do in one or the other.

Without going into that, I've noticed that Python however, is often used as an implementation language (uhmm, maybe the term here is incorrect technically - a language you use to, for example, enable some degree of scripting in a large application ... Tecplot, Rhinoceros etc.; these are from the scientific area; there are others surely) and Perl never (well, to my knowledge at least).

So I was wondering - what makes Python more suitable for something like that? What particulars make a language more suitable to be implemented as part of a larger app. for scripting in general? Is it only that that wasn't so common 10 years ago (scripting in applications), and Python is just at its peak at the moment, ... or something else?


答:
There is no real best way. There are some options:

Create an exception hierarchy with a class for each specific exception that all inherit from a common base class (the exception class you are using now for example). Each specific exception class then carries the details of the encountered error and can produce a human-readable message when the what() method gets called.

This option is particularly useful if you might want to differentiate between the different exceptions in your catch clauses.

Use a single exception type that gets filled with different messages at the throw point.

This is your current approach and is perfectly valid if you know beforehand that the calling code will never have a need to differentiate between the different kinds of errors.

If there is no need to have different exception types, then it comes down mostly to personal preference and agreements within the team which option to use. We can't advise in that.


问:
What's the best way to implement a real time show board to show results from concurrent result producers in Java?
I'm making a load test tool that launches multiple thread to simulate load on the target server. Each thread executes a predefined set of commands in the structure of TestSuite - TestCase- TestStep and each level returns results objects (of respective types). Each thread loops its predefined commands, so a series of TestSuite results are generated and it takes a while for all the loops to finish.

I'm trying to find the best way to show results generated in the still running threads. I've thought about a few possible ways:

Use BlockingQueue and producer - consumer pattern. This requires heavy concurrency programming and I haven't been very clear on how I should handle different levels of results - suite results, case results and step results.

Use a concurrent map to hold reference to results, and poll that map periodically to show what's available. This can be very inefficient. How do I just get the new results every time I poll?

Develop a custom Log4J logger, so I can add appenders which will receive results on-the-fly. I haven't researched on how much work is involved if I use this approach. Is it even possible? Considering the level of result types it needs to handle.

答:
This sounds like a pretty standard multi-threading problem which can be solved by well-established techniques.

My suggestion would be:

Set up a singleton class whose job in life is to log events. Synchronize the methods to ensure it is thread safe.

Have each test regularly call the thread-safe logger to do any logging work. Make sure that the logging message includes a thread ID.

As your logging class is thread-safe, you are free to attach whatever appenders suit.


问:
Examples of operating systems capable of serving http-requests that does not support direct slash for directory separator
My php framework uses DIRECORY_SEPARATOR constant instead of /. Can there be any other options for a directory separator?

答:
Of the popular software today there are only two different directory seperators: / and \ . Windows being the one using \ also happens to support / of all the api's and command line tools accepting a file path as argument.

I have often on windows used / as a seperator from both Java and .NET code and I have never experienced any trouble.

To answer your question. There are no examples of operating systems in use today that doesn't support / as directory seperator.


答:
On MacOS, the directory separator is :, on Windows, it is \, and on VMS, it is ..

MacOS is no longer in use, though. OSX uses /, but continues to support :. Windows largely supports /, although for some APIs, you must use \.

Title: Examples of operating systems capable of serving http-requests that does not support direct slash for directory separator

Body: My php framework uses DIRECORY_SEPARATOR constant instead of /. Can there be any other options for a directory separator?


答:
Should I use DataTable and shove it to gridview just like the rest of my team do?

Hell no. That's just bad code. It's ok code for very small uncomplicated projects that are unlikely to change and has a database schema that will rarely if ever change.  Or for quick one-off-projects. Otherwise that is bad code practice and it will come back and bite you in the ass later.

When to use DataTable instead of custom objects or domain classes?

Never. Or well, as said before. For very small one-off projects. Though even then I prefer to stay as far away from DataTable as possible and use Dapper or Massive or something similiar to not have to write code against DataTable.

Currently I only know two Data Access pattern, ActiveRecord and DataMapper. What do you call the pattern that my team uses?

"Maintenence hell" :)

How can I code faster?

From what you are telling, it's not you who should code faster, its your team who should code slower. Fast coding is good, but correct coding is better. If you code correctly, adhering to best practices and doing automated testing and so on you will get faster in the long run by minimizing maintenence nightmares and having a more stable system that will be easier to change later on. Going fast is good, but not if you go fast and then end up with a system that you cannot add new features to or maintain. Go as fast as possible without cutting corners. With time and experience, you'll find the correct pace where you can deliver correct code fast enough.

Title: Development Time: sql in UI code vs domain model with datamapper

Body:
First, sorry for my English guys.

Currently this is my first programming job. I am labeled as the most incompetent programmer in my company that's because they measure the performance and productivity of programmer by how fast you can get things done. I'm not really sure if I'm slow or not, because I always test(manual testing) my code before submitting it, and I'm pretty sure that most programmers here don't test their code the way I test mine. I don't do automated test because I admit that the concept is still complex to me. Since our software is not yet use by the user, we don't know which programmer has the most or fewer bugs. And also the system is for internal use only, so we don't have strict deadline. Time to ship is not that important.

We don't have best practices, automated testing, code reviews, and coding standard here in the company, so basically you are on your own, just make the code works and your fine. Almost all of the programmers here are fresh from college. Even me I'm a fresh graduate.

I think the reason why they are fast it's because they do all of the business logic in sql. So Basically they have all the UI code and Sql code in one .aspx file just like the code below

```<code>Patial class InvoiceView : Page
{
    protected void button_click(object sender, Eventargs a)
    {
     string sql = "Select * from some blah blah blah";
     DataTable tab = .....some Ado.net code here.
     Gridview.DataSouce = Tab;
     Gridview.DataBind();
    }
}
</code>```

Before I got my first job(although this is my first job), I don't code like this anymore I usually use a custom object just like the code below.

```<code>Public class Invoice
{
     public int InvoiceNo {get;set;}
     Public DateTime PaidDate {get;set;}
     Public List<Item> Items {get;set;}
     public decimal Amount {
     get
        {
         decimal amount = 0;
         foreach(var i in Items)
         {
            amount = amount + i.TotalPrice;
         }
         return amount;
        }
    }
}
</code>```

after that, I'm going to create a DataMapper class, and I'm pretty sure this is the reason why I'm slow, because I have to manually map the row table to objects and test the datamapper. So basically their is no ORM or micro ORM. Our database don't have referential integrety and tables always change. So I thought ORMs are not ideal for this project.

The person that labeled me as the most slowest is actually a junior programmer just like the rest. He has 2 years experience ahead of us, that's why he is our immediate superior. Sometimes I always think that the reason why he said that is because he is still a junior and no experience when it comes to managing a team of programmers.

I'm confident that I can do all the job they will throw at me.

Here is my question.

Should I use DataTable and shove it to gridview just like the rest of my team do?

When to use DataTable instead of custom objects or domain classes?

Currently I only know two Data Access pattern, ActiveRecord and DataMapper. What do    you call the pattern that my team uses?

How can I code faster?

Thanks guys, sorry for my English.


问:
When is it appropriate to map a DTO back to its Entity counterpart
From what I've read and implemented, DTO is the object that hold a subset of value from a Data model, in most cases these are immutable objects.

What about the case where I need to pass either new value or changes back to the database?

Should I work directly with the data model/actual entity from my DAL in my Presentation layer?

Or should I create a DTO that can be passed from the presentation layer to the business layer then convert it to an entity, then be updated in the DB via an ORM call. Is this writing too much code? I'm assuming that this is needed if the presentation layer has no concept of the data model. If we are going with this approach, should I fetch the object again at the BLL layer before committing the change?

答:
If your presentation layer is always co-located with your Data Access Layer (DAL), which is often the case for server driven web apps (or standalone GUIs), you should typically not need a DTO layer: just use the entities directly.

If your presentaion layer can be remote, then DTO is a good idea. And, yes, a DTO can be used inbound as well as outbound, i.e. you send out DTOs and receive DTOs as input to update your persistent model through the DAL.

However, modern frameworks have largely obviated explicit DTOs. A good server MVC framework (e.g. Spring-MVC/web for Java) allows you to work with entity classes (from DAL) directly in your top-level APIs (e.g. REST interface) and do marshalling/unmarshalling to/from JSON or XML transparently. You don't give enough detail about your application, so your mileage may vary. If you're using some language-specific RPC mechanism (e.g. Java RMI) you might still want to hide your entity model from the outside world with a DTO layer.


答:
If you have an entity as in a DDD-entity (not what is generally called an entity in frameworks such as entity framework) then the entity should protect its invariants. Thus using the entity as a DTO is most likely wrong. A DTO is unvalidated input data from the user and should be treated as such. An entity is validated data in one of the object types valid invariants. Thus you should have a conversion between a DTO and an entity that converts a validated DTO to a domain entity object.

In many cases people skimp on these by using anemic domain models (http://www.martinfowler.com/bliki/AnemicDomainModel.html) where the "entities" generally contain no logic and then they put all the invariant protection logic etc in external code (and thus need to check invariants all over the place). This can work, but imho it leads to bugs. But it's something that happens pretty much everywhere - especially since a lot of frameworks encourage this by making it super easy to write code this way. This is imho too bad since it leads to the easiest/fastest way of coding not being the one that leads to the best results (if you follow DDD that is)...

But it's also important to recognise that in many cases DDD might be overkill. If you are basically making a CRUD application (which in many cases you probably are) then DDD might be overkill for your domain. Of course this doesn't mean that you should throw away all the good ideas and just go into full-on "do-anything mode", but in some cases not caring about certain parts of DDD can be the correct choice to make. The hard trick here is, of course, to identify if your domain is complex enough to warrant DDD or if it's easy enough to not bite yourself in the ass by foregoing certain parts of it. :)

Title: When is it appropriate to map a DTO back to its Entity counterpart

Body:
From what I've read and implemented, DTO is the object that hold a subset of value from a Data model, in most cases these are immutable objects.

What about the case where I need to pass either new value or changes back to the database?

Should I work directly with the data model/actual entity from my DAL in my Presentation layer?

Or should I create a DTO that can be passed from the presentation layer to the business layer then convert it to an entity, then be updated in the DB via an ORM call. Is this writing too much code? I'm assuming that this is needed if the presentation layer has no concept of the data model. If we are going with this approach, should I fetch the object again at the BLL layer before committing the change?


问:
Who should write the Technical Design Document? The BA or the Developer?
I work as a Snr. BA in a large Manufacturing company and I've just implemented a new Requirements Management Process.

We have a large range of internal developers who in the past have never been asked to define solution via a Technical Design Document once they have received an approved Requirements documents. They normally just go ahead and code without any written reference of their solution or why it was chosen and any associated risks involved.

Now our release manager states that it should be the BA who writes the solution and Technical Design documents. I disagree as I believe it should come directly from the Developer, especially as there is an easy-to-complete TDD template.

I feel it's a waste of the BA's time to repeat and try to interpret a Developers solution and it runs the risk of misinterpreting the Developers solution. BA's aren't supposed to be THAT technical! :-)

In my experience it's been the Developer / Architect who writes it.

答:
Unless the BA is also an technical architect, they should concern themselves with the "what it does" not the "how it does it". As a result, the BA writes the requirements and the technical architect writes the solution, and the developer writes the code.

Sometimes (or quite often) these roles are shared by someone, so a dev could also be the architect of their own code, or could be an expert in an area writing the Tdd for a junior to develop. Occasionally the BA will also be the TA, but only if they come from a technical and not business background.

Where I work now, we have a technical design authority who takes the basic requirements from the business people and turned them into technical requirements (ie makes them sensible), the senior developers write a solution document saying how they intend to fulfil the requirements which the TDA reviews, then the developers code it all up. The technical requirements are also used by the test team to write their system tests.


问:
DataThread class that doesn't extend Thread, poor naming?
I created a DataThread class that doesn't extend a Thread, but has one as a member variable.

Favor composition over inheritance, is a rule that I heard of, but I am thinking that the name of the class should be change, as to not mislead.

Is this true?

答:
It's not true.

The name of a class is part of its public interface. The user of a public interface doesn't care how functionality is implemented, only that it is available. (Indeed, allowing the user to not care about the implementation is the entire point of writing a class.)

Therefore, as long as the class offers the kind of operation commonly present in a Thread class, it doesn't matter whether internally this is done via delegation or inheritance. If your class is a drop-in replacement for a thread, by all means call it a name with "thread" in it.


问:
Object creation: when should I expose a factory vs wrapping class?
I am having some problems trying to figure out when to use a factory or to wrapper class. This question is slightly geared towards C# I guess, so I'm not sure if this is the correct place to ask.

Say there is a library that exposes an interface called IStackExchangeClient, and multiple differing implementations of that interface (private implementations that clients will not know about), HttpStackExchangeClient, UdpStackExchangeClient.

We can allow the object creation of the interface through a factory, like StackExchangeClientFactory.Create(), or we can wrap it up in another class like StackExchangeClient that internally does the same thing, but simply proxies.

In the second instance, clients can write new StackExchangeClient() which feels much more natural to me. So my question is, when do I choose one or the other? What are some of the considerations that I should be taking in?

I've thought hard about it and I can't choose between one style or the other, but clearly some parts of the .NET framework use factories, and some parts don't, even when there are multiple underlying implementations of its interface.

Thank you!

答:
If you're using dependency injection then using the Factory Pattern hides the dependencies of the object you're creating from the consumer.  For instance:

```<code>class MyClass
{
    MyClass(IDependencyA dependencyA, IDependencyB dependency) { ... }
}
</code>```

If you want to create this directly, you do:

```<code>var myClass = new MyClass(dependencyA, dependencyB);
</code>```

That means your consuming class has to take dependencies on all the dependencies of what you're creating.  If MyClass has lots of dependencies, and is created lots of places, then having a MyClassFactory provides decoupling:

```<code>class MyClassConsumer
{
    private readonly IMyClassFactory factory;

    MyClassConsumer(IMyClassFactory factory)
    {
        this.factory = factory;
    }

    ...

    private void someMethod()
    {
        var myClass = this.factory.Create();
    }
}
</code>```

As you can see, MyClassConsumer is now totally decoupled from the dependencies of MyClass.  If the dependencies of MyClass change, you now only have to change the Factory implementation, and nothing else changes.

Consider this: any class that calls new is by definition a factory.  Trying to follow the Single Responsibility Principle means creating an object should be the responsibility of a Factory class, and it should be that class's only responsibility.

Body:
If you're using dependency injection then using the Factory Pattern hides the dependencies of the object you're creating from the consumer.  For instance:

class MyClass
{
    MyClass(IDependencyA dependencyA, IDependencyB dependency) { ... }
}

If you want to create this directly, you do:

var myClass = new MyClass(dependencyA, dependencyB);

That means your consuming class has to take dependencies on all the dependencies of what you're creating.  If MyClass has lots of dependencies, and is created lots of places, then having a MyClassFactory provides decoupling:

class MyClassConsumer
{
    private readonly IMyClassFactory factory;

    MyClassConsumer(IMyClassFactory factory)
    {
        this.factory = factory;
    }

    ...

    private void someMethod()
    {
        var myClass = this.factory.Create();
    }
}

As you can see, MyClassConsumer is now totally decoupled from the dependencies of MyClass.  If the dependencies of MyClass change, you now only have to change the Factory implementation, and nothing else changes.

Consider this: any class that calls new is by definition a factory.  Trying to follow the Single Responsibility Principle means creating an object should be the responsibility of a Factory class, and it should be that class's only responsibility.


问:
Can multiple CPU's / cores access the same RAM simultaneously?
This is what I guess would happen:

If two cores tried to access the same address in RAM, one would have to wait for the other to access the RAM.  The second time that each core would try to access the same address, they may still have that RAM cached, so they could access their respective caches simultaneously.

If two cores tried to access different addresses in the same RAM, one would have to wait for the other to access the RAM.

In other words, I would imagine that for RAM intensive programming tasks, multiprocessing won't help much unless it involved reading from the same address in RAM multiple times per core.

So, can multiple CPU's / cores access the same RAM simutaneously, or is what I'm saying correct?

答: Modern CPUs are physically tied to their external memory devices in order to obtain maximum data transfer bandwidth.  This is due to signal integrity requirements (trace length, termination, clock skew, etc) necessary to sustain the high transfer rates.  For example, on a multi-CPU motherboard, each CPU has a dedicated set of DIMM slots.  Regardless of what software programmers might think, one CPU cannot simply access external memory data of another CPU.  A system's memory management software, whether at the level of OS kernel, Hypervisor, data plane cores, or otherwise, handles inter-CPU memory data transfer.</p>


答:
You don't care about physical RAM, you care more about virtual memory and address space of processes or threads (all the threads of the same process share a common address space) in practice.

Of course if you are coding a multi-core operating system kernel, you care about RAM and cache coherence a big lot.

Most multi-core processors have some form of cache coherence mechanism. Details are processor specific. Since processor are using CPU caches, they sometimes behave as if several cores of the processor are accessing the same memory location simultaneously.

Recent standards of industrial languages like C11 or
C++11 have some (multi-thread aware) memory model.

Title: Can multiple CPU's / cores access the same RAM simultaneously?

Body:
This is what I guess would happen:

If two cores tried to access the same address in RAM, one would have to wait for the other to access the RAM.  The second time that each core would try to access the same address, they may still have that RAM cached, so they could access their respective caches simultaneously.

If two cores tried to access different addresses in the same RAM, one would have to wait for the other to access the RAM.

In other words, I would imagine that for RAM intensive programming tasks, multiprocessing won't help much unless it involved reading from the same address in RAM multiple times per core.

So, can multiple CPU's / cores access the same RAM simutaneously, or is what I'm saying correct?


答:
I'll go against the grain slightly from the advice of "keep coding good/slow" and "find a new job" that you'll be receiving in the other answers, in case neither of those options are desirable for you.

Here's the sad truth: Sometimes its better to write crappy code that conforms to the team's style than it is to write good code that goes against the grain. However, you will need to spend some time covering your own rear-end and reputation against the inevitable slew of bugs and maintentance issues that will arise when some other junior dev goes and changes the database schema and your apps break.

Your team's style is to have lots of Web Forms apps that each have a ton of sql in button click events and GridView bindings, without a lot of "middle tier" pieces like reusable data classes and structures. This makes it near impossible to do Unit Testing, however that does not mean you cannot test at all. What you will need to do is focus on how to do coded UI Integration tests for your own work.

I HIGHLY recommend the Canopy UI Testing Nuget package (PM> Install-Package canopy). Its an F#-based UI testing tool, but don't let the F# scare you off, its very easy to learn the basics of how to wire up tests, and it uses CSS-style selectors, which you probably already know (or can learn easily).

If I were you, I would perform this type of workflow for when you need to code a new (sloppy) Web Forms app fast:

1) Go ahead and wire up your Web Forms app as fast as you can, using the dirty sql-in-button-event style that your colleges use. Say what you will about it, it IS fast/easy to write apps with that style (long-term maintenance is a nightmare, but that's the culture your team has selected!)

2) Write a SQL script to populate your test database with a set of known values

3) Write the Canopy/Other UI tests to run your app according to the requirements (put in value X on page Y and display result Z). These will verify any computed values that get output to the screen, as well as ensuring that you don't get any Yellow Screens of Death. You could also do things like have hidden 'test' pages that do nothing but check the database tables for the expected schemas and throw errors if they change enough to break your app.

4) If necessary, write a final sql script to check any database values not checked by your UI tests.

Now, you can run these tests periodically, and if there's any errors that come through because Steve the Intern changed a table's schema without telling the team, then its CRYSTAL CLEAR that he did it, and its not the fault of your web app. In the environment you are in, covering your own ass is going to be critically important. The team already views you as slow, and its going to take you a LONG time to change their opinion, so you'll need to get coding fast before you can earn their respect/trust.


答:
At my current job, we have BAs who are more technically inclined than where I've worked before, but we still have never expected them to write technical design docs. Developers always wrote those, and then architects signed off on them.

In support of xmojmr's comment, though, I would point out that while we were very diligent about documentation during our waterfall era, we noticed some weaknesses with it:

Technical documentation was expected to be completed before development began. In reality, the best we could do was document an educated guess at the technical details, and revise it frequently as development progressed.

Much of what went into the document was boilerplate, and thus had little or no real meaning to anyone.

The intended audience for the technical document was the developers (anyone who would be maintaining the code down the road). In this regard, it was utterly useless. Someone who needed to fix a problem or tweak some output would find nothing of value in the tech doc. The kind of detail needed by maintainers lives in the code itself. If you try to beef up your tech docs to approach the level of detail present in the code, you'll not just duplicate effort, but the code and the doc will inevitably fall out of sync (probably before version 1 even ships).

When we switched to an agile workflow, we deliberately ditched technical documents, and nobody misses them. We adhere to the idea of "just enough documentation," which means if there are decisions that need to be written down, or sticking points that need to be explained, we have a wiki for that kind of thing. Some processes still have formal flow diagrams, because those are useful to the product owner. But shifting focus away from documentation and more toward fulfilling customer needs has made all of the stakeholders happier, and the product is actually more stable than ever.

Title: Who should write the Technical Design Document? The BA or the Developer?

Body:
I work as a Snr. BA in a large Manufacturing company and I've just implemented a new Requirements Management Process.

We have a large range of internal developers who in the past have never been asked to define solution via a Technical Design Document once they have received an approved Requirements documents. They normally just go ahead and code without any written reference of their solution or why it was chosen and any associated risks involved.

Now our release manager states that it should be the BA who writes the solution and Technical Design documents. I disagree as I believe it should come directly from the Developer, especially as there is an easy-to-complete TDD template.

I feel it's a waste of the BA's time to repeat and try to interpret a Developers solution and it runs the risk of misinterpreting the Developers solution. BA's aren't supposed to be THAT technical! :-)

In my experience it's been the Developer / Architect who writes it.


问:
Many small requests vs. few large requests (API Design)
I'm currently working on a project with an organization as follows:

Client - Gets data from the main server via REST api.

Server - Requests data from various other servers via third-party APIs

Third-party APIs - Services out of my control that provide data to the server (Reddit, Hackernews, Quora, etc.)

For the sake of argument, let's say the client first needs a list of items from each of the third-party APIs. From this list, an item will be chosen at which point the client needs to see the full content of the item as well as responses (i.e. comments) to the item. I'm trying to decide between three options:

A la Carte

In this approach, I would have 3 separate endpoints on my server: one to get the list of items, one to get the main content for an item, and one to get the responses of the item.

Pros: I never make more requests than I need to, requests should be small so generally they should be faster.

Cons: I have to make a lot of requests. After choosing an item from the list, the user may have to wait before seeing the main content and then wait even longer to see the responses

Server-side cache

In this request, I would make a single call to my server to "fetch" all the data for all sources. The data would then be cached on the server. The client would then have the same REST endpoints as before, except there wouldn't be much waiting between calls since my server already has the data and just has to feed it to the client.

Pros: Still easy to implement on the client side, but without the latency issues

Cons: A bit more involved server side, and the first call could take really really long.

Client-side cache

This scenario is similar to the previous one except the client only ever makes one request to the server: give me all of the data. From here it's the client's responsibility to save the data and use it appropriately.

Pros: Easy server implementation, very speedy after the first call

Cons: First call will be very slow, more complicated client-side implementation

I'm not sure which is the best approach, or if maybe I'm missing the obvious solution. Any advice would be greatly appreciated!

答:
I would (almost) discount option 3. Choosing between 1 and 2 depends on two things:

(A) how big the result of a single, total fetch is

(B) how much of the detail of the result the client/user will typically use in that session.

It's easy to make a decision if A and B are extremes:

If A is large and B is small, definitely go for option 1 (A la Carte).

If A is small and B is large, go for 2 (Server-side cache) or even 3 (Client-side cache).

For any other A/B (large/small) variations, you will have to apply discretion. I often provide both coarse and fine endpoints to cater for different use cases from different clients.


问:
Dynamic Code Evaluation in Java - Clever or Sloppy?
I am trying to create a flexible ACL framework in Java for my application.

Many ACL frameworks are built on a whitelist of rules, where a rule is in the form of owner:action:resource.  For example,

"JOHN can VIEW resource FOOBAR-1"

"MARY can VIEW resource FOOBAR-1"

"MARY can EDIT resource FOOBAR-1"

This is attractive because the rules can easily be serialized/persisted to a database.  But my application has complex business logic.  For example,

"All users in department 1 with over 5 years of seniority can VIEW resource FOOBAR-1, else not authorized"

"All users in department 2, if the date is after 03/15/2016, can VIEW resource FOOBAR-2, else not authorized"

Upon first thought, it would be a nightmare to devise a database schema that could handle infinitely complex rules such as these.  Therefore, it seems as though I would need to "bake" them into the compiled application, evaluate them for each user, and then produce owner:action:resource rules as a result of the evaluation.  I want to avoid baking the logic into the compiled application.

So, I was thinking of representing a rule in the form of predicate:action:resource, where the predicate is a boolean expression that determines whether a user is allowed.  The predicate would be a string of a JavaScript expression that could be evaluated by Java's Rhino engine.  For example,

return user.getDept() == 1 && user.seniority > 5;

In doing so, the predicates could easily be persisted to the database.

Is this clever?  Is this sloppy?  Is this gimmicky?  Is this over-engineered?  Is this safe (apparently, Java can sandbox the Rhino engine).

答:
Piping dynamic data into an interpreter of your implementation language is usually a bad idea, since it escalates the potential for data corruption into a potential for malicious application takeover. In other words, you are going out of your way to create a code injection vulnerability.

Your problem can be better solved by a rules engine or maybe a domain-specific language (DSL). Look those concepts up, there is no need to reinvent the wheel.


问:
Does code generation increase the code quality?
Arguing for code generation, I am looking for some examples of ways in which it increases code quality. To clarify what I mean by code generation, I can talk only about a project of mine:

We use XML files to describe entity relationships in our database schema, so they help us generate our ORM framework and HTML forms which can be used to add, delete, and modify entities.

To my mind, it increases code quality because human error is reduced. If something is implemented incorrectly, it is broken in the model, which is good because the error might appear sooner since more generated code is broken too.

Since I was asked for the definition of code quality, let me clarify this, what I meant is software quality.

Software Quality:
It is not one attribute but many, e.g. efficiency, modifiability, readability, correctness, robustness, comprehensibility, usability, portability etc. which impact on each other.

答:
I totally agree with those who say that code generation is fine as long as you never have to edit (preferably, never have to look at) the generated code.

If we can accept that the generated code is approximately the same number of lines as hand written, and if we can say that it is bug free, then number of lines which might potentially contain bugs has decreased. Ergo, code quality ought to have increased.

Addendum: of course, other factors, such as execution time, may play a role.

Personally, I have written quite a few code generators, but never as an initial approach.

It has always been when I noticed a repetitive pattern in existing code, so my generator takes some existing code when adding new, but similar, code and parametrized some variable parts of it.

To that extent, my generated code is almost identical to existing hand-written code (except that it tends to better visually laid out and more uniform, which I find aids legibility, if it ever does have to be looked at).

Btw, I advocate inserting opening/closing comments which indicate that the code was generated, including details of the tool and its maintainer.


问:
Is Erlang really an actor model language?
I was reading this article:

http://www.doc.ic.ac.uk/~nd/surprise_97/journal/vol2/pjm2/

And it mentions that:

...in the actor model even an integer is represented as an actor...

Wikipedia confirms:

The Actor model adopts the philosophy that everything is an actor.

Erlang has many data types and those types are not actors as far as I can tell.

Doesn't it mean that Erlang is not an actor model language in a way some people say that e.g. Java is not a functional language just because it lacks certain functional programming features?

PS: by extension it means that Akka is definitely not an actor model because in addition to non-actor data types coming from the host language it even allows inheriting actors to extend their behavior via host language facilities.

答:
Although the Actor Model is older than Erlang, the designers of Erlang only learned about the Actor Model after having designed Erlang, so some differences are to be expected.

They followed parallel paths of evolution, though: the Actor Model was created by Carl Hewitt based on the message passing semantics of Smalltalk. Alan Kay, in turn had based the message passing semantics of Smalltalk on the goal-driven evaluation of PLANNER, which was designed by … Carl Hewitt.

PLANNER was the precursor to Prolog. Erlang was originally not intended to be a language, rather it started out as a library for fault-tolerant distributed programming in Prolog, and later evolved into a dialect of Prolog, before it became its own language, still to this day heavily influenced by Prolog (plus, the original Erlang interpreter was written in Prolog).

So, the similarities between Processes in Erlang, Objects in OO, and Actors in the Actor Model are far from coincidental.

Erlang is a language with several layers, each of which are supersets of the lower layers. The smallest layer is Functional Erlang. This is a standard functional language with some additions inherited from Prolog, such as unification instead of binding/equality. If we add Processes and Messages to that, we get Concurrent Erlang. Throw in remote processes, and you get Distributed Erlang. Now add some libraries and design patterns from the OTP, and you have fault-tolerant Erlang.

Processes are Actors. (They are also Objects.) The inside of Processes is Functional, not Actor-based. The structure of a large fault-tolerant Erlang system constructed using the tools and patterns of the OTP, is often very Object-Oriented.

So, it depends on what scale you are looking at.

In a typical large Erlang system, you have an object-oriented architecture with message-passing actors implemented using functional programming. What OTP calls a server is closely related to an object, servers are made up of processes (which are actors), processes use functions internally.

In general, I don't believe that any pure Actor Language has ever left research. Heck, I don't even know if Carl Hewitt's PLASMA, the original Actor Language was ever even implemented.


问:
What is a good speed for a webscraper?
I'm currently working on a webscraper that is going to be processing about 2 million pages in total. But I'm not entirely sure how to benchmark it.

Currently it processes about 100,000 pages in an hour at about 2mb/s.
It isn't saturating the the bandwidth of the server but I've tried a lot of ways to make it quicker but to no avail. CPU is running 50% or so on average.

答: That means you can get a fresh copy of every page roughly every day? Is that fast enough for you? If it's not, profile and improve.</p>

OwnerDisplayName: Fredrik

Title: What is a good speed for a webscraper?


答:
The response to this question is highly dependent on the organization of each company. As mentioned, the ideal is that the technical documents are written by the Software Analyst, after having discussed with the software developers/engineers of the project. However, when there is no Architect in the group, the workload has to be shared. In other words, why don't you stop considering writing the technical documents as a burden and start considering it as a perfect chance to obtain more technical knowledge ?

In my opinion, you cannot write this document on your own, because you lack significant technical background. However, neither the developer is fully capable of writing a well-structured technical document, since he misses other qualities. Even if the developer is really qualified and can write a perfect technical document, I think he will lose significant amount of time, that can be spent much more efficiently in the implementation phase.

So, I suggest that you write the technical document, after having multiple discussions with the Developer. In this way, there will be 2 benefits :
- You will acquire significant technical knowledge, e.g. around design patterns, protocols etc. This knowledge will be an important asset for your future.
- The project duration will be shorter, since the Developer will have more time for the implementation. And he will also appreciate you more ;)


问:
Is there some way to mark which branch is the latest in subversion?
We're reworking our process with subversion at the moment, and one of the things we're doing is making branches for each release target in our demo environment so that you can test a release that has been delayed independent of code that will be released separately. I am also experimenting with Jenkins in order to automatically run and report out on our unit tests in our demo environment. Is there some way in subversion to say "This branch is the release we're testing at the moment" such that Jenkins will check out that branch to test it? If not, how should I be approaching this issue? </p>

答: There doesn't seem to be. But Bamboo, which we're upgrading to from Jenkins, will automatically build and deploy a branch (any branch it finds) when it has activity. Set it up to do a clean deploy and you automatically have the tests run on the one that has activity, which by definition is the one we're testing currently. </p>


答:
This is a CI issue, not a SCM one. In Jenkins I assume you have a set of jobs that are looking at a particular SVN URL (eg trunk). You can edit these to point to a different url such as the current tag, or you can create a new set that mirror the trunk jobs but have a different repo url. Jenkins lets you group these in views to keep the display neat. You will also want to change the working copy of these jobs so it can checkout both sets simultaneously.

I use the 'job copy' feature in Jenkins to create a set of jobs from templates. You can set a variable in the template that is expanded at copy time to replace the svn URL and other parameters to keep the jobs separate.

Title: Is there some way to mark which branch is the latest in subversion?

Body: We're reworking our process with subversion at the moment, and one of the things we're doing is making branches for each release target in our demo environment so that you can test a release that has been delayed independent of code that will be released separately. I am also experimenting with Jenkins in order to automatically run and report out on our unit tests in our demo environment. Is there some way in subversion to say "This branch is the release we're testing at the moment" such that Jenkins will check out that branch to test it? If not, how should I be approaching this issue? </p>


答:
I did this, and I recommend that you don't.

What I did was write all the business logic in Lua, and stored that Lua script in a database. When my application started up it would load and execute the script. That way I could update the business logic of my application without distributing a new binary.

I invariably found that I always needed to update the binary when making changes. Some changes were in the Lua script, but I'd invariably have a list of changes that needed to be made, and so I almost always ended up having to make some changes in the binary and some changes in the Lua script. My imagination that I could avoid distributing binaries all the time simply didn't pan out.

What I found much more helpful was to ease the distribution of binaries. My application automatically checks for updates on startup, downloads, and installs any update. My users are thus always on the latest binaries that I've pushed. There is almost no difference between a change in the binary and a change in the scripts. If I did it again, I'd put even more effort to making the update seamless.

Title: Dynamic Code Evaluation in Java - Clever or Sloppy?

Body:
I am trying to create a flexible ACL framework in Java for my application.

Many ACL frameworks are built on a whitelist of rules, where a rule is in the form of owner:action:resource.  For example,

"JOHN can VIEW resource FOOBAR-1"

"MARY can VIEW resource FOOBAR-1"

"MARY can EDIT resource FOOBAR-1"

This is attractive because the rules can easily be serialized/persisted to a database.  But my application has complex business logic.  For example,

"All users in department 1 with over 5 years of seniority can VIEW resource FOOBAR-1, else not authorized"

"All users in department 2, if the date is after 03/15/2016, can VIEW resource FOOBAR-2, else not authorized"

Upon first thought, it would be a nightmare to devise a database schema that could handle infinitely complex rules such as these.  Therefore, it seems as though I would need to "bake" them into the compiled application, evaluate them for each user, and then produce owner:action:resource rules as a result of the evaluation.  I want to avoid baking the logic into the compiled application.

So, I was thinking of representing a rule in the form of predicate:action:resource, where the predicate is a boolean expression that determines whether a user is allowed.  The predicate would be a string of a JavaScript expression that could be evaluated by Java's Rhino engine.  For example,

return user.getDept() == 1 && user.seniority > 5;

In doing so, the predicates could easily be persisted to the database.

Is this clever?  Is this sloppy?  Is this gimmicky?  Is this over-engineered?  Is this safe (apparently, Java can sandbox the Rhino engine).