问:
Legitimate cases of having .equals() behaving inconsistently with .compareTo()?
Java documentation says it's "strongly recommended" to have them behaving consistently.

But are there legitimate cases of java/c#/python/etc Object.equals() method behaving inconsistently with the method Comparable.compareTo()?

答:
The reason you have two different methods is that they do two different things.

The .equals method returns a boolean value indicating whether the object on which you call the method is equal to the object passed in as a parameter  (for some definition of "is equal to" that is consistent with the nature of the object being compared).

The .compareTo method returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.  That makes it a useful method for sorting; it allows you to compare one instance with another for purposes of ordering.

When the Java documentation says that these two methods must behave consistently, what they mean is that the .equals method must return true in exactly the same situations where the .compareTo method returns zero, and must return false in exactly the same situations where the .compareTo method returns a nonzero number.

Is there any good reason to violate these rules?  Generally no, for the same reasons that

```<code>#define TRUE FALSE
</code>```

is a really bad idea.  The only legitimate reason for inconsistent behavior is hinted at in the Java documentation itself: "[if the] class has a natural ordering that is inconsistent with equals."

To drive home the point, you can actually define .equals() in terms of compareTo(), thus guaranteeing consistent behavior.  Consider this .equals() method from a Rational class which, after a few sanity checks, simply defines .equals as compareTo() == 0:

```<code>public boolean equals(Object y) {
    if (y == null) return false;
    if (y.getClass() != this.getClass()) return false;
    Rational b = (Rational) y;
    return compareTo(b) == 0;
}
</code>```

Body:
The reason you have two different methods is that they do two different things.

The .equals method returns a boolean value indicating whether the object on which you call the method is equal to the object passed in as a parameter  (for some definition of "is equal to" that is consistent with the nature of the object being compared).

The .compareTo method returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.  That makes it a useful method for sorting; it allows you to compare one instance with another for purposes of ordering.

When the Java documentation says that these two methods must behave consistently, what they mean is that the .equals method must return true in exactly the same situations where the .compareTo method returns zero, and must return false in exactly the same situations where the .compareTo method returns a nonzero number.

Is there any good reason to violate these rules?  Generally no, for the same reasons that

#define TRUE FALSE

is a really bad idea.  The only legitimate reason for inconsistent behavior is hinted at in the Java documentation itself: "[if the] class has a natural ordering that is inconsistent with equals."

To drive home the point, you can actually define .equals() in terms of compareTo(), thus guaranteeing consistent behavior.  Consider this .equals() method from a Rational class which, after a few sanity checks, simply defines .equals as compareTo() == 0:

public boolean equals(Object y) {
    if (y == null) return false;
    if (y.getClass() != this.getClass()) return false;
    Rational b = (Rational) y;
    return compareTo(b) == 0;
}


问:
Software pattern for combining properties
I have two classes that read distinct files. As an examples, two classes, sourceA or Client, and sourceB or Resources:

```<code>public class Client()
{
    public string ClientName {get; set;}
    public int ClientNumber {get; set;}
    public string Address {get; set;}
    //...
}

public class Resources()
{
    public int ClientNumber {get; set;}
    public decimal Resources {get; set;}
    //...
}
</code>```

Let's say that I need to merge booth classes into a new one, but I just need some fields from class Client and Resources. Is there any software pattern motivated by something like this, to compose a class like ClientReport?

The new class should be something like this:

```<code>public class ClientReport()
{
    public string ClientName {get; set;}
    public int ClientNumber {get; set;}
    public string Address {get; set;}
    public decimal Resources {get; set;}

    public int CalculateRating()
    {
        //...
    }
}
</code>```

These new classe will have some properties of Client and Resources, and copying code from them in order to create ClientReport seems to be a repetition, and I think it should be a away to compose this class and only use the needed properties from Client and Resources.

答:
If I understand your question, the Facade Pattern fits your needs:

Intent:

Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem
  easier to use.

Wrap a complicated subsystem with a simpler interface.

Your Facade, the ClientReport class, has classes SourceA and SourceB by composition. The simpler, unified interface provided by ClientReport delegates to the appropriate methods of SourceA and SourceB; however, the client deals only with the ClientReport interface.

The link above has this checklist for using the Facade pattern:

Identify a simpler, unified interface for the subsystem or
  component.

Design a 'wrapper' class that encapsulates the subsystem.

The facade/wrapper captures the complexity and collaborations of the
  component, and delegates to the appropriate methods.

The client uses (is coupled to) the Facade only.

Consider whether additional Facades would add value.

ContentLicense: CC BY-SA 3.0


问:
How does modulus work?
I am not asking asking how the mathematical concept of modulus works, or how 20 % 3 == 2 I understand this fine. I'm more curious how the compiler/interpreter determines this. I can think of a very naive way to do it, like so:

```<code>int modulus(int a, int b)
{
    while (a > b)
    {
        a -= b;
    }
return a;
}
</code>```

(obviously this needs a few more cases because a can be smaller then b, but you get the idea.) But this would would have some serious performance issues. I threw together some C++ to test the efficiency of both the modulus operator and my naive function.

```<code>#include <iostream>
#include <chrono>
#include <limits>
#include "chrono_io"
using namespace std;

typedef chrono::high_resolution_clock Clock;

int mod(int a, int b)
{
    while (a > b)
    {
        a -= b;
    }
    return a;
}

int main()
{
    auto start = Clock::now();
    cout << 20 % 3 << endl;
    auto end = Clock::now();
    cout << "Modulus on a small number took "  << end - start << " seconds to calculate.\n";

    start = Clock::now();
    cout << numeric_limits<int>::max() % 3 << endl;
    end = Clock::now();
    cout << "Modulus on a large number took "  << end - start << " seconds to calculate.\n";

    start = Clock::now();
    cout << mod(20, 3) << endl;
    end = Clock::now();
    cout << "My modulus function on a small number took "  << end - start << " seconds to calculate.\n";

    start = Clock::now();
    cout << mod(numeric_limits<int>::max(), 3) << endl;
    end = Clock::now();
    cout << "My modulus function on a large number took "  << end - start << " seconds to calculate.\n";
}
</code>```

and the output is:

```<code>2
Modulus on a small number took 43629 nanoseconds seconds to calculate.
1
Modulus on a large number took 5644 nanoseconds seconds to calculate.
2
My modulus function on a small number took 3682 nanoseconds seconds to calculate.
1
My modulus function on a large number took 2153824554 nanoseconds seconds to calculate.
</code>```

The modulus operator varied from 4,000-70,000 nanoseconds. My function always won on the small numbers, but took around 2 seconds on the large number. Since the modulus operator is so much more consistent, I assume that it compares the number on a bitwise level.

So how does the modulus operator work? I can think of some cases that would be very easy to determine. For example, with mod 2, you can just look at the very last byte. Or with mod 4 you can look at the second to last byte. But not all numbers have such a simple pattern.

答:
Nearly all CPUs have a single instruction that will return the modulus of a value.  For instance, consider this program:

```<code>int main()
{
    int i = 10;
    return i % 3;
}
</code>```

If I compile this on my Intel OS X machine using g++ -S, the result will be some boilerplate and this:

```<code>movl    $3, %eax
movl    $0, -4(%rbp)
movl    $10, -8(%rbp)
movl    -8(%rbp), %ecx
movl    %eax, -12(%rbp)         ## 4-byte Spill
movl    %ecx, %eax
cltd
movl    -12(%rbp), %ecx         ## 4-byte Reload
idivl   %ecx
movl    %edx, %eax
</code>```

The actual modulus happens with this instruction: idivl %ecx.  When this instruction executes, the quotient will be placed in in %eax and the remainder will be placed in in %edx.

Since really, this means the % operation is only going to take a few clock cycles, the bulk of which is actually moving the data into the right register.  Also note that with Intel at least, the same operation finds both the quotient and the remainder, so in reference to your comment, / and % take exactly the same time.  It is the same operation.  The only thing that changes is what register the compiler gets the results from.

With any CPU made in the last couple decades, you can assume that any basic mathematical operation (including things that look like library functions like sqrt or cos) is actually a single machine instruction and generally only take a few clock cycles at most.

[UPDATE]

As people have noted in the comments, to see something approaching a correct timing, you need to remove the output from the timed section like this:

```<code>int i;
auto start = Clock::now();
i = 20 % 3;
auto end = Clock::now();
cout << i << endl;
</code>```

But even that is likely not accurate as the actual granularity of the timings may exceed what you are trying to time.  Instead, you might want to do this:

```<code>int i=0;
int x;
auto start = Clock::now();
for(i=0;i<1000000;i++)
    x = i % 3;
auto end = Clock::now();
cout << i << endl;
</code>```

Then divide your timing by 1,000,000.  (This will be slightly high as it includes the time taken for an assignment, a comparison and an increment.)  On my machine, this gives a time of 5 nanoseconds.

Title: How does modulus work?

Body:
Nearly all CPUs have a single instruction that will return the modulus of a value.  For instance, consider this program:

int main()
{
    int i = 10;
    return i % 3;
}

If I compile this on my Intel OS X machine using g++ -S, the result will be some boilerplate and this:

movl    $3, %eax
movl    $0, -4(%rbp)
movl    $10, -8(%rbp)
movl    -8(%rbp), %ecx
movl    %eax, -12(%rbp)         ## 4-byte Spill
movl    %ecx, %eax
cltd
movl    -12(%rbp), %ecx         ## 4-byte Reload
idivl   %ecx
movl    %edx, %eax

