问:
Proper way to interpret this dereference operation?
I've seen this example in a text book and am a little confused how to interpret the operator precedence rules. Given this struct:

```<code>   typedef struct {
   char *data;
   size_t start, end;
   } str_wends;
</code>```

Let B be declared as a pointer to this struct,that is.

```<code>   str_wends *B = malloc(sizeof(str_wends));
</code>```

and assume B->start != 0,

then this should be a legal construct:

```<code>   &B->data[B->start]
</code>```

which will return a reference to the string offset by B->start. The question is how to interpret the precedence rules. Since we know that -> and [] have the same precedence and bind left to right, why is B->Start evaluated before B->data[].

答:
Since we know that -> and [] have the same precedence and bind left to right, why is B->Start evaluated before B->data[].

This is a common misconception that just won't die.

Precedence and evaluation order are unrelated.

Precedence rules tell us what your statement means; which tokens form operands to which operators. It tells us that your code is equivalent to &(B->data[B->start]), not (&B->data)[B->start].

The order in which those operands are evaluated with respect to one another is guided by completely separate rules; in this case, it's obvious that B->Start must be evaluated before the surrounding B->data[].

University professors really need to stop saying that a higher precedence leads to something being "executed" "before" some other thing; it absolutely does not.


问:
Login using email or username?
Is registration login using email a better idea than username to identify the user?</p>

答: Most people like to keep the username and email a bit separate, because their email address may contain personal data. Therefore, it's a good idea to allow the user to choose a username.</p>

ContentLicense: CC BY-SA 2.5

Title: Login using email or username?


问:
Why do negative numbers evaluate to true in PHP?
```<code>function haha($lol)
{
   if($lol) { echo "plus"; }
   else { echo "minus"; }
}
</code>```

haha(-1) echoes plus.

Is it because PHP uses twos complement? Google search wasn't really helpful.

答:
Google search wasn't really helpful.

This did not take long to find. From http://php.net/manual/en/language.types.boolean.php :

When converting to boolean, the following values are considered FALSE:

the boolean FALSE itself

the integer 0 (zero)

the float 0.0 (zero)

the empty string, and the string "0"

an array with zero elements

an object with zero member variables (PHP 4 only)

the special type NULL (including unset variables)

SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

Warning: -1 is considered TRUE, like any other non-zero (whether negative or positive) number!

ContentLicense: CC BY-SA 3.0


问:
Design pattern for ensuring the "signature" of generic lists is equal
I have an interface, Attribute, that is going to be implemented in various ways,

```<code>class AttributeA implements Attribute{\\..}
class AttributeB implements Attribute{\\..}
</code>```

Then I'm planning to have a class containing a list of interface members

```<code>class Example {
    List<Attribute> attributes;
    //..
}
</code>```

And then I'm planning to have a class containing a list of those

```<code>class ExamplesAndMore {
    List<Example> examples;
    //..
}
</code>```

But, I want any instatiation of ExamplesAndMore to make sure that it only takes examples of the same type or signature. That is, I want to make sure the examples list doesn' t contain one member whose attributes list is of the form <AttributeA, AttributeA, AttributeB> while another is of the <AttributeA, AttributeA, AttributeA> or <AttributeA, AttributeA, AttributeB, AttributeB>.

I could just check everywhere I modify the examples list.

A comment asked me to be more specific, so I'll give code for how I could do this.

```<code>class Example {
    List<Attribute> attributes;

    public List<Class<? extends Attribute>> getSignature(){
        List<Class<? extends Attribute>> result = new ArrayList<Class<? extends Attribute>>();
        for(Attribute attribute : attributes){
            result.add(attribute.getClass());
        }

        return result;
    }

    //..
}

public class ExamplesAndMore {
    List<Example> examples;
    List<Class<? extends Attribute>> signature;

    public ExamplesAndMore(List<Class<? extends Attribute>> signature){
        this.signature = signature;
        this.examples = new ArrayList<Example>();
    }

    public void addExample(Example example){
        if(!example.getSignature().equals(signature)){
            throw new IllegalArgumentException(String.format("This takes examples with signature %s", signature.toString()));
        }
        examples.add(example);
    }

    //..
}
</code>```

But I wonder if this is a good way of going about this, checking for types at runtime doesn't feel nice. Basically I think this code smells a bit. One way this smell might manifest as an actual problem is when I create

```<code>class GenericAttribute<T> implements Attribute{\\..}
</code>```

with the intention of not having an example with an attribute of type GenericAttribute<ClassA> and one of type GenericAttribute<ClassB> in the same list. Then type erasure ruins my day.

Also, when I don't need examples to contain arbitrarily many attributes but only a fixed number (say 3), then my problem goes away entirely and I can even check at compile-time by having

```<code>class Example<T1, T2, T3> {
    //..
}

public class ExamplesAndMore<T1,T2,T3> {
    List<Example<T1,T2,T3> examples;

    public void addExample(Example<T1,T2,T3> example){\\..}
    //..
}
</code>```

However this approach obviously doesn't extend to examples with arbitrarily many attributes.

Anyway, I feel that I'm missing some obvious technique or something. Is there a nice pattern that deals with this, am I designing this badly? Chances are I'm not the first one doing this.

Also sorry for the lousy title, If I had a better description for my problem I'd probably have better luck searching for an answer and wouldn't have to ask...

答:
If class AttributeA implements Attribute and class AttributeB implements the same, that means: in some respect AttributeA behaves like AttributeB; and the abstraction level on which they do that, is behaving like Attribute.
This is how polymorphism works!

But, I want any instatiation of ExamplesAndMore to make sure that it only takes examples of the same type or signature.

The correct way of implementing this - according to your initial design would be to have a separate class of Example which has a List of Attributes of one kind, i.e. you need another Interface for Example which allows to distinguish between Example containing AttributeA and Example containing AttributeB. Then you are a) sure, that the concrete Example contains only the attributes you wanted and b) could use the abstraction of the interface to treat them the same in this respect.

In the end, you could define your ExamplesAndMore class, like intended: containing Examples, but not classes, but rather interfaces.


问:
Starting on Web Project now - Do we choose HTML5/JS over Silverlight?
we are about to start on a Web Development project (the planning starts early 2011).

Do we choose HTML5/JS over Silverlight?

Are there any applications which now run on HTML5? Samples?

A simple Google Search led me here. Those look great (especially the Star Wars one!), but they are not what you call proper applications as such.

答:
Definitely HTML5. HTML5 all the way. The amount of users is much, much larger. Plus, compatibility is not that big of a problem with HTML5. Some good HTMl5 examples can be found here:

http://www.apple.com/html5/


答:
PHP inherits a lot of its design decisions like this one from Perl. Perl borrowed ideas widely, but almost certainly took this particular idea from C. C inherited it from B.

B did not have different data types like int, boolean, etc, but rather just operated on memory slots, and the interpretation of each slot depended on what instructions were used on it, so it had to use some fixed rule for converting a bit pattern to boolean, and the one it chose was all zero its false, all others true.

B was a derivative of BCPL, which had a similar type system, but diverges from BCPL's definition of truth values (which has the same definition of false, but requires true to have all bits set, I.e. -1 if interpreted as a signed 2's complement integer). BCPL leaves the result of using any other value unspecified.

It is likely that B's approach was influenced by the instruction set on the PDP 7 it was originally designed for. The PDP 7 provided instructions that would conditionally execute the next instruction if its accumulator register was zero or not zero which would execute in a single cycle. Testing for equality with any other value required multiple cycles. It also had an instruction ISZ (increment and skip if zero) which could very efficiently handle loops that count up to zero, an idiom made simple if non-zero numbers are true:

```<code>c = -8;
do { ... } while (++c);
</code>```

Title: Why do negative numbers evaluate to true in PHP?

Body:
```<code>function haha($lol)
{
   if($lol) { echo "plus"; }
   else { echo "minus"; }
}
</code>```

haha(-1) echoes plus.

Is it because PHP uses twos complement? Google search wasn't really helpful.

Body:
PHP inherits a lot of its design decisions like this one from Perl. Perl borrowed ideas widely, but almost certainly took this particular idea from C. C inherited it from B.

B did not have different data types like int, boolean, etc, but rather just operated on memory slots, and the interpretation of each slot depended on what instructions were used on it, so it had to use some fixed rule for converting a bit pattern to boolean, and the one it chose was all zero its false, all others true.

B was a derivative of BCPL, which had a similar type system, but diverges from BCPL's definition of truth values (which has the same definition of false, but requires true to have all bits set, I.e. -1 if interpreted as a signed 2's complement integer). BCPL leaves the result of using any other value unspecified.

It is likely that B's approach was influenced by the instruction set on the PDP 7 it was originally designed for. The PDP 7 provided instructions that would conditionally execute the next instruction if its accumulator register was zero or not zero which would execute in a single cycle. Testing for equality with any other value required multiple cycles. It also had an instruction ISZ (increment and skip if zero) which could very efficiently handle loops that count up to zero, an idiom made simple if non-zero numbers are true:

c = -8;
do { ... } while (++c);


问:
Child classes only change some "options" - what's the best approach?
I'm currently implementing functionality in Symfony (PHP - not that it should make any difference which language I'm using) where I have about four controllers that do almost exactly the same thing. The only difference between them is that they use different entity objects and form objects.

I've already refactored all the common functionality into an abstract parent class. I then have two abstract methods called getEntityInstance and getFormInstance, which only return the appropriate object instances.

The entity and form instances returned would both have common interfaces, called AbstractQuery and AbstractForm respectively.

As an example, let's say I have the following two classes.

```<code>abstract class AbstractQueryController {
    abstract protected function getEntityInstance();

    abstract protected function getFormInstance(AbstractQuery $query);

    public function queryAction(Request $request) {
        //Do some stuff
        $form = $this->getFormInstance($this->getEntityInstance());
        //Do something with $form
    }
}

class SomeRandomController extends AbstractQueryController() {
    protected function getEntityInstance() {
        return new SomeRandomQuery();
    }

    protected function getFormInstance(AbstractQuery $query) {
        return new SomeRandomForm($query);
    }
}
</code>```

Now this approach works, but it looks wrong. What design pattern or other concept should be applied here to make the code "cleaner"? The issue is that, with every new controller that extends AbstractQueryController, I'm basically baking the "configuration" (if you can call it that) into the child class, which looks incorrect.

答:
It depends on what you want to do exactly, which is a bit unclear from your example.

However there are certain issues with your design, such as the Controller being directly responsible for creating needed objects. This leads to very tight coupling, very hard to test code and other issues.

I would begin refactoring your example by moving the creation of Query and Form instances into factories and then inject these factories into your controller.

You can have different factories, each producing a different instance of Query and Form classes (note that these classes should implement common interface, QueryInterface and/or FormInterface) and create an IoC container which will be responsible to injecting the correct factory into your controller (or concrete method) based on user input - be it url parsing or anything else.

If the current logic for hangling the result of the getFormInstance method is always the same, correctly implementing factories and the IoC container acting as strategy pattern, you could have as little as only one Controller handling all your request and would not need to have more of them.

The return type of getFormInstance would then be an interface which specific Forms would implement and using the interface instead of specific classes would guarantee you the behaviour by the interface's definition.


问:
Dependency Injection: Field Injection vs Constructor Injection?
I know this is a hot debate and the opinions tend to change over time as to the best approach practice.

I used to use exclusively field injection for my classes, until I started reading up on different blogs (exs: petrikainulainen and schauderhaft and fowler) about the benefits of constructor injection.  I have since switched my methodologies to use constructor injection for required dependencies and setter injection for optional dependencies.

However, I have recently gotten into a debate with the author of JMockit - a mocking framework - in which he sees constructor & setter injection as bad practice and indicates that the JEE community agrees with him.

In today's world, is there a preferred way of doing injection?  Is Field injection preferred?

Having switched to constructor inject from field injection in the last couple of years, I find it a lot clearer to use, but I am wondering if I should re-examine my viewpoint.  The author of JMockit (Rogério Liesenfeld), is clearly well versed in DI, so I feel obligated to review my approach given that he feels so strongly against constructor/setter injection.

答:
Field injection gets a definite "No" vote from me.

Like Robert Harvey, it is a bit too automagic for my taste. I prefer explicit code over implicit, and tolerate indirection only as/when it provides clear benefits as it makes code harder to understand and reason about.

Like Maciej Chałapuk, I don't like needing reflection or a DI/IoC framework to instantiate a class. It's like driving to Rome to get to Paris from Amsterdam.

Mind you I love DI and all the advantages it brings. Just not sure about needing the frameworks to instantiate a class. Especially not the effect that IoC containers or other DI frameworks can have on test code.

I like my tests to be very straightforward. I don't like having to go through the indirection of setting up an IoC containers or other DI framework to then have them set up my class under test. It just feels awkward.

And it makes my tests dependent on the global state of the framework. That is to say that I can no longer run two tests in parallel that require an instance of class X to be set up with different dependencies.

At least with constructor and setter injection, you have the option of not using the frameworks and/or reflection in your tests.


问:
What is the difference between proxy class and delegation in Python?
Wiki:

A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes

Hmm!, what would this look like in terms of code ?

Wiki

delegation refers to one object relying upon another to provide a specified set of functionalities

This class for example delegates its functionalities to another object:

```<code>class CustomInt:

    def __init__(self):
        self.obj = int()

    def __getattr__(self, attr):
        return getattr(self.obj, attr)   # Delegation
</code>```

Since it's a class functioning as an interface for something else, can I consider it as a proxy class ?

答:
A proxy has no other functionality than to forward actions. A class that delegates also adds its own functionality.

In that, effectively, a proxy is a special case of delegation.

As @Jules said, your example is one of a proxy.

ContentLicense: CC BY-SA 4.0


问:
Is this a good solution for deactivating key value pairs?
A (relatively) simple CRUD application on which I work has a lookup table which holds key-value pairs, some of which have child key-value pairs. These are used mainly in drop-down lists on the application front end.

Currently there is a RowStatus field to specify a key-value pair is active/inactive and is not to be included in drop-down lists. This is fine for creating records however it is an issue when updating historical records.

I plan on introducing a ValidFrom and ValidTo field in the lookup table for which 'Create' screens will use, along with the existing RowStatus field, to ensure that any items in the drop-down lists are valid for the current date-time. These would also be nullable in which case the underlying sql would ignore the field.

'Update' screens will continue to use just the RowStatus field, a bonus would be that the Update screens could also only display items which were valid at the time of creation, although business rules would determine this.

In practice, a user control loads key-value pairs from the lookup table and uses different criteria dependent on the page the user control is on. ie.

Create:

```<code>select * from lookuplist where RowStatus=1 and ValidFrom < sysdate and ValidTo > sysdate
</code>```

Update:

```<code>select * from lookuplist where RowStatus=1
</code>```

or

```<code>select * from lookuplist where RowStatus=1 and ValidFrom < CreatedOn and ValidTo > CreatedOn
</code>```

Are there any issues with this approach that I've not considered?

Any ways in which this could be improved?

Code is in c#/ASP.Net/Oracle 12C but not hugely relevant.

答:
Either ignore the flag when updating OR flag the update as in error if the flag switched from active to inactive.

Which you choose depends on the business logic you're implementing. In some cases the first is appropriate, in others the second.

For example we've a field that determines the inspection intervals for machinery. This field is linked to legal requirements and determines the expiration date of a certificate which is a legal document. If the value in that field becomes inactive, we skip the check on active in the validation of the record because it's of course not a good idea to change the expiration date of the certificate on the fly just because an inspection interval is no longer allowed but a machine was inspected last before that change was made. Of course when a new inspection is entered only the then valid intervals can be selected.

In other cases you may want to flag the record for needing to be updated with a new value. Think of a field that holds the title of a customer. If you decide to disallow a possible value in that list (maybe because of a typo) you would want every next update of the customer record to require the value to be changed.


问:
How to use DAO effectively in my MMO server
I am working on a small multi player game for my final year project and currently working on the server. It's a Tank Battle game and have two main entities which I will use on the server side which are

Player (Player details like username, password, currentTank, statistics)

Tank (Details of a tank like velocity, rotationVelocity, Turret)

Turret(Details of turret like rotation velocity, fireRate, etc)

Statistics(stats like totalKills, total deaths, total shots etc)

I have recently read about DAO and how they separate out the database concerns and thought to use it in my project because my project does have good amount of data to persist and also due to the fact that I want to learn this technique.

After reading about DAO I realised there will be need to map the DTO to Domain Objects for business logic. As I am going to have quite a bit of logic on these object as well methods which are not really needed on DTO's.

So for example I map :

PlayerDTO -> PlayerObject

Whenever there is a request from player to move his tank, I queue the direction in a queue contained in player's tank. (This shows the need for having Domain Object as I don't need movement queue on the database but I need it on the tank objects to queue movements)

Now let's say in my MovementService of my server, I loop through the PlayerObject list (the logged in players) and update player's tank position in by calling the player.moveTank() which will update his positions according to the movement queued in the movement queue inside the TankObject contained in PlayerObject. I understand it till this point what I need to do.

Now my question is how will I save PlayerObject back to Database? Do I need to map it back to PlayerDTO? What is the most effective way to do it?

For now I have thought that when the player logs out,In my LogoutService I will use the PlayerDAO service and get the PlayerDTO using PlayerObject ID and update the object details and save him back to the database but I feel that I will be making extra database calls just to get the object (An extra select call) and to save it back rather than just updating the object using update query.

I also feel that just for updating let's say his position on the database I will have to use a query which will overwrite everything. Is there any better way of doing it or I am doing it right?

Note: I won't be using any ORM in my project.

P.S. I searched a lot but couldn't find any similar question. I know I haven't put any code and it's a long question but if anything is not clear let me know.

答:
I wouldn't use the PlayerObject ID anywhere in this. I wouldn't "PlayerDTO using PlayerObject ID".

The player object ID should be irrelevant to you. Of course the DAO and especially the ORM (library or your own custom code) need it and use it, but the domain object shouldn't care about it. It only carries it around for the DAO's use. If I had my way, it wouldn't even be available from the domain object except perhaps through reflection or a DAO specific interface the domain object has to support in order to be persistable.