The actual modulus happens with this instruction: idivl %ecx.  When this instruction executes, the quotient will be placed in in %eax and the remainder will be placed in in %edx.

Since really, this means the % operation is only going to take a few clock cycles, the bulk of which is actually moving the data into the right register.  Also note that with Intel at least, the same operation finds both the quotient and the remainder, so in reference to your comment, / and % take exactly the same time.  It is the same operation.  The only thing that changes is what register the compiler gets the results from.

With any CPU made in the last couple decades, you can assume that any basic mathematical operation (including things that look like library functions like sqrt or cos) is actually a single machine instruction and generally only take a few clock cycles at most.

[UPDATE]

As people have noted in the comments, to see something approaching a correct timing, you need to remove the output from the timed section like this:

int i;
auto start = Clock::now();
i = 20 % 3;
auto end = Clock::now();
cout << i << endl;

But even that is likely not accurate as the actual granularity of the timings may exceed what you are trying to time.  Instead, you might want to do this:

int i=0;
int x;
auto start = Clock::now();
for(i=0;i<1000000;i++)
    x = i % 3;
auto end = Clock::now();
cout << i << endl;

Then divide your timing by 1,000,000.  (This will be slightly high as it includes the time taken for an assignment, a comparison and an increment.)  On my machine, this gives a time of 5 nanoseconds.


问:
How do I model this relationship so that it is valid by construction?
Imagine a device class that represents a physical real world mobile device, with fields like Enabled, Platform, Model IMEI, etc. Then, an operation class, which is something that needs to be done to a certain device, like DeviceEnablementOperation or LockOperation. This is a 'one device to many operations' relationship, and an operation cannot exist without being related to an existing device. Can I model this in such a way that the system will not allow certain types of operations to devices with certain platforms? For example, an Android device would not allow a DeviceEnablementOperation attached to it, while a Windows Phone device would.

Our current modeling started out considering only Android devices. At the time, we created the concept of operations as a poor man's event source, so that we could track what was done against a certain device via our API. Later on, we started supporting iOS devices too, and we introduced the Platform field using an enumeration class to differentiate them, like this:

public enum PlatformType : short
{
    ///
    /// Device is an Android.
    ///
    Android = 0,

    ///
    /// Device is an Windows platform.
    ///
    Windows = 1,

    //// Can not place the name iOS.

    ///
    /// Device is an iOS platform.
    ///
    Ios = 2,
}
```

<p>At that point in time, the requirements were being met correctly, but now we need to restrict certain types of operations to certain platforms. The current model does not automatically restrict this, so the current implementation considers a hardcoded list of supported operations for each platform, and uses this to reject the creation of some operations to certain devices.</p>

<p>What I'd like to do is change the modelling so that this restriction is more robustly enforced. I thought about using inheritance and creating <code>AndroidDevice</code>, <code>IosDevice</code> and <code>WindowsPhoneDevice</code> classes, but I still fail to see how I could restrict the relationship with operations themselves to cover this requirement. A device has operations, but not all devices support all operations.</p>

<p>The modelling for the operations themselves is very straightforward inheritance, like this:</p>

<pre class="lang-cs prettyprint-override"><code>public abstract class Operation
{
    protected Operation()
    {
        this.Logs = new List<OperationLog>();
    }

    public DateTime? CreationDate { get; set; }

    public virtual Device Device { get; set; }

    public int DeviceId { get; set; }

    public OperationStatus GeneralStatus { get; set; }

    public int Id { get; set; }

    public DateTime? LastUpdate { get; set; }

    public ICollection<OperationLog> Logs { get; internal set; }

    public DateTime? ReceiveDate { get; set; }
}
</code>```

And then derived operation types, like the ones I mentioned:

public sealed class LockOperation : Operation
{
    ///
    /// Gets or sets a value indicating whether the device must be locked or not.
    ///
    public bool Lock { get; set; }

    ///
    /// Gets or sets the device's lock password.
    ///
    public string Password { get; set; }
}
```

<p>and</p>

<pre class="lang-cs prettyprint-override"><code>public sealed class EnablementOperation : Operation
{
    /// <summary>
    /// Gets or sets a value indicating whether the device should be enabled or disabled.
    /// </summary>
    public bool Enabled { get; set; }
}
</code>```

Is it possible to model this to better reflect the new requirement that I want? I'd somehow need a way to tell if a given operation is supported for a given device, and only allow the relationship to exist if the operation was supported.

I suppose I could try something using generics and inheritance on both the device and operation classes, for example:

public abstract class Device<TOperation>
{
    public ICollection<TOperation> Operations { get; set; }
    ...
}

public sealed class AndroidDevice : Device<AndroidOperation> {...}

public abstract class Operation {...}

public abstract class AndroidOperation {...}

public sealed LockOperation : AndroidOperation {...}
```

But this particular approach would need multiple inheritance to work, and since I'm using C# it is not possible. I could then try using interfaces to differentiate operations, but them I suspect it would be a problem when mapping this to a database later using an ORM.

I also can't really break everything into their own completely isolated classes, because I need the general concept of "devices that have operations", regardless of platform or operation type. That's why the base classes exist in our current model.

答:
If you worry about ORM persistence, then here's a possible solution:

Each operation declares its supported platform, similar to interface approach but use flags property instead (please note I change your enum to flags and add an option for unknown type)

[Flags]
public enum PlatformType : short
{
    Unknown = 0,
    ///
    /// Device is an Android.
    ///
    Android = 1,

    ///
    /// Device is an Windows platform.
    ///
    Windows = 2,

    //// Can not place the name iOS.

    ///
    /// Device is an iOS platform.
    ///
    Ios = 4
}

public abstract class Operation
{
    public string Name { get; set; }
    public abstract PlatformType SupportedPlatforms { get; }

    //Other properties
}

public sealed class DeviceEnablementOperation : Operation
{
    public override PlatformType SupportedPlatforms
    {
        get
        {
            return PlatformType.Windows | PlatformType.Ios;
        }
    }

    //Other properties
}
```

<p>The abstract devices class will contain list of operations and ensure to accept only operations it supports (in constructor and AddOperation() method). It will throw exception immediately when violated so that developer can recognize quickly:</p>

<pre class="lang-cs prettyprint-override"><code>public abstract class Device
{
    public PlatformType Platform { get; private set; }
    private ICollection<Operation> _operations;

    protected Device(PlatformType platform)
    {
        Platform = platform;
        _operations = new List<Operation>();
    }

    protected Device(PlatformType platform, ICollection<Operation> operations)
    {
        Platform = platform;

        var violatedOperation = operations.FirstOrDefault(o => !OperationSupportedByThisDevice(o));
        if(violatedOperation != null)
        {
            throw new ApplicationException(string.Format("Operation {0} not supported by platform {1}", violatedOperation.Name, Platform));
        }

        _operations = operations;
    }

    public void AddOperation(Operation operation)
    {
        if(!OperationSupportedByThisDevice(operation))
        {
            throw new ApplicationException(string.Format("Operation {0} not supported by platform {1}", operation.Name, Platform));
        }

        _operations.Add(operation);
    }

    private bool OperationSupportedByThisDevice(Operation operation)
    {
        return operation.SupportedPlatforms.HasFlag(Platform);
    }
}

public class AndroidDevice : Device
{
    public AndroidDevice() : base(PlatformType.Android)
    {
    }

    public AndroidDevice(ICollection<Operation> operations) : base(PlatformType.Android, operations)
    {
    }
}
</code>```

So if an android device is created like this, it will throw exception since DeviceEnablementOperation is not supported by android device:

var androidDevice = new AndroidDevice(new List<Operation> { new DeviceEnablementOperation() });
```

If you worry about the flags usage for PlatformType for device (.i.e. an device can be mistakenly assigned with multiple platforms), then create a separate flags enum for operation, but you get the idea

Body:
If you worry about ORM persistence, then here's a possible solution:

Each operation declares its supported platform, similar to interface approach but use flags property instead (please note I change your enum to flags and add an option for unknown type)

[Flags]
public enum PlatformType : short
{
    Unknown = 0,
    /// <summary>
    /// Device is an Android.
    /// </summary>
    Android = 1,

    /// <summary>
    /// Device is an Windows platform.
    /// </summary>
    Windows = 2,

    //// Can not place the name iOS.

    /// <summary>
    /// Device is an iOS platform.
    /// </summary>
    Ios = 4
}

public abstract class Operation
{
    public string Name { get; set; }
    public abstract PlatformType SupportedPlatforms { get; }

    //Other properties
}

public sealed class DeviceEnablementOperation : Operation
{
    public override PlatformType SupportedPlatforms
    {
        get
        {
            return PlatformType.Windows | PlatformType.Ios;
        }
    }

    //Other properties
}

The abstract devices class will contain list of operations and ensure to accept only operations it supports (in constructor and AddOperation() method). It will throw exception immediately when violated so that developer can recognize quickly:

public abstract class Device
{
    public PlatformType Platform { get; private set; }
    private ICollection<Operation> _operations;

    protected Device(PlatformType platform)
    {
        Platform = platform;
        _operations = new List<Operation>();
    }

    protected Device(PlatformType platform, ICollection<Operation> operations)
    {
        Platform = platform;

        var violatedOperation = operations.FirstOrDefault(o => !OperationSupportedByThisDevice(o));
        if(violatedOperation != null)
        {
            throw new ApplicationException(string.Format("Operation {0} not supported by platform {1}", violatedOperation.Name, Platform));
        }

        _operations = operations;
    }

    public void AddOperation(Operation operation)
    {
        if(!OperationSupportedByThisDevice(operation))
        {
            throw new ApplicationException(string.Format("Operation {0} not supported by platform {1}", operation.Name, Platform));
        }

        _operations.Add(operation);
    }

    private bool OperationSupportedByThisDevice(Operation operation)
    {
        return operation.SupportedPlatforms.HasFlag(Platform);
    }
}

public class AndroidDevice : Device
{
    public AndroidDevice() : base(PlatformType.Android)
    {
    }

    public AndroidDevice(ICollection<Operation> operations) : base(PlatformType.Android, operations)
    {
    }
}

So if an android device is created like this, it will throw exception since DeviceEnablementOperation is not supported by android device:

var androidDevice = new AndroidDevice(new List<Operation> { new DeviceEnablementOperation() });

If you worry about the flags usage for PlatformType for device (.i.e. an device can be mistakenly assigned with multiple platforms), then create a separate flags enum for operation, but you get the idea


问:
Parallelising processing of users
Update I updated my question to reflect the fact I'm working with a database.
I need to process user actions:

The actions for each user change the user's balance which is then persisted to a database.

A user's action must be processed sequentially. Otherwise, we might corrupt the balance in the database.

Some actions are associated with 2 users in which case they can't run in parallel with either user's actions.

The volume of actions per user varies considerably during the day.

Update The processes are going to be distributed over several machines.

I am trying to find a way to distribute the actions between processes so that the above requirements are met.

Is there a known paradigm, architecture or algorithm that solves such a problem?

I'm looking for a solution that does not involve processes talking to each other except through a message queue or some other scalable mediator.

答:
A simple greedy approach should fulfill your requirements. I assume you have an ordered input queue with all actions to process, and a list of actions associated with corresponding users currently under (parallel) processing (lets call these "users under processing"). Whenever the processing of one action is done, it is removed, and you check the next elements from your input queue which ones can be added as next without a collision with the users under processing. Note that you check the full queue in order, not just the top element.

You can add new actions to the processing list as long you have actions for users currently not under processing. If you need to restrict the number of processes in parallel to some number N, that's easily done by not adding more than N actions to the currently processed acctions.

Title: Parallelising processing of users


问:
Is there a name for refactoring technique that turns hardcoded values into configurable parameters?
What is that technique called when you take values in the code that are hardcoded and make them variable, possibly constructing elaborate OO constructs to make that variable properly configurable?

For example you are printing labels, and you are specifying a value of labels to print per page, like say 4.

Later you realize you have different label sizes, and shapes.  You construct a label factory, which calls proper label files, which also configure themselves and know their own size in relation to the page which is then returned via a function call using polymorphism, and that value is then used instead of the hardcoded 4.

In my own words I can describe it as

Refactoring in effort to increase configurability and flexibility of the software.

but as far as naming specific technique, no..

答:
Often among my friends we would call this softcoding. It's a play on words to imply the opposite of hardcoding and has the nice advantage that it's recognizable for most programmers.

More technically, if I were to describe it in documentation it would simply be "making the software more configurable" or variations of such.

In math related software I sometimes hear it being called parameterizing the code. Or parameterization. It's the name of the process of making equations able to change behavior by changing variables (parametric equations).


问:
is OOP the dominant programming model in real world?
Objects Never? Well, Hardly Ever

In the VIEWPOINT section of Communications of The ACM, I found an
interesting article entitled "Objects Never? Well, Hardly Ever".
It’s a radically different perspective than objects-first or objects-late. He suggests "objects-never" or maybe "objects-graduate school".

The author talked about OOP and made a question about how OOP is used
in real world programming environments. He thinks that OOP is not the
dominant programming model. For example, he claims, 70% of
programmings are done for Embedded Systems where OOP is not really
suited.

When some professors in universities wants to talk about the benefits
of OOP, they talk about code-reuse. As another example, again, he
claims, this is not the real case in real world. code-reuse is harder
than what's claimed in universities:

I claim that the use of OOP is not as prevalent as most people believe, that it is not as successful as its proponents claim, and, therefore, that its central place in the CS curriculum is not justified.

It's interesting for me to know how people in stack-overflow think
about this? Is OOP the dominant programming model from programmers'
point of view?

If I should choose/learn/use just one approach, is it OOP or not? why?

答:
Where are all the developers doing those "70% of programmings"? out of all the developers I know less than 1% are working on Embedded systems.

So, we have 3 options:

I'm unique and all your friends really do embedded programing

There are armies of developers locked in a basement somewhere doing those 70%

this statistic is made up and the article is bullshit

unless I see some evidence that options 1 or 2 are actually true I'm going with option 3.

(BTW, I do not consider modern mobile development embedded programing, and mobile development  is often OO, after all Apple forces you to use *Objective*C to develop for the iPhone)

ContentLicense: CC BY-SA 2.5


答:
I would suggest you look into scheduling algorithms:
a list of scheduling algorithms by category here

and partial order relations to make sure the order of the actions of a given user is respected. You can generate a tree of dependencies using the relations which would help you in scheduling.

Title: Parallelising processing of users

Body:
Update I updated my question to reflect the fact I'm working with a database.
I need to process user actions:

The actions for each user change the user's balance which is then persisted to a database.

A user's action must be processed sequentially. Otherwise, we might corrupt the balance in the database.

Some actions are associated with 2 users in which case they can't run in parallel with either user's actions.

The volume of actions per user varies considerably during the day.

Update The processes are going to be distributed over several machines.

I am trying to find a way to distribute the actions between processes so that the above requirements are met.

Is there a known paradigm, architecture or algorithm that solves such a problem?

I'm looking for a solution that does not involve processes talking to each other except through a message queue or some other scalable mediator.


答:
Martin Fowler (author of the book "Refactoring") would probably do this in more than one step. These steps could be, for example, Replace Magic Number with Symbolic Constant" to replace 4 by a symbol LabelsPerPage, then Add Parameter to replace the constant by a parameter of the method where it is used. Later, Replace Parameter with Method could be the first step to provide the labels per page through a method which can be made polymorphic afterwards through Replace Type Code With Polymorphism.