I am not up on the current thinking on this (haven't done a lot of database work lately), but in my mind DTO's (data transfer objects) only serve the purpose of limiting (or deriving) what gets transfered to and from a database. They are most useful when using an ORM because it allows the ORM to remain fully generic by working on - usually behaviorless - DTO classes. In essence the DTO serves as the map between the domain object and the information stored in the database.

So in your case, I would just hand a player domain object to the player dao service. The dao service would then either construct a player dto itself by inquiring the player domain object it received, or would ask the player domain object to provide a player dto instance, and then hand the player dto instance to the code that builds the queries and executes them against a database. That could be an ORM or your own code.

Whether the dao service constructs the dto, or the domain object does, is a trade off. I prefer the dao service to construct the player dto to be used by the database access code (custom or ORM). The reason is that the domain object should be unconcerned about any persistence - it should be able to assume that it will always be around. The dao service is the natural place for all persistence logic: where to store anything (db, file, registry), what needs to be stored (mapping of domain to dto) and how it needs to be stored (mapping of dto to tables and fields, xml structures or whatever) and what translations need to be done (for example translating an enumeration into the values for a character field in a table).


答:
When I first read this question something about it bothered me, but I couldn't put my finger on it.

This morning I realized that what bothered me was that some people may be doing this, converting numbers to booleans.  Perhaps the OP was just doing it as an academic exercise, but IMHO it should never be done in practice.

This admonition from MSDN sums it up nicely, "...You should never write code that relies on equivalent numeric values for True and False. Whenever possible, you should restrict usage of Boolean variables to the logical values for which they are designed."


答: Consider OpenID. But if you don't want to use that, the plus for user name is that it isn't linked to a specific email. The plus for email is they won't have to remember what they used for a user name. </p>

Title: Login using email or username?

Body: Is registration login using email a better idea than username to identify the user?</p>


问:
How to do reports from python
This is not a question, asking for a (single) tool, although to answer my question, of course tools are involved. The focus of this question is, asking for advice in which direction to head for.

I have a JAVA-background, so in order to generate any document, Jasper Reports are a good starting point.

Coming to Python, I am facing the requirement, that our customer wants either PDF output oder (ideally) .docx (Office 2010). Since Office 2010 is able to read .odt, my first approach was using py3o to do the job in Libreoffice. But that was a bit dissatisfying. The compatibility between Libreoffice and MS Office isn't as good as expected.

Would it be a better approach to target PDF and use LaTeX to generate the document? I took a look at weasyprint which generates PDF from HTML and CSS. The demo looks quite promising, but I hesitate to use CSS for the job.

My question is: what is the common way to deal with "reports" under python?

P.S.: I should mention, that the software is required to be Open Source or has to have at least a community version

答:
Here are two popular ones:

pyPDF2

ReportLab

As far as I know ReportLab has a free and paid version.

Title: How to do reports from python


问:
Vertical alignment: yea or nay?
For instance, non-vertically aligned:

```<code>Name:   Hamt
Version:  0.1.0
Cabal-Version:  >= 1.2
License:  BSD3
Author:  Jason Baker
</code>```

Or vertically aligned:

```<code>Name:           Hamt
Version:        0.1.0
Cabal-Version:  >= 1.2
License:        BSD3
Author:         Jason Baker
</code>```

Which do you prefer and why?

答:
Saves time when you just do it like this:

```<code>Name: Hamt
Version: 0.1.0
Cabal-Version: >= 1.2
License: BSD3
Author: Jason Baker
</code>```

Isn't too hard to read either.

Title: Vertical alignment: yea or nay?

Body:
Saves time when you just do it like this:

Name: Hamt
Version: 0.1.0
Cabal-Version: >= 1.2
License: BSD3
Author: Jason Baker

Isn't too hard to read either.


问:
Class library naming conventions
Typically in a C# program, the entry point is in Program.cs. However, if you  are creating a rather generic class library, with no Main() method, such as

TCPClient.dll

what is the appropriate base class name? (cannot be TCPClient as that is the namespace).

答:
There isn't one.

The entrypoint is for your executable. There is one.

Your library has as much business declaring an entrypoint as do all the other files in your program, be they dynamically or statically linked; i.e. none.

Name the classes it declares however you like.

Title: Class library naming conventions


答:
There are situations where either has advantages over the other.

I think let the users take the call here so you should think about including both the options. If the login name is the same as the email then you select an additional check-box/radio-button etc.

Sites like monster allow for login with either the username or email-id. Check their interface out.

Title: Login using email or username?


问:
In Scrum, should developers talk directly to customers (bypassing the PO)?
How should a product owner in scrum deal with very detailed questions from the team regarding the features they are implementing that he cannot instantly answer himself? When it would clearly be the faster solution for the developer to directly talk to the customer himself?

I wonder if direct communication between the team and the customer undermines the role of the product owner. I feel like the PO should exclusively represent the customer and therefore answer all questions regarding the requirements - even if that takes longer. Bypassing him seems to weaken him and eventually make him superfluous...

Is there a best practice in scrum?

答:
It is always a good idea (especially in so-called Agile projects) not to stick to some cargo cult or text book telling you "who should (not) talk to whom", but switch on your brain and do whatever works best in a project.

Though the communication between PO and the customer should be the standard (because of the reasons scetched by @PatrickHughes in his comment), you may face a situation where a complex business requirement has to be clarified, and the direct communication between a dev and a business expert will speed up things a lot. In such a situation, one should avoid playing "chinese whisper" with the PO in the middle, and let the dev and the business expert directly talk to each other - for this restricted context.

However, the PO should never be bypassed. Ideally, he takes part in that conversation, probably as a moderator. He can verify the customer does not bring up completly new requirements on the table during the talk, or requirements contrary to what was agreed upon before.

This depends also on the people involved, and the situation. The PO might have enough trust in the specific dev and the customer's expert, to let the two talk alone about a specific topic, and let him or her report what was said afterwards. In another situation, with other people involved, he might prefer to take a more active part. To get this decisions right is the core of good project management.


答:
Login name.

Email address was never meant to be a means of identification, but a means of communication

If a user is logging in before somebody's eyes, then their email address will be revealed which is quite bad. If a login name is revealed, it's not a big deal.

Do not automatically turn the login name into a public display name. They're two completely different things. Let the user specify the display name separately. Bonus points, let the user freely edit both the login name and a display name later.

Title: Login using email or username?


答:
To the developers, the product owner IS the customer. Ideally (and I know that's not always possible) the product owner should be a direct representative of the customer, a domain expert and future user of the system.

That's the best way to ensure you have direct and correct information available and the shortest lines possible into their processes.

Ideal example is probably the team I'm working with now. Product owner is a senior end user and domain expert with full authority to authorise design decisions on the spot (and the willingness and ability to actually do so). He's an integral part of the team and directly assists the analyst and designer in writing the user stories, as well as programmers and testers in building the product by providing near instant feedback on implementation questions and test scenarios.

Lines can't really be shorter than having your future user sitting next to you while coding :)

Title: In Scrum, should developers talk directly to customers (bypassing the PO)?

Body:
How should a product owner in scrum deal with very detailed questions from the team regarding the features they are implementing that he cannot instantly answer himself? When it would clearly be the faster solution for the developer to directly talk to the customer himself?

I wonder if direct communication between the team and the customer undermines the role of the product owner. I feel like the PO should exclusively represent the customer and therefore answer all questions regarding the requirements - even if that takes longer. Bypassing him seems to weaken him and eventually make him superfluous...

Is there a best practice in scrum?


问:
How to populate Lazy object from database
I have these classes:

```<code>public class Order
{
    private Lazy<IEnumerable<Volume>> _volumes;
    long ID { get; private set; }
    string Description { get; private set; }
    IEnumerable<Volume> Volumes { get { return _volumes.Value; } }
    //etc..
}
public class Volume
{
    long ID { get; private set; }
    string Description { get; private set; }
    //etc..
}
</code>```

I need to instantiate and populate several Orders. To supply the objects of these classes I have these Repositories:

```<code>public interface IOrderRepository
{
    Order GetByID(long ID);
    IEnumerable<Order> GetAll();
    Order Create(long ID, string Description);
    void Update(Order O);
    void Delete(Order O);
}
public interface IVolumeRepository
{
    Volume GetByID(long ID);
    IEnumerable<Volume> GetAll(Order O);
    Volume Create(long ID, string Description, Order O);
    void Update(Volume V);
    void Delete(Volume V);
}
</code>```

I don't need to populate the Volumes of each Order upon instantiation, it would be best to implement lazy loading, in my opinion, as there can be a lot of Volumes.

So how should I let the Order know where to fetch the Volumes? I have this code that populates the Order it is instantiated:

```<code>//Interface
public interface IVolumeFetcher { IEnumerable<Volume> GetAll(Order O); }
//Order Constructor
public Order(long ID, string Description, IVolumeFetcher VF)
{
    _volumes = new Lazy<IEnumerable<Volume>>(() => VF.GetAll(this));
}
</code>```

This gives the Order a reference to the Repository, it doesn't seem a good idea to me.

I could keep the Order's Volumes a simple List and fill it when needed:

```<code>public List<Volume> Volumes { get; private set; }
</code>```

But this approach would be easily corrupted, any caller could add a Volume to the list and it wouldn't be persisted to the DB.
Btw, this is a three layered application, with a Order and Volume class for each layer, as well as a repository.

答:
I'm fine with Order having reference to IVolumeRepository, but only under 2 conditions.

First is that all involved entities are under single Context. Eg. a class exists that represents current transaction that handles lifetime of all it's entities. So this Context needs to exist as long as you are manipulating those entities and newly fetched and created entities fall under this context. This is how ORMs do it.

Second is that the implementation of the IVolumeRepository is injected transparently when new instance of Order is either created or materialized from the database. This ensures that the domain has no knowledge about actual implementation of the repository. Again, this is how ORMs do it, because every materialized concrete instance of entity (ORMs mostly create their own concrete class for each entity through runtime code generation) has reference to Context.


答:
There is a factor you may not consider - default times should be blank or you will end up with people putting "some time in the future" as defaults and one day, you'll get a support call asking why all your dropdowns have stopped working. (it happened to a colleague at the worst time - they expired at noon, after the sales guys ran through their demo in the morning that was to be shown to customers in the afternoon).

A default of 3000 years in the future might work but a blank for 'not set' would be easier to read - and you can easily see which ones are 'live' as the expiry date would not be set. Similarly you will have to put a created date on all which could cause problems for your historical records unless you get it perfectly right.

Title: Is this a good solution for deactivating key value pairs?

Body:
A (relatively) simple CRUD application on which I work has a lookup table which holds key-value pairs, some of which have child key-value pairs. These are used mainly in drop-down lists on the application front end.

Currently there is a RowStatus field to specify a key-value pair is active/inactive and is not to be included in drop-down lists. This is fine for creating records however it is an issue when updating historical records.

I plan on introducing a ValidFrom and ValidTo field in the lookup table for which 'Create' screens will use, along with the existing RowStatus field, to ensure that any items in the drop-down lists are valid for the current date-time. These would also be nullable in which case the underlying sql would ignore the field.

'Update' screens will continue to use just the RowStatus field, a bonus would be that the Update screens could also only display items which were valid at the time of creation, although business rules would determine this.

In practice, a user control loads key-value pairs from the lookup table and uses different criteria dependent on the page the user control is on. ie.

Create:

```<code>select * from lookuplist where RowStatus=1 and ValidFrom < sysdate and ValidTo > sysdate
</code>```

Update:

```<code>select * from lookuplist where RowStatus=1
</code>```

or

```<code>select * from lookuplist where RowStatus=1 and ValidFrom < CreatedOn and ValidTo > CreatedOn
</code>```

Are there any issues with this approach that I've not considered?

Any ways in which this could be improved?

Code is in c#/ASP.Net/Oracle 12C but not hugely relevant.


答:
There are several reasons to prefer username over email (it would be an abuse of the concept of email, a bystander could read your address - not that I would care the slightest, but some could) etc, but I think the advantages still win:

With an email address for login you can have any user name (too short, too long, with spaces and caps you won't have to remember, with special symbols, you name it);

You already have to remember a password for every site, remembering a paired username is really too much to ask;

People should be able to change usernames;

In some cases (for instance, a music bands community) a user could manage more accounts - should he have an extra login for each and any? Should he have an username to manage all of them? Which one? Nobody will ever see it, anyway;

People may want to change usernames.

That said, the solution is using 3rd party authentication services, in particular OpenID: if you're such a hardcore h4X0r not to have an account in any of the supported platforms (google, facebook, twitter, anything) then you probably have your own OpenID server.

Title: Login using email or username?


答:
One consideration could be the row which is invalid, then valid, then invalid again.

To counter this and other complexities I would recommend you force the creation of a new row for a 're-enable' action.

I've done similar systems before and found that the users find the 'historical' menu items confusing, especially in a hierarchical structure.

Another approach is to have 'versions' of the whole tree, which you then switch between when publishing/rolling back.

Once a version is live, you are unable to edit it. This forces some good practice on the users who maintain the structure and reduces the complexity of maintenance.


问:
How to have my callbacks authenticated in a REST app?
I'm developing a REST application and I allow my clients to authenticate in several ways (typically using Authorization: Token ... as in OAuth 2.0, but also there's session-based auth option for the web-browsable API). The application allows the client to provide their endpoint to which my application would later POST with some data whenever a particular event happens.

Now I wonder: what's the best way for the client application to authorise that it's my application calling?

Should I roll something up myself (like, include a token derived from the client application secret, which the client app would then verify), or is there a more conventional approach I can follow?

答:
The API is yours, so it is up to your clients to adapt to it, not the other way around.

If some of your clients require authentication on their https://client.app.com/callback-for-youapp I think they'd have to figure that by themselves. For example they could include a token when calling you so that when you call them back they can authenticate your call ex :

Your client subscribing:

POST https://your.app.com/subscriptions
{
   "...": "..."
   "callback": "https://client.app.com/callback-for-youapp?token=xyz"
}

So when your are calling back on
https://client.app.com/callback-for-youapp?token=xyz
They can authenticate your request using the token in the query string.


问:
Workflow for chains of dependent pull requests to projects that depend on other projects
Suppose you have project A and project B, where project B depends on project A - let's say A is a library. And project A and project B live in separate version control repositories - either because project A was created by a third party, or because you just decided to organise your repositories that way. You want to make some changes to project B, but in order to do so you have to make some changes to project A. So you make two pull requests, one for your changes to project B and one for your changes to project A - these PRs "have to" be applied together - although in practice, of course, one of them has to be merged first (logically, it has to be the PR for project A) and here's where the problem can come in.

We have our CI server (TeamCity) set up to build all feature branches, so we can easily see if an individual, standalone PR to project B breaks things in project B. But because code in feature branches doesn't get published to our artifact repository (Nexus) until it's merged to master, this doesn't work so well for pairs (or even chains) of PRs like the scenario described above. We can only see, in a valid way, if the PR for project B is going to build on the build server after we've already merged the PR for project A. And it just so happened recently that this dependent build failed... because of a problem that only occurred on the build server.

Thus, we ended up with a situation where project B's master wasn't building due to a tightly-bound pair of PRs only being half-merged - the PR for project A had been merged, but the PR for project B hadn't been yet, due to the unexpected issue on the build server.

How could we adjust our workflow to avoid this kind of problem in future?

答:
In the situation described, if you want to ensure that the CI build doesn't get broken, you might need to split the changes into even smaller, or slightly different, chunks.

A successful workflow could be:

Change project A such that the new functionality can be supported, but the existing API remains valid (at least for the time being).

Wait until the new version of A is available in the artefact repository.

Make the required changes to project B, using the newly introduced interfaces from project A.

(Optionally) Remove from project A the interfaces that have become obsolete and are no longer used.

The major difference with your existing workflow is that you do not change both projects at the same time. First you make the required changes, in a backwards-compatible way, to the lower projects in the dependency graph and only when you have a "released" version of your dependencies that support what you need, only then do you make the update to the higher levels.


问:
Can I check the existence of an annotation in an unit test?
I have a java class hierarchy that are formed by an Abstract class and N extensions of it.
In the abstract class I have a method that is annotated with a @Remove annotation. While we won't get any exceptions of won't fail fast if this annotation is removed, we may get out of memory exceptions, so I would like to be sure that we notice as fast as possible if this annotation disappears in some refactoring.

I am trying to create GUTS (good unit tests), so I thought I could document this "technical requirement" in my tests, with a test case that states it.

But this is not a feature, it as an implementation detail and it is not linked to the behavior of the method (the method could be empty, but it has to exist and has to be annotated).

Is it ok to create a test for that or is there any other way to check the existence of this annotation?

答:
Yes create a unit test. You are saying that if the annotation is removed then you can get out of memory bugs in production. That would be a killer bug. Letting that happen due to some idea that tests should somehow be limited is counter productive.  Tests should check for correctness in all senses. The sooner you detect the possible problem the better so having a unit test and failing the CI build is the solid way to prevent the bug. Trying to invent another mechanism to prevent the introduction of such a bug does not seem worth while. Every new developer will have to be given an explanation of how to handle the "special case" of none functional correctness tests. That is most likely not a good use of developer time.

Edit Teams that do BDD are likely to separate out business functional test from technical tests such as performance tests. Typically teams have different types of tests including integration tests that are run less frequently than their core business logic tests. This is usually done with build profiles so that developers in their flow can run fast business logic tests frequently and the slower integration tests before they commit code. The CI build will run all the tests.


问:
Does Having DI Happen in the Composition Root go against the whole point of Dependency Injection?
I am using Dependency Injection for a .NET MVC web application in which I have three basic layers:

1) Web App
2) Service Layer
3) Data Layer