(see http://www.refactoring.com/catalog/)

Title: Is there a name for refactoring technique that turns hardcoded values into configurable parameters?

Body:
What is that technique called when you take values in the code that are hardcoded and make them variable, possibly constructing elaborate OO constructs to make that variable properly configurable?

For example you are printing labels, and you are specifying a value of labels to print per page, like say 4.

Later you realize you have different label sizes, and shapes.  You construct a label factory, which calls proper label files, which also configure themselves and know their own size in relation to the page which is then returned via a function call using polymorphism, and that value is then used instead of the hardcoded 4.

In my own words I can describe it as

Refactoring in effort to increase configurability and flexibility of the software.

but as far as naming specific technique, no..


答:
I wouldn't call this refactoring, as it adds functionality (you can now have other numbers of labels per page). Refactoring is making changes to the code without changing the functionality.

What you are doing is adding a layer of abstraction. Maybe multiple layers, it depends on how you like to count these things -- the Label classes and their machinery are a clear new layer of abstraction, but is a LabelFactory its own layer? It doesn't really matter.


问:
Are there any good reasons to use ER Diagrams instead of UML Class Diagrams for data modeling? Is ERD the COBOL of data modeling?
Are there any good reasons to use ER Diagrams instead of UML Class Diagrams for data modeling, given the fact that class diagrams subsume ER diagrams? Or is it just for historical reasons because database people are used to ER modeling and are not familiar with UML? So, is ERD the COBOL of data modeling?

UML and ERD are two languages that can do the same thing: model entity (or object) types and their relationship types (or associatons).

答:
None of the answers so far seems to have picked up on the difference between conceptual and physical data modelling.

A UML conceptual model will show inheritance relationships, cardinallity and all that good stuff, with the minimum of implementation detail.

The physical model (ER diagram) will differ:

Inheritance is no longer obvious. There are three classical ways of mapping inheritance to a relational database - table per concrete class, table per class hierarchy and table per base class plus table per concrete class (holding extra fields only). Many databases have a mix of the three methods, so the ER diagram clearly shows the physical mappings.

Many-to-many mappings in the conceptual model translate to a join table in the ER diagram. In the conceptual model this is just a pair of crows feet symbols at the end of the relationship link. In the database it is a real table.

Naming conventions are often different. For instance, my organisation would map the Java Date creationDateTime field to an Oracle column  CREATION_TS TIMESTAMP.

But given the choice, I always go for the ER diagram. You can't easily write SQL given just the conceptual model. Given an unfamiliar and undocumented database, I usually use a reverse-engineering tool to create an ER diagram. With a good tool and a database that has referential integrity constraints defined, you get great results.

The target audience for conceptual models is likely to be enterprise architects and the more technical business analysts.

So in my view, UML and ER diagrams serve similar but quite distinct purposes.


问:
Why does C provide language 'bindings' where C++ falls short?
I recently was wondering when to use C over C++, and vice versa? Fortunately someone already beat me to it and although it took a while, I was able to digest all the answers and comments to that question.

However one item in that post keeps being addressed again and again, without any kind of example, verification or explanation:

"C code is good for when you want to have multiple language bindings for your library"

That's a paraphrase. I should note that several people point out that multiple language bindings are possible in C++ (via some extern functioning), but nevertheless, if you read that post in its entirety, it's pretty obvious that C is ideal for portability/language binding. My question is: why?

Can someone please provide concrete reasons why writing libraries in C allows for easier bindings and/or portability in other languages?

答:
Fundamentally it comes down to the ABI standardisation. While neither C nor C++ has a standardised ABI that other languages can use to interface between binaries written, C has become a de-facto standard, everyone knows it and everyone else can use the same, simple, rules that the language has with respect to types and function calls.

C++ could have a standard ABI, but Stroustrup has said that he doesn't see the need for one. He also says it would be difficult to get consensus from compiler writers (though I doubt that - the C++ standard committee would issue a ABI similar to existing ones and compiler writers would simply alter the next version of their compilers, which are occasionally incompatible with binaries built with old versions of their compilers anyway - I recall recompiling a couple of libraries with a new Sun compiler and finding they failed to work with the old ones)

You'll note that that some companies have moved to using a standard ABI, Microsoft started this process with COM way back in the 90s, and today they've refined this into the WinRT ABI (not to be confused with the other WinRT that refers to a type of table OS) that allows programs written in C# to communicate with libraries written in C or C++ (ie Microsoft's own OS layer is written in C++, exposed using WinRT and consumed by C# applications when they call any OS runtime routine)

There's not a lot anyone can do unless a standards body steps up and fixes this situation. Microsoft obviously sees the value in it and has taken steps to resolve it for their platform.

So the answer is really C doesn't provide language bindings. It happens that nobody has listened and consumes them regardless.


问:
How do you scale your integration testing?
I am investigating techniques and strategies for scaling our growing number of integration tests on our current product, so that they can (humanly) remain part of our development, and CI process.

At about 200+ integration tests we are already hitting the 1hr mark to complete a full test run (on aa desktop dev machine), and this is negatively affecting a developer's ability to tolerate running the whole suite as part of the routine push processes. Which is affecting motivation to be disciplined about creating them well. We integration test only key scenrios front to back, and we use an environment that mirrors production, that is built from scratch each test run.

Because of the time it takes to run, it is making for a terrible feedback loop and many wasted cycles waiting on machines to finish test runs, no matter how focused the test runs are. Nevermind the more expensive negative impact on flow and progress, sanity and sustainability.

We expect to have 10x fold more integration tests before this product begins to slow down (no idea really, but it does not feel like we are even getting started in terms of features yet). We have to resaonably expect to be in the few hundreds or or couple thousands of integration tests, I reckon at some point.

To be clear, to try to prevent this becoming a discussion on unit testing versus integration testing, (which should never be traded). We are doing both unit testing with TDD AND integration testing in this product. In fact, we do integration testing at the various layers in the services architecture that we have, where it makes sense to us, as we need to to verify where we introduce breaking changes when changing the patterns in our architecture to the other areas of the system.

A little about our tech stack. We are currently testing on a (CPU and memory intensive) emulation environment to run our tests from end to end. Which is composed of Azure REST web services fronting a noSql backend (ATS). We are simulating our production environment by running in the Azure desktop Emulator + IISExpress. We are limited to one emulator and one local backend repository per dev machine.

We also have a cloud-based CI as well, which runs the same test in the same emulated environment, and the test runs are taking twice as long (2hrs+) in the cloud with our current CI provider. We have reached the limits of the cloud CI providers SLA in terms of hardware performance, and exceeded their allowance on test run time. To be fair to them, their specs are not bad, but half as good as an inhouse grunty desktop machine clearly.

We are using a testing strategy of rebuilding our data store for each logical group of tests, and preloading with test data. While comprehensively insuring data integrity, this adds 5-15% impact on each test. So we think there is little to be gained optimizing that testing strategy at this point in the product development.

The long and the short of it is that: whilst we could optimize the throughput of each test (even if by as much as 30%-50% each), we still wont scale effectively in the near future with several hundred tests. 1hr now is even still far in excess of humanly tolerable, we need an order of magnitude-ish improvement in the overall process to make it sustainable.

So, I am investigating what techniques and strategies we can employ to drastically reduce testing time.

Writing less tests is not an option. Lets please not debate that one in this thread.

Using faster hardware is definately an option, although very expensive.

Running groups of tests/scenarios on separate hardware in parrallel is also definately a preferred option.

Creating grouping of tests around features and scenarios under development is plausible, but ultimately not reliable in proving full coverage or confidence that the system is not affected by a change.

Running in a cloud-scaled staging environment instead of running in the desktop emulator is technically possible, although we start adding deployment times to test runs (~20mins each at the start of the test run to deploy the stuff).

Dividing the components of the system into independent logial pieces is plausible to a degree but we expect limited mileage on that, since the interractions between components is expected to increase with time. (i.e. a change is ine is likely to affect others iin unexpected ways - as often happens when a system is developed incrementally)

I wanted to see what strategies (and tools) others are using in this space.

(I have to believe others may be seeing this kind of difficulty using certain technology sets.))

[Update: 12/16/2016: We ended up investing more in CI parallel testing, for a discussion of the outcome: https://web.archive.org/web/20200114101702/http://www.mindkin.co.nz/blog/2015/12/16/16-jobs ]

答:
It sounds like your code base is growing large, and some code management will help. We use Java, so apologies in advance if I assume this.

A large project needs to be broken down into smaller individual projects that compile to libraries. Java tools like nexus make this easy.

Every library should implement an interface. This aids stubbing out the library in higher-level tests. This is particularly useful if the library accesses a database or an external datastore (e.g. a mainframe). In such cases, getting the mainframe or database data into a repeatable state will likely be slow, and may be impossible.

Integration tests for each library can be comprehensive, but only need run when new library source is committed.

Higher-level integration tests should just call the libraries and assume they are perfect.

The Java shop that I work in uses this approach, and we are seldom held up waiting for integration tests to run.

ContentLicense: CC BY-SA 4.0


问:
A CLR SQL Server Stored Procedure calling an ASP.NET Web API
We are developing a big system with SQL Server database, ASP.NET Web API 2.2 services and another external services.

We need to load more data on a table while we process the current data on it. To allow load data in background we call our ASP.NET Web API from a CLR SQL Server Stored Procedure.

Then, our ASP.NET Web API retrieve more data and itself insert that data on SQL Server.

Better explained the process is the following:

SQL Server Stored procedure detects that we need more data, then it calls CLR SQL Server Stored Procedure.

CLR SQL Server SP calls ASP.NET Web API.

ASP.NET Web API retrieves more data and insert then into SQL Server.

What do you think about this 'architecture'? Do you know a better approach?

My doubt here is second step: a SQL Server database calling an ASP.NET Web API. But we need to do that work in background.

And also, the new data that we need to insert into SQL Server could be in a WCF SOAP Service.

答:
I've worked in places where CLR assemblies are used in this fashion. In my opinion it is a bad idea.

Here's my reasoning.

1: Embedding logic in the database is always bad. This is a 'programming philosophy' position, but I feel that it is justified as a general rule

2: The CLR will be limited to .net 2 on mssql server

3: The CLR may timeout or error due to its dependency on the external resource. This will produce different result sets from the sproc

4: the DB selects? then calling the API which then inserts is going to give you locking and transaction problems with no easy solution

5: You already have a .Net layer in your solution (the webapi) so you have the infrastructure to support a windows service or similar application which can fulfill the business role.

I guess the thing missing from your question which would enable me to suggets a better pattern is what is calling the sproc in the first place?

Just a quick expansion on point 1 as I know it can be contentious. I've worked in a lot of companies and I tend to see two types of system.

Systems initially created by DBAs. these tend to have lots of SQL Agent Jobs, big sprocs with case statements, loops and business logic, SSIS packages etc

Systems initially created by programmers. These tend to have no indexes or keys, xml columns etc. DB just used for persistence of objects

The DBA created systems fall over because they don't scale

The programmer systems get corrupt data but struggle on. Because you can always add another web box


问:
Should we define types for everything?
Recently I got into a problem with the readability of my code.

I had a function that did an operation and returned a string representing the ID of this operation for future reference (a bit like OpenFile in Windows returning a handle). The user would use this ID later to start the operation and to monitor its finish.

The ID had to be a random string because of interoperability concerns. This created a method that had a very unclear signature like so:

public string CreateNewThing()
```

<p>This makes the intent of the return type unclear. I thought to wrap this string in another type that makes its meaning clearer like thus:</p>

<pre class="lang-cs prettyprint-override"><code>public OperationIdentifier CreateNewThing()
</code>```

The type will contain only the string and be used whenever this string is used.

It's obvious that the advantage of this way of operation is more type safety and clearer intent, but it also creates a lot more code and code that isn't very idiomatic. On the one hand I like the added safety, but it also creates a lot of clutter.

Do you think it is a good practice to wrap simple types in a class for safety reasons?

答:
Unpopular opinion:

You should usually not define a new type!

Defining a new type to wrap a primitive or a basic class is sometimes called defining a pseudo-type. IBM describes this as a bad practice here (they focus specifically on misuse with generics in this case).

Pseudo types make common library functionality useless.

Java's Math functions can work with all number primitives. But if you define a new class Percentage (wrapping a double that can be in the range 0~1) all these functions are useless and need to be wrapped by classes that (even worse) need to know about the internal representation of the Percentage class.

Pseudo types go viral

When making multiple libraries you will often find that these pseudotypes go viral. If you use the, above mentioned, Percentage class in one library you will either need to convert it at the library boundary (losing all safety/meaning/logic/other reason you had for creating that type) or you will have to make these classes accessible to the other library as well. Infecting the new library with your types where a simple double might have sufficed.

Take away message

As long as the type you wrap does not need a lot of business logic I would advice against wrapping it in a pseudo class. You should only wrap a class if there are serious business constraints. In other cases naming your variables correctly should go a long way in conveying meaning.

An example:

A uint can perfectly represent a UserId, we can keep using Java's built in operators for uints (such as ==) and we do not need business logic to protect the 'internal state' of the user id.

Title: Should we define types for everything?


答:
Integration tests will always be long running as they should mimic a real user. For this very reason you shouldn't run them all synchronously!

Given that you are already running stuff in the cloud it seems to me like you are in a prime position to scale your tests over multiple machines.

In the extreme case, spin up one new environment per test and run them all at the same time. Your integration tests will then only take as long as the longest running test.

Title: How do you scale your integration testing?

Body:
I am investigating techniques and strategies for scaling our growing number of integration tests on our current product, so that they can (humanly) remain part of our development, and CI process.

At about 200+ integration tests we are already hitting the 1hr mark to complete a full test run (on aa desktop dev machine), and this is negatively affecting a developer's ability to tolerate running the whole suite as part of the routine push processes. Which is affecting motivation to be disciplined about creating them well. We integration test only key scenrios front to back, and we use an environment that mirrors production, that is built from scratch each test run.

Because of the time it takes to run, it is making for a terrible feedback loop and many wasted cycles waiting on machines to finish test runs, no matter how focused the test runs are. Nevermind the more expensive negative impact on flow and progress, sanity and sustainability.

We expect to have 10x fold more integration tests before this product begins to slow down (no idea really, but it does not feel like we are even getting started in terms of features yet). We have to resaonably expect to be in the few hundreds or or couple thousands of integration tests, I reckon at some point.

To be clear, to try to prevent this becoming a discussion on unit testing versus integration testing, (which should never be traded). We are doing both unit testing with TDD AND integration testing in this product. In fact, we do integration testing at the various layers in the services architecture that we have, where it makes sense to us, as we need to to verify where we introduce breaking changes when changing the patterns in our architecture to the other areas of the system.

A little about our tech stack. We are currently testing on a (CPU and memory intensive) emulation environment to run our tests from end to end. Which is composed of Azure REST web services fronting a noSql backend (ATS). We are simulating our production environment by running in the Azure desktop Emulator + IISExpress. We are limited to one emulator and one local backend repository per dev machine.

We also have a cloud-based CI as well, which runs the same test in the same emulated environment, and the test runs are taking twice as long (2hrs+) in the cloud with our current CI provider. We have reached the limits of the cloud CI providers SLA in terms of hardware performance, and exceeded their allowance on test run time. To be fair to them, their specs are not bad, but half as good as an inhouse grunty desktop machine clearly.

We are using a testing strategy of rebuilding our data store for each logical group of tests, and preloading with test data. While comprehensively insuring data integrity, this adds 5-15% impact on each test. So we think there is little to be gained optimizing that testing strategy at this point in the product development.

The long and the short of it is that: whilst we could optimize the throughput of each test (even if by as much as 30%-50% each), we still wont scale effectively in the near future with several hundred tests. 1hr now is even still far in excess of humanly tolerable, we need an order of magnitude-ish improvement in the overall process to make it sustainable.

So, I am investigating what techniques and strategies we can employ to drastically reduce testing time.

Writing less tests is not an option. Lets please not debate that one in this thread.

Using faster hardware is definately an option, although very expensive.

Running groups of tests/scenarios on separate hardware in parrallel is also definately a preferred option.

Creating grouping of tests around features and scenarios under development is plausible, but ultimately not reliable in proving full coverage or confidence that the system is not affected by a change.

Running in a cloud-scaled staging environment instead of running in the desktop emulator is technically possible, although we start adding deployment times to test runs (~20mins each at the start of the test run to deploy the stuff).

Dividing the components of the system into independent logial pieces is plausible to a degree but we expect limited mileage on that, since the interractions between components is expected to increase with time. (i.e. a change is ine is likely to affect others iin unexpected ways - as often happens when a system is developed incrementally)

I wanted to see what strategies (and tools) others are using in this space.

(I have to believe others may be seeing this kind of difficulty using certain technology sets.))