I inject the data layer into the service layer and the service layer into a controller in my web app which is all fine but I am confused over where the registering of these classes takes place.

After researching I've been told that the composition root is within the web application specifically in the Global.asax file which I have in my project, but this means that now I have a reference to the Data Layer within the web application in order to be able to register it. This seems to go against exactly what DI is for to me as I don't want my web app to know or care about the data layer only the service layer should have a reference?

答:
Does Having DI Happen in the Composition Root go against the whole point of Dependency Injection?

No. You should create the object graph in the Composition Root.

I think that I understand the reason of your confusion. And I think that it is related to ASP.NET projects. To explain this, let me give first  an example that does not involve ASP.NET.

Let's say we have a Console Application. We have created some class libraries that contain all the pieces of logic that our application need.

Let's say we created the following class libraries:

ApplicationLibrary contains classes that are related to the application itself. It might contain some UI logic also.

BusinessLogicLibrary contains classes related to business logic.

DataAccessLibrary contains classes related to data access.

The ApplicationLibrary in this case does not have a reference to the DataAccessLibrary.

And then we compose these pieces together in the Console Application project. This project in this case does not contain anything except the composition root.

The thing with the ASP.NET projects is that by default we get a template in which the composition root and some Application/UI logic are in the same project.

What would be great is to have an ASP.NET web project that contains only the composition root (IControllerFactory implementation for example). And then move our Controllers and Views to another class library that does not have a reference to the DataAccessLayer since it is no longer the composition root.

You might even be able to do this with ASP.NET. I am not sure if there is an easy way though.


问:
Is there a name for the Builder Pattern where the Builder is implemented via interfaces so certain parameters are required?
So we implemented the builder pattern for most of our domain to help in understandability of what actually being passed to a constructor, and for the normal advantages that a builder gives. The one twist was that we exposed the builder through interfaces so we could chain required functions and unrequired functions to make sure that the correct parameters were passed. I was curious if there was an existing pattern like this.

Example below:

```<code>public class Foo
{
   private int someThing;
   private int someThing2;
   private DateTime someThing3;

   private Foo(Builder builder)
   {
       this.someThing = builder.someThing;
       this.someThing2 = builder.someThing2;
       this.someThing3 = builder.someThing3;
   }

   public static RequiredSomething getBuilder()
   {
       return new Builder();
   }

   public interface RequiredSomething { public RequiredDateTime withSomething (int value); }
   public interface RequiredDateTime { public OptionalParamters withDateTime (DateTime value); }
   public interface OptionalParamters {
      public OptionalParamters withSeomthing2 (int value);
      public Foo Build ();}

   public static class Builder implements RequiredSomething, RequiredDateTime, OptionalParamters
   {
      private int someThing;
      private int someThing2;
      private DateTime someThing3;

      public RequiredDateTime withSomething (int value) {someThing = value; return this;}
      public OptionalParamters withDateTime (int value) {someThing = value; return this;}
      public OptionalParamters withSeomthing2 (int value) {someThing = value; return this;}
      public Foo build(){return new Foo(this);}
   }
}
</code>```

Example of how it's called:

```<code>   Foo foo = Foo.getBuilder().withSomething(1).withDateTime(DateTime.now()).build();
   Foo foo2 = Foo.getBuilder().withSomething(1).withDateTime(DateTime.now()).withSomething2(3).build();
</code>```