[Update: 12/16/2016: We ended up investing more in CI parallel testing, for a discussion of the outcome: https://web.archive.org/web/20200114101702/http://www.mindkin.co.nz/blog/2015/12/16/16-jobs ]


答:
Sounds like you have way too many integration tests. Recall Test pyramid. Integration tests belong in the middle.

As an example take a repository with method set(key,object), get(key). This repository is used extensively throughout your code base. All the methods that depend on this repository will be tested with a fake repository. Now you only need two integration tests, one for set and one for get.

Some of those integration tests could probably be converted to unit tests. For example, end to end tests in my view should only test that the site is configured correctly with the correct connection string and correct domains.

Integration tests should test that the ORM, repositories, and queue abstractions are correct. As a rule of thumb, no domain code is needed for integration testing - only abstractions.

Almost everything else can be unit tested with stubbed/mocked/faked/in-mem-implementations for dependencies.


问:
Does Silverlight have a future?
Recently I have read some articles/blogs/comments about the development and history of WPF and Silverlight. In some forums many developers and users criticize the performance of WPF applications (for example Visual Studio 2010). Actually the market share of Silverlight in comparison to Flash is not very high. At PDC 2010 Bob Muglia said something like "our Silverlight strategy and focus going forward has shifted...." and Microsoft wants to push HTML5 in the future.

Additionally, Microsoft has announced HTML5 being a core part of the Windows 8 and Windows Phone 8 ("Mango") platforms.

Recently I have started learning Silverlight and now I must ask myself, if I should continue investing time in learning these (in my opinions) very nice and powerful technologies!? Does they have a future? Does (Windows) desktop (client) applications have a future? Does so called "Rich Internet Applications" have a future? Or will HTML5 become the "absolute truth" in software development?

What is your opinion and what do you think?

答:
Silverlight is probably best described as Microsoft's answer to Flash.  It's the same problem domain, so what makes a good Flash game will also make a good Silverlight game.

No one really knows the future.  All I know at this moment is that not everything makes a good web-application, and not everything makes a good desktop application.  This much I do know:

WPF will probably stick around for a while.

Silverlight is in its infancy, so Microsoft is going to pimp it for a while.  I've heard rumors that it's nicer to work with than Flash, but never having messed with either, I can't say.

HTML 5/CSS 3/JavaScript is supposed to be the bees knees, but won't be ready in a truly meaningful way any time this decade.  (Assuming the comittees approve it before 2020, it still needs full browser support and that takes time).

To choose the platform you are going to pursue you need to get some fundamental answers:

Who are your customers?  (i.e. what's your target market?)

Are you planning on making money?  How?

What's the time-frame you expect this app to be live before you upgrade it and/or replace it?

If you are looking longer than two years to get your first two versions out the door, chances are you are looking too far down the road.  Knowing your target market will help you understand if a platform is even viable.  For example, many mobile devices do not support any kind of plugin in their tiny browsers--that means not only no Silverlight, but no Flash either.  But if you are not targeting mobile devices, it doesn't matter to you.

Title: Does Silverlight have a future?


问:
Is my usage of explicit casting operator reasonable or a bad hack?
I have a big object:

```<code>class BigObject{
    public int Id {get;set;}
    public string FieldA {get;set;}
    // ...
    public string FieldZ {get;set;}
}
</code>```

and a specialized, DTO-like object:

```<code>class SmallObject{
    public int Id {get;set;}
    public EnumType Type {get;set;}
    public string FieldC {get;set;}
    public string FieldN {get;set;}
}
</code>```

I personally find a concept of explicitly casting BigObject into SmallObject - knowing that it is a one-way, data-losing operation - very intuitive and readable:

```<code>var small = (SmallObject) bigOne;
passSmallObjectToSomeone(small);
</code>```

It is implemented using explicit operator:

```<code>public static explicit operator SmallObject(BigObject big){
    return new SmallObject{
        Id = big.Id,
        FieldC = big.FieldC,
        FieldN = big.FieldN,
        EnumType = MyEnum.BigObjectSpecific
    };
}
</code>```

Now, I could create a SmallObjectFactory class with FromBigObject(BigObject big) method, that would do the same thing, add it to dependency injection and call it when needed... but to me it seems even more overcomplicated and unnecessary.

PS I'm not sure if this is relevant, but there will be OtherBigObject that will also be able to be converted into SmallObject, setting different EnumType.

答: None of the other answers have it right in my humble opinion. In this stackoverflow question the highest-voted answer argues that mapping code should be kept out of the domain. To answer your question, no - your usage of the cast operator is not great. I would advise to make a mapping service which sits between your DTO and you domain object, or you could use automapper for that.</p>


问:
Read complex data from a relational database through a join or through concurrent requests?
Consider a simple relational database with two tables:

```<code>item_index: item_id|item_name
item_property: item_id|property_name
</code>```

Each item has several properties, and I want to iterate over the collection of items in my database. For this I need to write a function with the following signature, where database denotes the type of database handles:

```<code>contents : database -> (item_name * (property_name list)) stream
</code>```

This signature means that the function contents returns a stream of pairs whose first member is the item name and the second member its list of properties.

There is two simple options to implement contents:

Concurrently require the stream of items and the stream of properties from the database, sorted appropriately, and aggregate the data by examining the two streams.

Require the stream of rows of an inner join, so that each item with its properties is represented by several rows, like item_id|item_name|property_name and aggregate the items from this data.

The second seems to put more overhead on the database, because of the join – probably packed as a view – while the first is significantly harder to program because of the concurrent access to the database.

Am I right thinking that implementing the contents functions using concurrently requests amounts to poorly implement a join operation in the application?  This would imply that the second design is superior to the first as it leads to comparable time complexity and simpler code.

答:
In the general case, you're better off letting the database do the work.

Time complexity is actually a good reason to follow this advice. Unless you're lucky with your data, you'll end up needing to index one or both tables to ensure you have efficient lookup.

Your database will already have various strategies in place for this and the heuristics to do a decent job of finding the best one. one can, sometimes, do better by hand (as you may well have more information) but unless you know for certain that is the case (and always will be), it's best to leave it to the DB.

A similar argument can probably be made for the concurrency and sorting aspects. By letting the DB do all the work, you're also giving it more info to help optimise the retrieval. Again, it is conceivable that you doing part of it and the DB doing part of it is better but this would need to be carefully tested for and I would definitely err on the side of simplicity.


答:
All answers fall short of the real problem: C++ compiling introduces "name mangling", so binaries are incompatible with "simple" function calls.

All ABI stuff is little more than an attempt to standardize it.

In general it's not guaranteed you can cross-link functions compiled with different compilers, even if you stick to plain C++. Formerly it was sure they were incompatible, but nowadays standardization is creeping in ;)

OTOH C was designed precisely to be a "high level Assembly" and allow all sort of easy interfacing.
It should not surprise it's better suited to cross-language liking.

Side note: original C++ compiler (cfront) actually produced C source that had to be compiled, exactly like gcc that produces Assembly "under the hood".

Title: Why does C provide language 'bindings' where C++ falls short?

Body:
I recently was wondering when to use C over C++, and vice versa? Fortunately someone already beat me to it and although it took a while, I was able to digest all the answers and comments to that question.

However one item in that post keeps being addressed again and again, without any kind of example, verification or explanation:

"C code is good for when you want to have multiple language bindings for your library"

That's a paraphrase. I should note that several people point out that multiple language bindings are possible in C++ (via some extern functioning), but nevertheless, if you read that post in its entirety, it's pretty obvious that C is ideal for portability/language binding. My question is: why?

Can someone please provide concrete reasons why writing libraries in C allows for easier bindings and/or portability in other languages?


答:
I think that its important to differenciate a solution obtain by applying an Object Oriented Approach and a solution implemented USING the Object Oriented Paradigm.
My opinion about a good object oriente piece of software is to combine both solutions. If you think in objects and you respect the object definitions and interactions, and you problem could be adapted to use this structure, then you'll have a code that is flexible and robust.
 But if you use objects to solve a code using a procedural paradigm, you'll end up with some nasty mix that wont take advantage from the Objects pros.

I really prefer my code to be Object Oriented, and i've come to realize that at first it could be a bit more annoyng to create a good structure, but when dealing with flexibility and client flash requirements of today, i think it's worth the effort.

Title: is OOP the dominant programming model in real world?

Body:
Objects Never? Well, Hardly Ever

In the VIEWPOINT section of Communications of The ACM, I found an
interesting article entitled "Objects Never? Well, Hardly Ever".
It’s a radically different perspective than objects-first or objects-late. He suggests "objects-never" or maybe "objects-graduate school".

The author talked about OOP and made a question about how OOP is used
in real world programming environments. He thinks that OOP is not the
dominant programming model. For example, he claims, 70% of
programmings are done for Embedded Systems where OOP is not really
suited.

When some professors in universities wants to talk about the benefits
of OOP, they talk about code-reuse. As another example, again, he
claims, this is not the real case in real world. code-reuse is harder
than what's claimed in universities:

I claim that the use of OOP is not as prevalent as most people believe, that it is not as successful as its proponents claim, and, therefore, that its central place in the CS curriculum is not justified.

It's interesting for me to know how people in stack-overflow think
about this? Is OOP the dominant programming model from programmers'
point of view?

If I should choose/learn/use just one approach, is it OOP or not? why?


问:
Best workflow for a web development team to work on a large amount of projects simultaneously?
We're a team of web developers, and as the number of projects we're working on has grown and continues to, things are starting to get messy.

What we currently do is work on a locally shared folder and sync files to production FTP hosts on save.

It's far from being perfect, but we have yet to find a better solution.

These are the main things we want to achieve when changing our workflow:

Fast reading and writing to files

Fast testing on the browser after saving

GIT

Frankly, we're not very experienced with more advanced workflow

Most of the team doesn't know how to work with Git at all and would rather stay with their current workflow, therefore we're looking for a way to achieve the points above with as few changes as possible

答:
You need to have some kind of version control system. You MUST have it. If git looks too complex try mercurial, even thought they are very similar. Set up a git repository server. My team uses gitlab and it works fine.

You need to put some rules for the control versioning. Meaning, ideally not all cannot commit to the main branch for example.

You should start to do some testing. Maybe unit testing is too difficult to implement right away, but you should do some testing before making a commit for a branch. I mean, it should at least compile and run right? Well, sometimes people make commits that doesn't even compile. You HAVE to do some testing if your team is growing. You don't say what are you guys doing or what language(s) you are using so I cannot give you any specific help, but maybe you should take a look at Jenkins.

You should use some kind of bug reporting tool. Take a look at these: http://mashable.com/2014/02/16/bug-tracking-apps I've used FogBugz and I like it. I heard you can now use it with trello.

You should use some kind of tool to communicate with your team and share ideas, like trello or something like that.

Try to have an homogeneous environment. Meaning, if different persons use different OS and compilers, things can get messy.


答:
The hardest part about having a lot of projects and a lot of people often isn't about how to maintain the code, it's how to communicate, implement the process, and work together with good tools.

To achieve that goal I'd recommend you

use git for source control

use jira, trello or privotal tracker for issue tracking

use agile processes and look into using kanban to focus on the work.

use slack for communication (it has recently swept thru the industry).

use remote repositories such as github or stash to store code.

use a full-time scrummaster for process

arrange team(s) that have developers, a scrum master, a Product owner and QA for process

Title: Best workflow for a web development team to work on a large amount of projects simultaneously?

Body:
We're a team of web developers, and as the number of projects we're working on has grown and continues to, things are starting to get messy.

What we currently do is work on a locally shared folder and sync files to production FTP hosts on save.

It's far from being perfect, but we have yet to find a better solution.

These are the main things we want to achieve when changing our workflow:

Fast reading and writing to files

Fast testing on the browser after saving

GIT

Frankly, we're not very experienced with more advanced workflow

Most of the team doesn't know how to work with Git at all and would rather stay with their current workflow, therefore we're looking for a way to achieve the points above with as few changes as possible


问:
Is browser fingerprinting a viable technique for identifying anonymous users?
Is browser fingerprinting a sufficient method for uniquely identifying anonymous users? What if you incorporate biometric data like mouse gestures or typing patterns?

The other day I ran into the Panopticlick experiment EFF is running on browser fingerprints.

Of course I immediately thought of the privacy repercussions and how it could be used for evil. But on the other hand, this could be used for great good and, at the very least, it's a tempting problem to work on.

While researching the topic I found a few companies using browser fingerprinting to attack fraud. And after sending out a few emails I can confirm at least one major dating site is using browser fingerprinting as but one mechanism to detect fake accounts. (Note: They have found it's not unique enough to act as an identity when scaling up to millions of users. But, my programmer brain doesn't want to believe them).

Here is one company using browser fingerprints for fraud detection and prevention:

http://www.bluecava.com/

Here is a pretty comprehensive list of stuff you can use as unique identifiers in a browser:

http://browserspy.dk/

答:
Some browsers can also be identified via HSTS Supercookies.

This is where you can embed a page with requests to random sets of secure and non secure resources for each visitor, then monitor the pattern of their requests on a returning visit. If each resource is requested in the same pattern, then you can use that information to identify the user.

These are particularly useful for identifying iPhone / iPads which would otherwise have more of a generic browser fingerprint. This approach is not so useful for Internet Explorer where HSTS is not supported.

This article explains the approach;
http://www.radicalresearch.co.uk/lab/hstssupercookies/

This article provides a good example of how to leverage HSTS Supercookies to identify users;
https://nakedsecurity.sophos.com/2015/02/02/anatomy-of-a-browser-dilemma-how-hsts-supercookies-make-you-choose-between-privacy-or-security/


问:
How to unit test static void methods?
How does one go about unit testing static void methods? I have a few more questions:

Is it necessary to unit test database queries like insert, select and update queries ? If so, how does one test them ?

Is unit testing of every method required ? If not, are there any rules I should keep in mind when deciding what methods should be tested?

How would I unit test a method that sends files from one system to another? The input to this method is just the IP address of the target system.

What is the best way of testing private methods that I have written? I have changed the scope to public and tested them. Is this a bad practice?

Must every unit test method have an assert statement? Is it possible to have a unit test without an assert statement? If so, how do I test it?

I am doing the unit testing in C# and I am using MSTest for testing.

答:
1) It is very hard to test static void methods but they must do something so what is it they do? If they modify global state you could read that global state, but the best thing is to refactor them into a better structure.

2) Unit testing is only for public methods. Even if you test all methods you can probably not input all parameter combinations so even if there are tests there can still be bugs. If you only write production code provoked by a failing test(TDD) it will be much clearer which tests are needed.