答:
What you are doing is called a fluent interface.

From Fowler's article:

In essence we create the various objects and wire them up together. If we can't set up everything in the constructor, then we need to make temporary variables to help us complete the wiring - this is particularly the case where you're adding items into collections.

Which is where @Frank was talking about "Phantom Types". Also Fowler says

Probably the most important thing to notice about this style is that the intent is to do something along the lines of an internal DomainSpecificLanguage. Indeed this is why we chose the term 'fluent' to describe it, in many ways the two terms are synonyms. The API is primarily designed to be readable and to flow.

The way I have seen this discussed is to use "fluent" as an adjective, so in your case it would be a "fluent builder".


问:
Login using email or username?
Is registration login using email a better idea than username to identify the user?</p>

答:
Just use email address. Screw separation of concerns; I already have way too many user names.

You could do both if you want, but you risk confusing people with non-standard UI if you're not careful. (This is a downside of OpenID.)

Also, don't be an idiot like Gawker and neglect to salt your passwords.

Title: Login using email or username?


问:
Relationship of Package names and file structure
I'm currently refreshing my Java knowledge and came across a question I couldn't answer yet:

How does the Java compiler know where the (possibly custom) packages are located on disk? I'd assume that using built-in libraries it looks up the java library folder - but how does it find the custom ones?

Here's the file's locations for the following example:

// part of the package

com/usuallyNot/example.java

// not part of the package

com/example2.java

Is the naming convention to be seen as relative path? If it's this, why do we need to write "import package com.usuallyNot.example;" (instead of "import package "usuallyNot.example;") even if the file we write it in resides in the "com" folder?

答: If you didn't import your types, the compiler would have to perform expensive hard disk scans every time it encounters a custom type. That is very expensive; it's better to force the programmer to declare the location explicitly, so the compiler only has to open one file directly. (An additional advantage is that you can have several types with the same unqualified name, but efficient compilation is the big one.)</p>


答:
The answer is the classpath:

Classpath is a parameter—set either on the command-line, or through an environment variable—that tells the Java Virtual Machine or the Java compiler where to look for user-defined classes and packages.

There are instructions from Oracle how to set your classpath.

The classpath is searched in order of the folders that appear for a class matching the import. There are lots of details in how multiple classes of the same name can co-exist.

The classpath is set either by %CLASSPATH% (Windows DOS shell,  $env:CLASSPATH in PowerShell) or $CLASSPATH in Unix or in the manifest of a Jar file.

You can see the future of classpath from the 2015 JavaOne keynot (starting @ 17 minutes).

Title: Relationship of Package names and file structure

Body:
I'm currently refreshing my Java knowledge and came across a question I couldn't answer yet:

How does the Java compiler know where the (possibly custom) packages are located on disk? I'd assume that using built-in libraries it looks up the java library folder - but how does it find the custom ones?

Here's the file's locations for the following example:

// part of the package

com/usuallyNot/example.java

// not part of the package

com/example2.java

Is the naming convention to be seen as relative path? If it's this, why do we need to write "import package com.usuallyNot.example;" (instead of "import package "usuallyNot.example;") even if the file we write it in resides in the "com" folder?


问:
Better To Call In Dive Into Submethods Or Pass Around a result

I have a service that does fairly complicated business logic when it receives a request. I have most the functionality isolated into private methods which dive a couple levels down from the method that receives the request. Basically receive request -> private method for subprocessing -> private method for processing different action -> method that creates a result -> method that verifies result.

I can either call each of these methods sequentially and pass around the various results between each private method or I can call one method from inside of the next method and keep passing along the data between steps the other way

//either passing around as returns or class variables
public onRequest(Request request){
        method1(request) // Returns two things for method 2
        method2(thing1, thing2) //Modifies and thing1 and thing2
        method3(thing1Mod, thing2Mod) //Returns a result
        verify(result)
        return result
}
```

<p>Option 2</p>

<pre class="lang-java prettyprint-override"><code>public onRequest(Request request{
    Result result = method1(request)
}

method1(request){
    //logic that makes thing1 thing2
    return method2(thing1, thing2)
}

method2 (thing1, thing2)
    //logic to modify thing1 and thing2
    return method3(thing1, thing2)

method3 (thing1, thing2) {
    //logic that gets a result from thing1, thing2
    verify(result)
    return result
}
</code>```

Each method contains discrete functionality.

The reason I am concerned is that I am trying to write test cases and I want to only leave onRequest public but I still wanna test methods 1-3 and verify individually.

Project is in Java

答:
If you want to unit test the otherwise private methods you have a number of choices

Reflection ! yay reflection.

Make them protected and expose by creating an accessor class which inherits from the original

Make the methods public, but put them on other sub-service classes, which  your original class then has private instances of.

Once you have exposed them in one of these ways, I think you can see that your first option, that of calling each in turn from the main method, gives you the best 'testablity' as you are able to test each method separately from the others. Whereas your second option, makes it difficult to test method1 if method2 is failing for example.


问:
Split a File into Multiple Objects Functionally
I want to read a file into a collection of objects. The data (it's a Leica PTX file if you're curious) is formatted as follows:

```<code>640 [begin item #1: number of columns]
480 [number of rows]
0 0 0 [position information: 3x3 matrix]
0 0 0 [position ctd]
0 0 0 [position ctd]
1 0 0 0 [calibration information: 3x4 matrix]
0 1 0 0 [calibration ctd]
0 0 1 0 [calibration ctd]
1.1 2.2 3.3 0.5 [point 1: X Y Z I]
-0.2 2.3 1.4 0.2 [point 2: X Y Z I]
...
3.9 1.2 -7.7 0.8 [point n: X Y Z I]
640 [begin item #2: number of columns]
480 [number of rows]
0 0 0 [position information]
0 0 0
0 0 0
1 0 0 0 [calibration information]
0 1 0 0
0 0 1 0
0.2 1.3 -2.1 0.4 [point 1 of item #2]
... [etc]
</code>```

I.e. Two lines each containing a single float/double (as text) signal the beginning of a new item, and no other lines are exactly one number.

It's easy to do if there's only one item per file, it's a simple fold operation. It would also be relatively straightforward to do with a while type loop that keeps state, but I'm new to functional programming and wondering if there isn't a more concise and elegant way to do this functionally with standard tools (like reduce, fold, split/partition, etc). The best solutions I've come up with so far involve "peeking" ahead using lists or arrays, but I'd like something that allows for the possibility of a sequence that is consumed as it iterates for maximum generality. (I'm using F# and .NET but I don't see this as a language-specific problem.)

答:
This isn't exactly one of functional programming's best use cases, but most languages have a construct that will create an infinite stream of lines, which you generally feed into a fold with an initial state.  Here's an example in Scala (sorry, I don't know F#):

```<code>val lines = io.Source.stdin.getLines
val state = lines.foldLeft(initialState)(processLine)
</code>```

Basically, the processLine function is whatever you would put in your while loop, and it returns a new state each time through.  Inside it, you can use split, regexes, pattern matching, or even parser combinators if you're brave.

I can't claim the functional solution ends up more elegant with something this stateful, but it does have the advantage that the wrong path is usually obvious pretty quickly.

Body:
This isn't exactly one of functional programming's best use cases, but most languages have a construct that will create an infinite stream of lines, which you generally feed into a fold with an initial state.  Here's an example in Scala (sorry, I don't know F#):

val lines = io.Source.stdin.getLines
val state = lines.foldLeft(initialState)(processLine)

Basically, the processLine function is whatever you would put in your while loop, and it returns a new state each time through.  Inside it, you can use split, regexes, pattern matching, or even parser combinators if you're brave.

I can't claim the functional solution ends up more elegant with something this stateful, but it does have the advantage that the wrong path is usually obvious pretty quickly.


问:
Where is the dynamic memory associated with std::bind?
The problem is that since you can use std:bind in a loop with an arbitrary number of iterations, the storage cannot be inline.  It doesn't appear to be on the heap, since it doesn't appear to generate memory leaks.  It seems, then, that it must be on the stack - SOME stack.  I have an application which could easily do hundreds of thousands of these binds setting up calls to a threader.  Since the caller could presumably go out of scope while the threader is still working, and since the threader needs the bind until it executes the job, that information must be stored SOMEWHERE.  Where is it, and how do I clean it up when the binds have served their purpose?

Example:

```<code>std::function<void()> *Jobs;
Jobs = new std::function<void()> Jobs[nJobs];
for (i=0; i<nJobs; ++i)
{
    Jobs[i] = std::bind (funtion, args, ...);
}
ThreadPool->QueueJobs (Jobs, nJobs); // store POINTERS to jobs
ThreadPool->WaitForCompletion();
delete Jobs;
</code>```

Does this look like it will work?

答:
The return value of std::bind is entirely on the stack. If you just called std::bind and did nothing else with it it would be on the stack and then disappear when it went out of scope.

In order to do anything useful with the result of std::bind you must have explicitly or implicitly made a copy of it, probably to some place in the heap.

For example, if you did this:

```<code>std::function foo(std::bind(this, "yellow"));
</code>```

The std::function will copy the result of std::bind to the heap. When the std::function is destroyed it will automatically release the memory for the copy.

If you did something like:

```<code>vector_of_function.push_back(std::function(std::bind(this, "yellow")));
</code>```

The std::bind will be copied into heap allocated by the std::function and the std::function will be copied into heap allocated by the std::vector. But in neither case do you need to worry about it because the vector and function will take care of deallocation when they are destroyed.

The rule in C++ is that whatever you new you must delete. Since the standard library is responsible for new the copies in these cases, the standard library will delete them.

Body:
The return value of std::bind is entirely on the stack. If you just called std::bind and did nothing else with it it would be on the stack and then disappear when it went out of scope.

In order to do anything useful with the result of std::bind you must have explicitly or implicitly made a copy of it, probably to some place in the heap.

For example, if you did this:

std::function foo(std::bind(this, "yellow"));

The std::function will copy the result of std::bind to the heap. When the std::function is destroyed it will automatically release the memory for the copy.

If you did something like:

vector_of_function.push_back(std::function(std::bind(this, "yellow")));

The std::bind will be copied into heap allocated by the std::function and the std::function will be copied into heap allocated by the std::vector. But in neither case do you need to worry about it because the vector and function will take care of deallocation when they are destroyed.

The rule in C++ is that whatever you new you must delete. Since the standard library is responsible for new the copies in these cases, the standard library will delete them.


问:
Modeling resources with links

Context

To be fully compliant with the REST principles enumerate in Fielding's dissertation, a resource must contains links that redirect to other resources that have a relation with it functionally, like for a bank account that display dynamically a withdraw link, or semantically as it could be related to an other concept related to the resource.

More generally this concept of linking is presented has HATEOAS.
L. Richardson described it very well as part of its Maturity Model (specifically the level 3)

Problem

From a technical point of view, links are not so easy to implement.
I'm facing particularly a problem when modeling my resources in classes. I must associate several fields that corresponds to an URI.
Here is an example of what it looks (based on this example), with a BankingAccount resource describing its characteristic :

```<code>class BankingAccount() {
    Double totalAmount;
    String ownerName;
    URI uriToCloseAccount;
    URI uriToWithdrawMoney;
}
</code>```

Here, the field uriToCloseAccount is a URI (=a link) that redirect to an other resource in order to close the account. In the same mind, an other URI uriToWithdrawMoney will redirect to a resource that process the withdraw.

It could be possible for a client to retrieve this resource through GET (at URI /bankingAccount/[id]) but also update only its owner name, for whatever reason.

Problem

Is it realistic to suppose that a client could update the uriToCloseAccount field of a BankingAccount's resource ?
I'm not completely fine with this. I always assumed in the past, that it's not a client that is responsible of managing URI. They are here just to indicate a path to follow (or the operations to do, depending on the hypermedia format chosen) by the server itself to the client.