3) This is not a unit test but an integration test. Is it possible to read the file back somehow? What is how I would write that integration test.

4) Don't test private methods. They are not part of the contract and you are free to change them as long as it doesn't change the behaviour of public methods. If you feel there is too much going on in the private methods, feel free to move some of the logic into a service and inject that instead.

5) In some cases it makes sense to have a unit test that checkes that some code runs without throwing an exception and in that case assert is not needed.

Title: How to unit test static void methods?


问:
PHP and Subversion workflow
I'm working on a project in a small team at the moment working on a webapp. We originally had 3 on the team with a lead dev and now we've grown to 7 and a lead dev.

At the moment our workflow is this: we all work off of one central repository and use SVN. Once we get our dev environment to a somewhat stable stage we copy it over to our testing site, then we push it live. At the moment I'm trying to push a single feature live, so I'm copying bits a pieces from our dev environment over to our test environment and it's a bit of a pain which has prompted this post.

(Disclaimer, my knowledge of git is mainly push, pull and commit) In my mind we should be doing the following: maintain one branch of code. Each dev would then create branch when working on a feature then when complete merge it back to the main branch.

My boss, the lead dev, reckons that merging in PHP is a pain in the ass. I can't think of why it would be different to any other language but I don't have the experience to know any better. Is this a workflow that we should be looking into or is there a better way? What way does your workflow go?