So the underlying question is: does links are part of resource model ? Or it is an information that is outside of the model (i don't know, maybe in the format chosen ?)

Thanks in advance !

答:
In the case bellow, no it should not be updated (then again is a uri to close account restful ? or withdraw money ?)

class BankingAccount() {
    Double totalAmount;
    String ownerName;
    URI uriToCloseAccount;
    URI uriToWithdrawMoney;
}

Suppose this is your model:

```<code>{
   "links":{
      "self": "/accounts/ACCOUNT_NUM"
      "owner":"/customers/OWNER",
      "transactions": "/transactions?account=ACCOUNT_NUM"
   }
   "number": "ACCOUNT_NUM",
   "balance": "10000 EUR"
}
</code>```

changing the owner (suppose banks allow that) would be something like:

```<code>PATCH /accounts/ACCOUNT_NUM
{
   "links":{
      "owner":"/customers/NEW_OWNER",
   }
}
</code>```

This of course requires /customers/NEW_OWNER to exist (the client should have checked prior to sending the update.

Now for transactions it obviously makes no sense to update that link. So the API should not allow that.

Whether or not a link is updatable depends on the meaning of the link.

Your internal Application model would of course be different, and does not have to include links

```<code>class BankingAccount() {
  int accountNumber
  Double totalAmount;
  String ownerId;
}
</code>```

But you would need to add some extra mapping while marshalling/unmarshalling to your json, xml or whatever your format is :

accountNumber is transformed to links.self /accounts/accountNumberValue

ownerId is transformed to links.owner /customers/ownerIdValue

add links.transactions so that client can navigate to the current account's transactions => /transactions?account=accountNumberValue

closing an account

As for closing an account (which is not a resource but an operation on a resource) that would be part of the API Docs, for example:
DELETE /accounts/MY_ACCOUNT or:

```<code>PATCH /accounts/MY_ACCOUNT
{
   "status":"closed"
}
</code>```

But then you should add a field status to your account model.

Withdraw money

This could be modeled as an operation on transactions.

```<code>POST /transactions
{
   "links":{
      "account":"/accounts/MY_ACCOUNT"
   },
   "type":"withdraw",
   "amount": "10000 USD"
}
</code>```

Notice that the target account is identified by a link.

Analogy

I know some don't like to make the analogy with databases but sometimes it makes sense to see your resources and resource collections as rows and tables:

```<code>DATABASE      | API
table         | resource collection
row           | resource
primary key   | self link
foreign key   | link to related resource
              |   (identified by resource type name for example)
1,n relation  | link to related collection with filter query
</code>```

SQL

```<code>UPDATE accounts SET owner=OWNER_ID WHERE account=ACCOUNT_ID
INSERT INTO transactions (account,type,amount) VALUE (ACCOUNT_ID,"withdrawal","10000 USD")
SELECT * FROM transactions WHERE account=ACCOUNT_ID
</code>```

API

```<code>PATCH /accounts/ACCOUNT_ID
{
   "links": {
     "owner":"/owners/OWNER_ID"
   }
}

POST /transactions
{
   "links":{
      "account":"/accounts/MY_ACCOUNT"
   },
   "type":"withdraw",
   "amount": "10000 USD"
}

GET /transactions?account=MY_ACCOUNT
</code>```

Why use links for relations instead of plain ids ?

Why not have field ownerId on the account resource instead of  links.owner ?

Having id fields instead of links means the client knows how to construct a url for the resource which is less restful (you know... HATEOAS). But it is your choice as to how restful the API needs to be.

Title: Modeling resources with links

Body:
In the case bellow, no it should not be updated (then again is a uri to close account restful ? or withdraw money ?)

class BankingAccount() {
    Double totalAmount;
    String ownerName;
    URI uriToCloseAccount;
    URI uriToWithdrawMoney;
}

Suppose this is your model:

{
   "links":{
      "self": "/accounts/ACCOUNT_NUM"
      "owner":"/customers/OWNER",
      "transactions": "/transactions?account=ACCOUNT_NUM"
   }
   "number": "ACCOUNT_NUM",
   "balance": "10000 EUR"
}

changing the owner (suppose banks allow that) would be something like:

PATCH /accounts/ACCOUNT_NUM
{
   "links":{
      "owner":"/customers/NEW_OWNER",
   }
}

This of course requires /customers/NEW_OWNER to exist (the client should have checked prior to sending the update.

Now for transactions it obviously makes no sense to update that link. So the API should not allow that.

Whether or not a link is updatable depends on the meaning of the link.

Your internal Application model would of course be different, and does not have to include links

class BankingAccount() {
  int accountNumber
  Double totalAmount;
  String ownerId;
}

But you would need to add some extra mapping while marshalling/unmarshalling to your json, xml or whatever your format is :

accountNumber is transformed to links.self /accounts/accountNumberValue

ownerId is transformed to links.owner /customers/ownerIdValue

add links.transactions so that client can navigate to the current account's transactions => /transactions?account=accountNumberValue

closing an account

As for closing an account (which is not a resource but an operation on a resource) that would be part of the API Docs, for example:
DELETE /accounts/MY_ACCOUNT or:

PATCH /accounts/MY_ACCOUNT
{
   "status":"closed"
}

But then you should add a field status to your account model.

Withdraw money

This could be modeled as an operation on transactions.

POST /transactions
{
   "links":{
      "account":"/accounts/MY_ACCOUNT"
   },
   "type":"withdraw",
   "amount": "10000 USD"
}

Notice that the target account is identified by a link.

Analogy

I know some don't like to make the analogy with databases but sometimes it makes sense to see your resources and resource collections as rows and tables:

DATABASE      | API
table         | resource collection
row           | resource
primary key   | self link
foreign key   | link to related resource
              |   (identified by resource type name for example)
1,n relation  | link to related collection with filter query

SQL

UPDATE accounts SET owner=OWNER_ID WHERE account=ACCOUNT_ID
INSERT INTO transactions (account,type,amount) VALUE (ACCOUNT_ID,"withdrawal","10000 USD")
SELECT * FROM transactions WHERE account=ACCOUNT_ID

API

PATCH /accounts/ACCOUNT_ID
{
   "links": {
     "owner":"/owners/OWNER_ID"
   }
}

POST /transactions
{
   "links":{
      "account":"/accounts/MY_ACCOUNT"
   },
   "type":"withdraw",
   "amount": "10000 USD"
}

GET /transactions?account=MY_ACCOUNT

Why use links for relations instead of plain ids ?

Why not have field ownerId on the account resource instead of  links.owner ?

Having id fields instead of links means the client knows how to construct a url for the resource which is less restful (you know... HATEOAS). But it is your choice as to how restful the API needs to be.


问:
What data type should Gateway return in Repository Pattern to eliminate refactoring when switching persistence mechanisms?
Following this description of the Repository Pattern, we have three main concerns that need their own classes:

The "Repository," which takes and returns Domain Models.

The "Gateway," which takes data from the Domain Model and returns some sort of generic data

The "Factory," which takes the "generic" data from the Gateway and maps it to the Domain Model

A Repository needs two objects in order to do its job:

A "Gateway" for interacting with persistent storage

A "Factory" to translate data from the Gateway into the Domain Model

When dealing with strongly typed languages, every variable needs a "Type." If you specify that Type and use it in your Repository, you are coupling it to the underlying data model of the persistence layer, and then passing it on to the Factory, but the examples I find show the Repository dealing directly with both the Gateway and Factory.

An example of the interfaces for a "Blog"

public interface IBlogGateway
{
    // Returns generic data type so switching persistence
    // does not require refactoring in the Repository
    object Find(long id);
}

public interface IBlogFactory
{
    // Accepts generic data type so switching persistence
    // does not require refactoring in the Repository
    Blog Make(object data);
}

public interface IBlogRepository
{
    Blog Find(long id);
}
```

<p>And the implementation of the interfaces:</p>

<pre class="lang-cs prettyprint-override"><code>public class SqlBlogGateway : IBlogGateway
{
    public object Find(long id)
    {
        DataTable table = // Find from database
        DataRow row = table.Rows.Count == 1
                    ? table.Rows[0]
                    : null;

        // Implicit cast from DataRow to object (this code smells)
        return row;
    }
}

public class SqlBlogFactory : IBlogFactory
{
    public Blog Make(object data)
    {
        // Explicit cast from object to DataRow (this code smells)
        DataRow row = (DataRow)data;
        Blog blog = new Blog(long.Parse(row["ID"].ToString()))
        {
            Title = row.Field<string>("TITLE")
        };

        return blog;
    }
}

public class BlogRepository : IBlogRepository
{
    private IBlogFactory factory;
    private IBlogGateway gateway;

    public BlogRepository(IBlogFactory factory, IBlogGateway gateway)
    {
        this.factory = factory;
        this.gateway = gateway;
    }

    public Blog Find(long id)
    {
        object data = gateway.Find(id);

        if (data == null)
            return null;

        return factory.Make(data);
    }
}
</code>```

Specifically I'm working with C# in .NET, but this is applicable to any strongly typed object oriented language. When persisting to a database, we could deal with DataSet, DataTable and DataRow objects (or array for PHP or HashTable for Java). When it comes time to refactor the "Gateway" to persist to a web service those Types will not suffice, because a web service is not likely to use a DataTable. Instead it will specify it's own Data Transfer Object.

You could have the Gateway return an object type, and the "Factory" take an object type and cast it to the proper type, but then you lose all the benefits of a strongly typed language, such as compile time checking and Intellisense/Auto-Complete in an IDE. Further more if you cast up to object then back down to a type specific to the Gateway, you really can introduce some funky, hard to debug runtime errors. It feels like the Repository needs a Gateway, and a Gateway needs a Factory, but the Repository shouldn't know about the Factory.

To eliminate the need for refactoring the Repository when changing persistence mechanisms, what data type should the Gateway return?

答:
There is one instance where I can see that adding theses extra Gateway and Factory layers could help. That is when you are creating a CRUD style repo per Model

This is often seen with the use of generics. ie

```<code>Repo<Customer> repo = new Repo<Customer>();
Customer c = repo.GetById("1");
</code>```

With this pattern you can see that you can create a generic Repo class if you also have generic Factories/Gateways for the various objects.

In this case they could use/return either the non sql specific DataRow a dictionary of Key Value pairs or similar.

Body:
There is one instance where I can see that adding theses extra Gateway and Factory layers could help. That is when you are creating a CRUD style repo per Model

This is often seen with the use of generics. ie

Repo<Customer> repo = new Repo<Customer>();
Customer c = repo.GetById("1");

With this pattern you can see that you can create a generic Repo class if you also have generic Factories/Gateways for the various objects.

In this case they could use/return either the non sql specific DataRow a dictionary of Key Value pairs or similar.


答:
Ideally, you only want your Gateway class to know what persistence back-end it is talking to, and all the other parts should be agnostic to the back-end. Unfortunately, you are finding that, given this particular implementation, the Factory class cannot be agnostic because it needs to know what type of object it is getting.

You mentioned that you can't just return a DataTable, etc. because a non-database persistence back-end wouldn't use these structures. Can we instead pass an agnostic representation out of the Gateway? Let's look at some options:

Return a DataTable. If you are only going to use database-backed persistence, just do this. It handles a lot of the details for you while being generic across database engines. You don't want to do this because you are worried that a non-database back-end doesn't use this.

Return a simple, custom DTO object from the Gateway. For the IBlogGateway, it might return a BlogDTO object with just data members. This means more classes, but you can return an object with all the correct types already in place. This also creates a dependency on the DTO class in  all of the other classes, but this dependency is reasonable since they all already deal with Blog and BlogDTO will mirror that dependency.

Return a generic container that can be created from any type of persistence. For example, we can convert the DataTable to an IEnumberable<Dictionary<string, object>>, where the enumerable holds the database rows (or web service results, etc.) represented as Dictionarys mapping keys to values. We lose some type information since all the values are objects, but DataRow has a similar limitation that seems otherwise acceptable. This is comparable with the way dynamic languages return results (such as PHP returning an array of associative arrays).

I want to also point out (as @Ewan noted in a comment to the question) that the Gateway, Factory, and Repository don't strictly need to be distinct classes/interfaces. A repository can fill the role of all three, especially when starting out. Later, we can refactor out parts as needed. Even if the gateway is factored out, often the factory and repository can be the same class since they have closely related responsibilities (creating objects of a type).

Contrarily, separating the classes out provides the opportunity for composition, allowing (for example) the gateway to vary in isolation from the rest of the code. Different gateway implementations, corresponding to different back-ends, can be composed in at runtime (and test time) for greater flexibility.

Title: What data type should Gateway return in Repository Pattern to eliminate refactoring when switching persistence mechanisms?

Body:
Following this description of the Repository Pattern, we have three main concerns that need their own classes:

The "Repository," which takes and returns Domain Models.

The "Gateway," which takes data from the Domain Model and returns some sort of generic data

The "Factory," which takes the "generic" data from the Gateway and maps it to the Domain Model

A Repository needs two objects in order to do its job:

A "Gateway" for interacting with persistent storage

A "Factory" to translate data from the Gateway into the Domain Model

When dealing with strongly typed languages, every variable needs a "Type." If you specify that Type and use it in your Repository, you are coupling it to the underlying data model of the persistence layer, and then passing it on to the Factory, but the examples I find show the Repository dealing directly with both the Gateway and Factory.

An example of the interfaces for a "Blog"

public interface IBlogGateway
{
    // Returns generic data type so switching persistence
    // does not require refactoring in the Repository
    object Find(long id);
}

public interface IBlogFactory
{
    // Accepts generic data type so switching persistence
    // does not require refactoring in the Repository
    Blog Make(object data);
}

public interface IBlogRepository
{
    Blog Find(long id);
}
```

<p>And the implementation of the interfaces:</p>

<pre class="lang-cs prettyprint-override"><code>public class SqlBlogGateway : IBlogGateway
{
    public object Find(long id)
    {
        DataTable table = // Find from database
        DataRow row = table.Rows.Count == 1
                    ? table.Rows[0]
                    : null;

        // Implicit cast from DataRow to object (this code smells)
        return row;
    }
}

public class SqlBlogFactory : IBlogFactory
{
    public Blog Make(object data)
    {
        // Explicit cast from object to DataRow (this code smells)
        DataRow row = (DataRow)data;
        Blog blog = new Blog(long.Parse(row["ID"].ToString()))
        {
            Title = row.Field<string>("TITLE")
        };

        return blog;
    }
}

public class BlogRepository : IBlogRepository
{
    private IBlogFactory factory;
    private IBlogGateway gateway;

    public BlogRepository(IBlogFactory factory, IBlogGateway gateway)
    {
        this.factory = factory;
        this.gateway = gateway;
    }

    public Blog Find(long id)
    {
        object data = gateway.Find(id);

        if (data == null)
            return null;

        return factory.Make(data);
    }
}
</code>```

Specifically I'm working with C# in .NET, but this is applicable to any strongly typed object oriented language. When persisting to a database, we could deal with DataSet, DataTable and DataRow objects (or array for PHP or HashTable for Java). When it comes time to refactor the "Gateway" to persist to a web service those Types will not suffice, because a web service is not likely to use a DataTable. Instead it will specify it's own Data Transfer Object.

You could have the Gateway return an object type, and the "Factory" take an object type and cast it to the proper type, but then you lose all the benefits of a strongly typed language, such as compile time checking and Intellisense/Auto-Complete in an IDE. Further more if you cast up to object then back down to a type specific to the Gateway, you really can introduce some funky, hard to debug runtime errors. It feels like the Repository needs a Gateway, and a Gateway needs a Factory, but the Repository shouldn't know about the Factory.

To eliminate the need for refactoring the Repository when changing persistence mechanisms, what data type should the Gateway return?


答:
Examples written in Java. I think something similar can be done in C#.

public interface GenericRow {
  String getString(String fieldName);
  Integer getInteger(String fieldName);
  Long getLong(String fieldName);
  Timestamp getDate(String fieldName);
  // getters for other types
}

public interface BlogGateway {
  GenericRow find(long id);
}
```

<p>The same, but with some degree of <strong>compile-time type-safety</strong> (more elegant IMHO).</p>

<pre class="lang-java prettyprint-override"><code>public interface Row<T extends Enum<T>> {
  String getString(T field);
  Integer getInteger(T field);
  Long getLong(T field);
  Timestamp getDate(T field);
}

public enum BlogField {
  TITLE,
}

public interface BlogGateway {
  Row<BlogField> find(long id);
}
</code>```

Body:
Examples written in Java. I think something similar can be done in C#.

public interface GenericRow {
  String getString(String fieldName);
  Integer getInteger(String fieldName);
  Long getLong(String fieldName);
  Timestamp getDate(String fieldName);
  // getters for other types
}

public interface BlogGateway {
  GenericRow find(long id);
}

The same, but with some degree of compile-time type-safety (more elegant IMHO).

public interface Row<T extends Enum<T>> {
  String getString(T field);
  Integer getInteger(T field);
  Long getLong(T field);
  Timestamp getDate(T field);
}

public enum BlogField {
  TITLE,
}

public interface BlogGateway {
  Row<BlogField> find(long id);
}


答:
You have to remember that the customer of the company who employs you as a developer has different goals to the company who employs you.

The product owner has to represent the goals of your company rather the goals of the customer. So if the devs go straight to the customer they can undermine thier own company.


问:
When returning from a period of not programming, do you find you've improved?
It seems as though whenever I take an extended break from programming—whether to pursue other interests or simply because I fall out of the habit for a while—I invariably find that when I return to a project and set to coding, I come with an abundance of new ideas, novel approaches, and just plain better code. It may be because I have a lot of other creative interests besides programming, and my mind likes to find correlation and crossover between them, so while I'm doing one thing, in the back of my mind I'm usually also applying it to another.

So what's your experience? Do you ever return from a break (whether intentional or not) feeling not only refreshed, but also somehow noticeably improved? Is it actually the norm?

答:
I do think that small breaks / periods of not programming can be useful, as they will clear you mind and take you away from the annoyances of programming.

I do, however, find longer periods of not programming to be quite the opposite. I have found that if I have several months of not programming, then I "suck" (In lack of better word) at it when I return.

Even though I have 6-7 years of experience with PHP, then when I started working again a couple of months ago, after a break for several months, where I focused on my study, I had to "get back to it", before I could really work again, which put me right back to the annoyances of programming, and therefore I didn't get much out of my "break".


问:
Which pattern best describes decoupling file building from output file format?
A common feature we have is a report be available available in multiple formats. For example, a pricing report will be available as an Excel spreadsheet for the marketing team to be able to tweak the numbers, as a PDF report to look nice for external customers, and as ASCII text for emailing/SMS-ing out the sales staff.

We accomplish this by decoupling the creation of the output with the report using an interface like

```<code>public interface DocumentMaker{
    void makeSectionHeader( String s );
    void makeParagraph( String s );
    void makeFootnote( String s );
    ...
    String make();
}
</code>```

et cetera. The report logic itself then calls these methods without knowing what the final format of the report it will be.

We end up referring to this pattern as the "builder pattern" (and often use that as our naming) but it does not feel like that is an appropriate application of the pattern. The builder pattern is described as:

Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.

However, we aren't really interested in the object returned, and often all variations return the same type (eg. String).

It actually, seems closer to the strategy pattern which is described as:

The strategy pattern defines a family of algorithms, encapsulates each algorithm, and makes the algorithms interchangeable within that family.
  Strategy lets the algorithm vary independently from clients that use it

Which sounds more like we are doing.

Although a colleague suggests that they are abstract factories:

The client doesn't know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.

So, is what we are doing appropriate to call the "builder pattern"? If not, is there a more appropriate pattern to call it?

答:
Your class is definitely a Builder. I would change some names to be more consistent with other implementations of this pattern.

public interface DocumentBuilder {
  void addSectionHeader(String s);
  void addParagraph(String s);
  void addFootnote(String s);
  ...
  String build();
}
```

Factories and strategies (typically) accomplish a task within single method invocation.

Body:
Your class is definitely a Builder. I would change some names to be more consistent with other implementations of this pattern.

public interface DocumentBuilder {
  void addSectionHeader(String s);
  void addParagraph(String s);
  void addFootnote(String s);
  ...
  String build();
}

Factories and strategies (typically) accomplish a task within single method invocation.


答:
If the whole file is small enough to fit into memory, then I think one way would be to parse the file into a list and then process the list piece by piece, something like:

let parseItem (columnsString::rowsString::rest) =
    let columns = int columnsString
    let rows = int rowsString
    let position, rest = parsePosition rest
    let calibration, rest = parseCalibration rest
    let points, rest = parsePoints columns rows rest
    (columns, rows, position, calibration, points), rest

let rec parseItems = function
    | [] -> []
    | lines ->
        let item, restLines = parseItem lines
        let restItems = parseItems restLines
        item :: restItems
```

<p>As you surely noticed, this code is pretty repetitive, but you can simplify it using the state workflow (known as state monad in Haskell) from ExtCore:</p>

<pre class="lang-fs prettyprint-override"><code>let parseItem =
    state {
        let! columns = parseInt
        let! rows = parseInt
        let! position = parsePosition
        let! calibration = parseCalibration
        let! points = parsePoints columns rows
        return columns, rows, position, calibration, points
    }

let rec parseItems = function
    | [] -> [], []
    | lines ->
        state {
            let! item = parseItem
            let! restItems = parseItems
            return item::restItems
        } <| lines
</code>```

Title: Split a File into Multiple Objects Functionally

Body:
I want to read a file into a collection of objects. The data (it's a Leica PTX file if you're curious) is formatted as follows:

```<code>640 [begin item #1: number of columns]
480 [number of rows]
0 0 0 [position information: 3x3 matrix]
0 0 0 [position ctd]
0 0 0 [position ctd]
1 0 0 0 [calibration information: 3x4 matrix]
0 1 0 0 [calibration ctd]
0 0 1 0 [calibration ctd]
1.1 2.2 3.3 0.5 [point 1: X Y Z I]
-0.2 2.3 1.4 0.2 [point 2: X Y Z I]
...
3.9 1.2 -7.7 0.8 [point n: X Y Z I]
640 [begin item #2: number of columns]
480 [number of rows]
0 0 0 [position information]
0 0 0
0 0 0
1 0 0 0 [calibration information]
0 1 0 0
0 0 1 0
0.2 1.3 -2.1 0.4 [point 1 of item #2]
... [etc]
</code>```

I.e. Two lines each containing a single float/double (as text) signal the beginning of a new item, and no other lines are exactly one number.

It's easy to do if there's only one item per file, it's a simple fold operation. It would also be relatively straightforward to do with a while type loop that keeps state, but I'm new to functional programming and wondering if there isn't a more concise and elegant way to do this functionally with standard tools (like reduce, fold, split/partition, etc). The best solutions I've come up with so far involve "peeking" ahead using lists or arrays, but I'd like something that allows for the possibility of a sequence that is consumed as it iterates for maximum generality. (I'm using F# and .NET but I don't see this as a language-specific problem.)

Body:
If the whole file is small enough to fit into memory, then I think one way would be to parse the file into a list and then process the list piece by piece, something like:

let parseItem (columnsString::rowsString::rest) =
    let columns = int columnsString
    let rows = int rowsString
    let position, rest = parsePosition rest
    let calibration, rest = parseCalibration rest
    let points, rest = parsePoints columns rows rest
    (columns, rows, position, calibration, points), rest

let rec parseItems = function
    | [] -> []
    | lines ->
        let item, restLines = parseItem lines
        let restItems = parseItems restLines
        item :: restItems

As you surely noticed, this code is pretty repetitive, but you can simplify it using the state workflow (known as state monad in Haskell) from ExtCore:

let parseItem =
    state {
        let! columns = parseInt
        let! rows = parseInt
        let! position = parsePosition
        let! calibration = parseCalibration
        let! points = parsePoints columns rows
        return columns, rows, position, calibration, points
    }

let rec parseItems = function
    | [] -> [], []
    | lines ->
        state {
            let! item = parseItem
            let! restItems = parseItems
            return item::restItems
        } <| lines


问:
Is it a good idea to make method behavior depend on the calling thread?
I want to subclass a 3rd party class, in order to make it thread-safe.

I have a good idea of how to implement this, but there is a problem: the superclass has a property, which affects the behaviour of one of its methods. If one thread sets the property, it will interfere with the other threads when they call the method.

I can see two ways to do this:

Create a thread-safe 'stateless' object which then has multiple 'views' into it. The property is in the view and each thread has its own view instance.

Detect which thread makes the call in the property's get accessor and the method, and store the state for that thread internally.

(1) is self-explanatory, but it involves more boilerplate code. (2) does something non-trivial behind the scenes, but if it works, it is completely transparent.

Which is best, for maintainability and readability? The more complex code but whose behaviour is up-front, or the code which is easier to use when it works, but if it breaks it will do so in a location and way which is not obvious?

Is there any reason an object should not be dependent on what thread interacts with it?

(EDIT: Removing reference to the 3rd party class, since the requirements of the implementation are not as simple as it sounds and it was generating more confusion than needed!)

答:
The idea of having a thread-specific variable is not unreasonable, though I am unsure if it is appropriate for your use case.  The idea of a thread-safe Stream strikes me as a bit broken; I would rather have a thread-safe StreamFactory.

The best way to implement a thread-specific state variable is to use either ThreadStatic or ThreadLocal<T>.  This makes your code short, simple, and trivially maintainable.  This variable will be a member of your Stream.

See ThreadStatic v.s. ThreadLocal: is generic better than attribute? for discussion on which to use (short version: use ThreadLocal<T> if you're on .Net 4+).


答:
This does not answer your question, but:

It is not a good idea to subclass a 3rd party class, in order to make it thread-safe. Author most likely did not think of thread safety when designing the class, so it will be very hard to add it by subclassing, if even possible. Thinking about polymorphism and thread safety at the same time is just too much. What if the implementation of the class will change?

It is not a good idea to make a thread-safe stream. Stream can not be read by two readers at the same time, so why bother to access it from multiple threads? Accidental complexity.

Title: Is it a good idea to make method behavior depend on the calling thread?

Body:
I want to subclass a 3rd party class, in order to make it thread-safe.

I have a good idea of how to implement this, but there is a problem: the superclass has a property, which affects the behaviour of one of its methods. If one thread sets the property, it will interfere with the other threads when they call the method.

I can see two ways to do this:

Create a thread-safe 'stateless' object which then has multiple 'views' into it. The property is in the view and each thread has its own view instance.

Detect which thread makes the call in the property's get accessor and the method, and store the state for that thread internally.

(1) is self-explanatory, but it involves more boilerplate code. (2) does something non-trivial behind the scenes, but if it works, it is completely transparent.

Which is best, for maintainability and readability? The more complex code but whose behaviour is up-front, or the code which is easier to use when it works, but if it breaks it will do so in a location and way which is not obvious?

Is there any reason an object should not be dependent on what thread interacts with it?

(EDIT: Removing reference to the 3rd party class, since the requirements of the implementation are not as simple as it sounds and it was generating more confusion than needed!)


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答: XML is like violence - if it doesn’t solve your problems, you are not using enough of it.</p>

LastEditorDisplayName: Roger Pate