Thanks

答:
Merging in SVN is no different to merging in git - if the computer can figure it out, it does it and all's good, if it needs manual attention it prompts you. (exception: SVN's handling of new/deleted/renamed files is poor, but git can have issues in this area too).

So, that out of the way you can really think of SVN as a clone of a repo that you push to. Once you have a working copy, you modify it and commit the changes - they are effectively committed and pushed in a single stage and the origin repo automatically pulls your changes to it. All very simple.

Branching: not much different here, create a branch off the trunk per dev, do work, then merge it back onto trunk. Very simple, really easy. Works.

Once you have a stable trunk with all the features you want, you should create or update a tag - this is just a branch by a different name. I'd maintain a tag for your test and live environments, just merge the trunk to the test tag when you're ready to deploy and your test environment can then simply update its working copy from that tag. When its passed test, either merge the test tag to the live one, or (better) create a new live tag from the test branch.

I've never found git v svn particularly different, obviously the tooling is but the concepts of branching, merging and updating is roughly the same. What you would do with git is just the same with svn - only with a central repo that you transfer the files to or from instead of pushing and pulling to different repos, the SVN 'working copy' being the equivalent of your local git repo.

So that's a very rough description - basically, your old workflow should still be the one to use with SVN.

Title: PHP and Subversion workflow


答:
Without gettting into an argument over what a 'unit' test is:

Yes you should test your sql/sprocs. especially if you (foolishly) put business logic in them. you can use database snapshots to set up dbs

https://msdn.microsoft.com/en-us/library/jj851212%28v=vs.103%29.aspx

'Test all your methods' is a good rule because it allows no room for interpretation. When you are a rock star programmer (like me) you can test a subset of your methods (YOLO!)

Abstract the underling stream writing so that you are able to inject a mock stream and test the logic without actually sending data between systems. ie ip address not found, connection lost etc

Reflection, internalsVisibleTo or (my fave) Make it protected, inherit the class and add a public accessor

https://msdn.microsoft.com/en-US/library/ms184807%28v=vs.80%29.aspx

Yes, you can even assert that an exception is thrown

http://www.nunit.org/index.php?p=exceptionAsserts&r=2.5.3

Title: How to unit test static void methods?

Body:
How does one go about unit testing static void methods? I have a few more questions:

Is it necessary to unit test database queries like insert, select and update queries ? If so, how does one test them ?

Is unit testing of every method required ? If not, are there any rules I should keep in mind when deciding what methods should be tested?

How would I unit test a method that sends files from one system to another? The input to this method is just the IP address of the target system.

What is the best way of testing private methods that I have written? I have changed the scope to public and tested them. Is this a bad practice?

Must every unit test method have an assert statement? Is it possible to have a unit test without an assert statement? If so, how do I test it?

I am doing the unit testing in C# and I am using MSTest for testing.


问:
Can I test effectively javascript functions with a PHP unit-testing framework?
If I want to unit-test some of my javascript functions, would it be more efficient (and doable) to use the already installed PHP unit-testing framework, or should I use a javascript unit-testing framework?

EDIT: It seems I have to clarify things a bit. I'm using javascript for form validation. It seems that some logic doesn't work as I want it to be, and I thought to myself that would be a good point to begin to use unit-testing (something that came to my scope only recently). I already began to use SimpleTest on a little project of mine, but never to test logic that is generated client-side.

Now I know that SimpleTest have the possibility to emulate a browser for example. But I was wondering what other method would they be to unit-test my form validation. While I was searching for idea, I realized that there is also unit-testing framework for javascript, but after a bit of searching on some of the SE sites, I didn't find anything about use of PHP and Javascript Framework together, so I wondered how common such a situation it was, and how do other people manage in such an environment.

答:
The short answer is no.

You cannot effectively test JavaScript with PHP.  To do it effectively, you need to use JavaScript.

More than likely you will have to use a JavaScript unit testing library such as the one used for Prototype.js.  Essentially, you need to be able to execute the JavaScript in browser, and get the results of the JavaScript run.  You won't be able to do that from the server side (PHP).

Unit testing frameworks are most efficient and useful when you are using the same language to test as you are to write the code in.  For that reason we have PHP unit testing frameworks, Java unit testing frameworks, C#/.Net unit testing frameworks, and yes, JavaScript unit testing frameworks.  A big part of the reason for this is that your unit tests need to examine the results of what your code is doing in the environment where it runs.  SimpleTest runs in the PHP environment, and examines to assert that your PHP functions are doing what you expect.  It doesn't run directly in the client browser, but as all PHP code it runs on the server and generates HTML output.

In order to run and test JavaScript functionality--particularly when the problem might be how a one browser implements it--you need to execute and assert functionality in JavaScript.  Now, you can roll your own JavaScript unit testing framework for your environment, or you can use one that already exists.

The JavaScript lives 100% on the client side.  That's why you didn't see anything about running JavaScript and PHP together--just as you won't find information on Java and JavaScript together (in the same context we are talking here).


问:
In MVC, who is in charge of handling observers?
(I'm writing a large MATLAB GUI that makes significant use of MVC, so my example is written in MATLAB. However, I believe this question is language-agnostic. Please correct me if I'm wrong.)

I have a class Model which is obviously the model for my MVC application. Suppose I have the following:

```<code>classdef Model < handle
    properties
        objectA
        objectB
        objectC
    end
end
</code>```

objectA, objectB, and objectC are all objects that can be observed:

```<code>classdef objectA < handle
    events
        ObjectAEvent
    end
    methods
        function raise(this)
            this.notify('ObjectAEvent', someEventData);
        end
     end
end
</code>```

etc.

Now say I want my View to respond to changes to my Model. In particular I want the View to respond to the ObjectAEvent event. There are two ways to do this:

Let the View directly subscribe to the ObjectAEvent event. We've now coupled the View into the internals of the Model, which I believe violates the Law of Demeter. I'm pretty sure this also violates the concept of MVC by definition.

Let the Model "forward" the event to the View, as follows.

```<code>classdef Model < handle
    properties
        objectA
        objectB
        objectC

        listeners
    end
    events
        eventFromObjectA
        ...
    end
    methods
        function this = Model
            this.listeners(1) = addlistener(this.objectA, 'ObjectAEvent', @(src, eventdata) this.notify('eventFromObjectA', eventdata);
            ...
        end
    end
end
</code>```

Now the View directly observes the Model, but the Model has to pass the events and associated data to the View. I suppose this is kind of the point of MVC, but now there's a coupling between each object_ and the Model directly. I suppose the Model ought to know about his object_s, but this still feels... clunky.

Which approach is more correct? Are there other alternatives which are cleaner than either of these?

(Answers may have examples in any OOP language; I'm just most familiar with MATLAB.)

答:
Let the View directly subscribe to the ObjectAEvent event. We've now coupled the View into the internals of the Model, which I believe violates the Law of Demeter. I'm pretty sure this also violates the concept of MVC by definition.

MVC isn't about total decoupling. It's about avoiding coupling to elements that are unstable. As for Law of Demeter, you'd have to show why you think it violates it. It's not a hard and fast principle, either, despite its name having the word "Law" in it. It's nearly impossible not to violate it at some point.

View classes tend to be less stable than the model classes, because views are part of the user interface. Users tend to want new ways to view information (it's hard to get the views right the first time), etc. E.g. how many times has the GUI for Microsoft Word changed, yet the model of a document (think of paragraphs, words, characters, fonts, styles, etc.) has not changed much?

In MVC, views can be directly coupled to the model classes, because model classes tend to be more stable. MVC makes this assumption as a design choice. If model classes change (it can happen), then all bets are off for those changes being isolated to the model. You'll probably have to change the views, too.

Model classes have to communicate with the Views, but MVC wants to avoid direct coupling. We get around this problem by disguising Views as "Observers." The Observer API is very stable, even if the views that implement it are not. So as far as I understand MVC, it's OK to have coupling the way you have described it in point #1.

Let's use a real object rather than ObjectA, say engineTemperature. The view that displays the temperature would surely know what it's displaying. It might add the units "degrees C" since the view knows the value is a temperature. It might use the color red if the temperature exceeds some upper value. It's normal for views to be directly coupled to the model elements they display.

The other way around, however, is different. engineTemperature should not know how it's being displayed, what colors are being used, who's displaying it, etc., since that knowledge would make it tightly coupled to the views, and it would lose its stability. Any change in the view might "break" the temperature object. So, with MVC and Observer, engineTemperature (as a Subject in the Observer pattern) only knows it has Observers, which all support the Observer API.

Have a look at http://martinfowler.com/eaaDev/uiArchs.html#ModelViewController for more info on MVC and other UI designs.


问:
Application model management questions
Consider the following type of Java / Spring web application, with an SQL database:

there are multiple data entity types (about 100) with relations between them

the entities are viewed, edited or exposed to APIs, and frequently this happens with several entity types (joined)

The current approach uses three layers:

a data layer, that queries the tables, and uses entities that are 1:1 match to the database

a service layer to perform the business logic, and call the data layer as needed

a controller layer - exposing operations to the client side code and to the API

My questions related to handling the models are:

Should every layer have its own models / entity classes? If yes, how is it best to handle copying / merging the models across the layers?

Sometimes, at the service layer, an entity might require to have certain fields filled in one case, but not in other cases. Should there be two model classes for these two situations? (To make sure you can count on what fields are provided by the service)

Given the large number of entities, is it worth to be consistent in addressing the issues above in the same manner, regardless of any extra complexities involved?

答:
They probably 'Should' however I recommend not. Map your data layer directly to your model in a Repository, use ViewModels in the controller layer, but just wrap your Models and add extra data where required instead of duplicating them.

This Sounds fishy to me. Probably a sign that you need another Model

It shouldn't be complicated. I recommend NOT writing your own generic mapper/orm code

Title: Application model management questions


答:
It might be okay.

A problem with your example is that you use such example-ish names. Consider:

```<code>SomeMethod(long longNum)
{
  int num = (int)longNum;
  /* ... */
</code>```

Now, when you've a good idea what a long and int means, then both the implicit cast of int to long and the explicit cast from long to int are quite understandable. It's also understandable how 3 becomes 3 and is just another way to work with 3. It's understandable how this will fail with int.MaxValue + 1 in a checked context. Even how it will work with int.MaxValue + 1 in an unchecked context to result in int.MinValue isn't the hardest thing to grok.

Likewise, when you cast implicitly to a base type or explicitly to a derived type its understandable to anyone who knows how inheritance works what is happening, and what the result will be (or how it might fail).

Now, with BigObject and SmallObject I don't have a sense of how this relationship works. If your real types where such that the casting relationship where obvious, then casting might indeed be a good idea, though a lot of the time, perhaps the vast majority, if this is the case then it should be reflected in the class hierarchy and the normal inheritance-based casting will suffice.

Title: Is my usage of explicit casting operator reasonable or a bad hack?

Body:
I have a big object:

```<code>class BigObject{
    public int Id {get;set;}
    public string FieldA {get;set;}
    // ...
    public string FieldZ {get;set;}
}
</code>```

and a specialized, DTO-like object:

```<code>class SmallObject{
    public int Id {get;set;}
    public EnumType Type {get;set;}
    public string FieldC {get;set;}
    public string FieldN {get;set;}
}
</code>```

I personally find a concept of explicitly casting BigObject into SmallObject - knowing that it is a one-way, data-losing operation - very intuitive and readable:

```<code>var small = (SmallObject) bigOne;
passSmallObjectToSomeone(small);
</code>```

It is implemented using explicit operator:

```<code>public static explicit operator SmallObject(BigObject big){
    return new SmallObject{
        Id = big.Id,
        FieldC = big.FieldC,
        FieldN = big.FieldN,
        EnumType = MyEnum.BigObjectSpecific
    };
}
</code>```

Now, I could create a SmallObjectFactory class with FromBigObject(BigObject big) method, that would do the same thing, add it to dependency injection and call it when needed... but to me it seems even more overcomplicated and unnecessary.

PS I'm not sure if this is relevant, but there will be OtherBigObject that will also be able to be converted into SmallObject, setting different EnumType.

Body:
It might be okay.

A problem with your example is that you use such example-ish names. Consider:

SomeMethod(long longNum)
{
  int num = (int)longNum;
  /* ... */

Now, when you've a good idea what a long and int means, then both the implicit cast of int to long and the explicit cast from long to int are quite understandable. It's also understandable how 3 becomes 3 and is just another way to work with 3. It's understandable how this will fail with int.MaxValue + 1 in a checked context. Even how it will work with int.MaxValue + 1 in an unchecked context to result in int.MinValue isn't the hardest thing to grok.

Likewise, when you cast implicitly to a base type or explicitly to a derived type its understandable to anyone who knows how inheritance works what is happening, and what the result will be (or how it might fail).

Now, with BigObject and SmallObject I don't have a sense of how this relationship works. If your real types where such that the casting relationship where obvious, then casting might indeed be a good idea, though a lot of the time, perhaps the vast majority, if this is the case then it should be reflected in the class hierarchy and the normal inheritance-based casting will suffice.


问:
What licence should I choose for my project?
I originally thought of creative commons when while reading a book about wordpress (professional wordpress), I learned that I should also specify that the product is provided

... WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE

and they recommend GNU GPL.  How do I write a license or select 1?

btw, what does MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE mean actually? Isn't without warranty enough?

答:
For small bits of code, I generally release them under the X11 licence. The problem with the GPL is that it's far too complicated for code that you don't really care enough about to protect. If you really don't want people using your code in commercial products, you would need to monitor for infringement and fight it out in court, which isn't really worth the time or the effort for small, free, open-source projects.

Copyright (c)

Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.

EDIT: If the body of code is more substantial, and you feel that you've invested enough time in it that you would be willing to protect it, by all means use the GPL to protect it.


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答: Implement strcpy, strcmp and friends.

Body: Implement strcpy, strcmp and friends.


问:
How bad is it that my index.php in a Zend Framework MVC application mixes definitions and side effects?
I'm introducing some more coding quality standards and checks via a new project - in particular, the PHP-FIG recommendations.

This project using Zend Framework 2, and I have a fairly simple entry script which passes on to the MVC application:

```<code>define("BASE_PATH", (dirname(__DIR__)));

// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) {
    return false;
}

// Setup autoloading

// Get the autoloader from composer
$loader = include BASE_PATH . '/vendor/autoload.php';

$zf2Path = BASE_PATH . '/vendor/ZF2/library';

// Add the Zend namespaces/paths to the autoloader
$loader->add('Zend', $zf2Path);
$loader->add('ZendXml', $zf2Path);

if (!class_exists('Zend\Loader\AutoloaderFactory')) {
    throw new RuntimeException('Unable to load ZF2.');
}

// Run the application!
Zend\Mvc\Application::init(require BASE_PATH . '/config/application.config.php')->run();
</code>```

When I run this through PHP-CodeSniffer, I get a warning that:

A file should declare new symbols (classes, functions, constants, etc.) and cause no other side effects, or it should execute logic with side effects, but should not do both. The first symbol is defined on line 11 and the first side effect is on line 17.

Essentially, PSR-1 does not like that I have a constant definition and then a return statement later on.

Is this an instance where it doesn't matter - as long as the rest of the MVC framework and application is okay, then there's no problem?

答:
This rule and consequent warning is sensible - I definitely wouldn't like to see class/constant definitions mixed with side-effects in one file.

But in this particular case I wouldn't mind - PHP bootstrap files are usually a bit like this - setting up the environment which sometimes consists of several distinct (and possibly unrelated) steps.

You could declare the constant in the separate file (e.g. "constants.php") which you can then include into the bootstrap file - this should silence the CodeSniffer. Now, does this make your application better? Is the code better readable? I don't think so, at least for this one constant (if there are more, then yes, it makes sense).

Most such rules apply only in "most" cases, each one has some exceptions and I think think this is the case here ...


问:
Difference between class scope and object scope design patterns
Apparently design patterns have a ton of classifications. One I am struggling with is whether or not the pattern is a class scoped pattern or an object scoped pattern. Of course no documentation exists on the differences between the two, so I'm asking your opinion.

The GoF book defines it as:

"Class patterns deal with relationships between classes and their subclasses. These relationships are established through inheritance, so they are static-fixed at compile-time. Object patterns deal with object relationships, which can be changed at run-time and are more dynamic. Almost all patterns use inheritance to some extent. So the only patterns labelled "class patterns" are those that focus on class relationships. Note that most patterns are in the object scope."

Problem is, there are only class relationships as an object is nothing without its class. I've never heard of "object relationships" outside of this book.

答:
A class is a blueprint or template or set of instructions to build a specific type of object. A object is a instance of a class.

So a class patterns plays with things you can do with classes like abstraction, inheritance, interfaces, visibility scope, etc. A Object pattern plays with things you can do whith instance like references, pointers, creation and destruction, etc.

Anyway, I don't see this concept very important because most of the patterns mixes classes and objecs techniques to acomplish the objective.

OwnerDisplayName: Matt

OwnerDisplayName: jlvaquero


答:
You could probably hack it in, but I can't see the end result being particularly pretty or easy to use. Are you just looking to use the PHP testing framework to report test results, or are you hoping to call the javascript via the PHP?

Personally I'd use something like QUnit; the jquery testing framework. It's very easy to use and lets you use javascript to test javascript within a browser. You can also link it into Rhino (with env.js) to allow for automated headless test runs.

Title: Can I test effectively javascript functions with a PHP unit-testing framework?

Body:
If I want to unit-test some of my javascript functions, would it be more efficient (and doable) to use the already installed PHP unit-testing framework, or should I use a javascript unit-testing framework?

EDIT: It seems I have to clarify things a bit. I'm using javascript for form validation. It seems that some logic doesn't work as I want it to be, and I thought to myself that would be a good point to begin to use unit-testing (something that came to my scope only recently). I already began to use SimpleTest on a little project of mine, but never to test logic that is generated client-side.

Now I know that SimpleTest have the possibility to emulate a browser for example. But I was wondering what other method would they be to unit-test my form validation. While I was searching for idea, I realized that there is also unit-testing framework for javascript, but after a bit of searching on some of the SE sites, I didn't find anything about use of PHP and Javascript Framework together, so I wondered how common such a situation it was, and how do other people manage in such an environment.