答:
Understand the basic constructs of programming languages, and design patterns.

If you know how core things like declaration/initialization, loops, conditional statements, IO, etc you can pick up any language and 'work with' it.

Moving further (and as per your example) if you know design patterns well you can write efficient code in less time in any modern language like java or c#. So try going for the GOF design patterns book. This way you can 'master' the language.

If you know the constructs and the patterns, the rest is just syntax that you can look up in the reference library while coding. Looking at reference docs will be a bit slow in the beginning but once you have coded in a language for 2-3 years you will no longer need to look up the reference docs.

Title: I know the language but still can't code like other peers

Body:
I have moved to a new job and code base (been doing C#, .NET, Windows Forms, etc. for last four years) and I have been on this for three months until today. During these three months I caught up with parts of the language and syntax that I didn't know before (MVVM, Silverlight, some advanced stuff in .NET like Action, Func, Callbacks, etc.), so now I know those but still when I go in the code to fix a bug and see their code, I get disappointed, because I see some coding techniques that although I know the syntax and understand it but I think to myself "could I write this myself"?

The answer is no. For example they create classes that have a member as "Action" and at run-time they assign actions to separate instances, or register - unregister events at some parts of the code, etc.

Is it normal? and gets better by time? or I am just a stupid mediocre developer? and how can I make it better?


问:
So Singletons are bad, then what?
There has been a lot of discussion lately about the problems with using (and overusing) Singletons. I've been one of those people earlier in my career too. I can see what the problem is now, and yet, there are still many cases where I can't see a nice alternative - and not many of the anti-Singleton discussions really provide one.

Here is a real example from a major recent project I was involved in:

The application was a thick client with many separate screens and components which uses huge amounts of data from a server state which isn't updated too often. This data was basically cached in a Singleton "manager" object - the dreaded "global state". The idea was to have this one place in the app which keeps the data stored and synced, and then any new screens that are opened can just query most of what they need from there, without making repetitive requests for various supporting data from the server. Constantly requesting to the server would take too much bandwidth - and I'm talking thousands of dollars extra Internet bills per week, so that was unacceptable.

Is there any other approach that could be appropriate here than basically having this kind of global data manager cache object? This object doesn't officially have to be a "Singleton" of course, but it does conceptually make sense to be one. What is a nice clean alternative here?

答:
Singletons are just the projection of a serviced oriented architecture into a program.

An API is an example of a singleton at a protocol level. You access Twitter, Google etc through what are essentially singletons. So why do singletons become bad within a program?

It depends on how you think of a program. If you think of a program as society of services rather than randomly bound cached instances then singletons make perfect sense.

Singletons are a service access point. The public interface to a tightly bound library of functionality that hides perhaps a very sophisticated internal architecture.

So I don't see a singleton as that different from a factory. The singleton can have constructor parameters passed in. It can be created by some context that knows how to resolve the default printer against all the possible selection mechanisms, for example. For testing you can insert your own mock. So it can be quite flexible.

The key is internally in a program when I execute and need a bit of functionality I can access the singleton with full confidence that the service is up and ready for use. This is key when there are different threads starting in a process that must go through a state machine to be considered ready.

Typically I would wrap a XxxService class that wraps a singleton around class Xxx. The singleton isn't in class Xxx at all, it's separated out into another class, XxxService. This is because Xxx can have multiple instances, although it's not likely, but we still want to have one Xxx instance globally accessible on each system. XxxService provides a nice separation of concerns. Xxx doesn't have to enforce a singleton policy, yet we can use Xxx as a singleton when we need to.

Something like:

//XxxService.h:
/**
 * Provide singleton wrapper for Xxx object. This wrapper
 * can be autogenerated so is not made part of the object.
 */

#include "Xxx/Xxx.h"

class XxxService
{
    public:
    /**
     * Return a Xxx object as a singleton. The double check
     * singleton algorithm is used. A 0 return means there was
     * an error. Developers should use this as the access point to
     * get the Xxx object.
     *
     *

     * @@ #include "Xxx/XxxService.h"
     * @@ Xxx* xxx= XxxService::Singleton();
     *

     */

     static Xxx*     Singleton();

     private:
         static Mutex  mProtection;
};

//XxxService.cpp:

#include "Xxx/XxxService.h"                   // class implemented
#include "LockGuard.h"

// CLASS SCOPE
//
Mutex XxxService::mProtection;

Xxx* XxxService::Singleton()
{
    static Xxx* singleton;  // the variable holding the singleton

    // First check to see if the singleton has been created.
    //
    if (singleton == 0)
    {
        // Block all but the first creator.
        //
        LockGuard lock(mProtection);

        // Check again just in case someone had created it
        // while we were blocked.
        //
        if (singleton == 0)
        {
            // Create the singleton Xxx object. It's assigned
            // to a temporary so other accessors don't see
            // the singleton as created before it really is.
            //
            Xxx* inprocess_singleton= new Xxx;

            // Move the singleton to state online so we know that is has
            // been created and it ready for use.
            //
            if (inprocess_singleton->MoveOnline())
            {
                LOG(0, "XxxService:Service: FAIL MoveOnline");
                return 0;
            }

            // Wait until the module says it's in online state.
            //
            if (inprocess_singleton->WaitTil(Module::MODULE_STATE_ONLINE))
            {
                LOG(0, "XxxService:Service: FAIL move to online");
                return 0;
            }

            // The singleton is created successfully so assign it.
            //
            singleton= inprocess_singleton;

        }// still not created
    }// not created

    // Return the created singleton.
    //
    return singleton;

}// Singleton
```

ContentLicense: CC BY-SA 2.5

Title: So Singletons are bad, then what?

Body:
Singletons are just the projection of a serviced oriented architecture into a program.

An API is an example of a singleton at a protocol level. You access Twitter, Google etc through what are essentially singletons. So why do singletons become bad within a program?

It depends on how you think of a program. If you think of a program as society of services rather than randomly bound cached instances then singletons make perfect sense.

Singletons are a service access point. The public interface to a tightly bound library of functionality that hides perhaps a very sophisticated internal architecture.

So I don't see a singleton as that different from a factory. The singleton can have constructor parameters passed in. It can be created by some context that knows how to resolve the default printer against all the possible selection mechanisms, for example. For testing you can insert your own mock. So it can be quite flexible.

The key is internally in a program when I execute and need a bit of functionality I can access the singleton with full confidence that the service is up and ready for use. This is key when there are different threads starting in a process that must go through a state machine to be considered ready.

Typically I would wrap a XxxService class that wraps a singleton around class Xxx. The singleton isn't in class Xxx at all, it's separated out into another class, XxxService. This is because Xxx can have multiple instances, although it's not likely, but we still want to have one Xxx instance globally accessible on each system. XxxService provides a nice separation of concerns. Xxx doesn't have to enforce a singleton policy, yet we can use Xxx as a singleton when we need to.

Something like:

//XxxService.h:
/**
 * Provide singleton wrapper for Xxx object. This wrapper
 * can be autogenerated so is not made part of the object.
 */

#include "Xxx/Xxx.h"

class XxxService
{
    public:
    /**
     * Return a Xxx object as a singleton. The double check
     * singleton algorithm is used. A 0 return means there was
     * an error. Developers should use this as the access point to
     * get the Xxx object.
     *
     * <PRE>
     * @@ #include "Xxx/XxxService.h"
     * @@ Xxx* xxx= XxxService::Singleton();
     * <PRE>
     */

     static Xxx*     Singleton();

     private:
         static Mutex  mProtection;
};

//XxxService.cpp:

#include "Xxx/XxxService.h"                   // class implemented
#include "LockGuard.h"

// CLASS SCOPE
//
Mutex XxxService::mProtection;

Xxx* XxxService::Singleton()
{
    static Xxx* singleton;  // the variable holding the singleton

    // First check to see if the singleton has been created.
    //
    if (singleton == 0)
    {
        // Block all but the first creator.
        //
        LockGuard lock(mProtection);

        // Check again just in case someone had created it
        // while we were blocked.
        //
        if (singleton == 0)
        {
            // Create the singleton Xxx object. It's assigned
            // to a temporary so other accessors don't see
            // the singleton as created before it really is.
            //
            Xxx* inprocess_singleton= new Xxx;

            // Move the singleton to state online so we know that is has
            // been created and it ready for use.
            //
            if (inprocess_singleton->MoveOnline())
            {
                LOG(0, "XxxService:Service: FAIL MoveOnline");
                return 0;
            }

            // Wait until the module says it's in online state.
            //
            if (inprocess_singleton->WaitTil(Module::MODULE_STATE_ONLINE))
            {
                LOG(0, "XxxService:Service: FAIL move to online");
                return 0;
            }

            // The singleton is created successfully so assign it.
            //
            singleton= inprocess_singleton;

        }// still not created
    }// not created

    // Return the created singleton.
    //
    return singleton;

}// Singleton

ContentLicense: CC BY-SA 3.0


问:
Does “notification center” pattern encourage good or bad program design?
Sometimes I come across these message-hub-style APIs, for example the Cocoa NSNotificationCenter: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html

Usually these APIs provide a global access point on which you subscribe to or broadcast messages/events. I'm thinking this is a problem because it encourages a flat and unstructured program architecture, where dependencies are not explicit in the API, but hidden in the source code. You are not forced to think about object ownership and hierarchies, but can rather make any object in your program result in any code anywhere being called. But maybe this is a good thing?

Does this pattern generally encourage good or bad program design, and why so? Does it make the code harder or easier to test?

Forgive me if this question is too vague or broad. I'm trying to wrap my head around the potential consequences of extensive use of an API like this, and the different ways you could use it.

Edit: I guess my biggest issue with this pattern is that the API "lies" about dependencies and object couplings, and can be illustrated with this example:

```<code>myObj = new Foo();
myOtherObj = new Bar();
print myOtherObj.someValue; // prints 0
myObj.doSomething();
print myOtherObj.someValue; // prints 1, unexpectedly, because I never indicated that these objects had anything to do with each other
</code>```

答: It's good for event-driven systems, and is nicer than the alternative of having a bunch of Observers observing each other, as you're less likely to wind up with inadvertent infinite loops of observers firing events.  This was a real problem in the old VB days, when you had event-driven ActiveX controls that could be wired up to each other with event handlers.</p>


问:
How to visualize the design of a program in order to communicate it to others
I am (re-)designing some packages for R, and I am currently working out the necessary functions, objects, both internal and for the interface with the user. I have documented the individual functions and objects.

So I have the description of all the little parts. Now I need to give an overview of how the parts fit together. The scheme of the motor so to say.

I've started with making some flowchart-like graphs in Visio, but that quickly became a clumsy and useless collection of boxes, arrrows and-what-not. So hence the question:

Is there specific software you can use for vizualizing the design of your program

If so, care to share some tips on how to do this most efficiently

If not, how do other designers create the scheme of their programs and communicate that to others?

Edit: I am NOT asking how to explain complex processes to somebody, nor asking how to illustrate programming logic. I am asking how to communicate the design of a program/package, i.e.:

the objects (with key features and representation if possible)

the related functions (with arguments and function if possible)

the interrelation between the functions at the interface and the internal functions (I'm talking about an extension package for a scripting language, keep that in mind)

So something like this :

But better. This is (part of) the interrelations between functions in the old package that I'm now redesigning for obvious reasons :-)

PS : I made that graph myself, using code extraction tools on the source and feeding the interrelation matrix to yEd Graph Editor.

答:
I am using processing.org (Java) to model gene networks. This is essentially documenting DNA based software using a node diagram originally used to draw relationships in cell phone networks http://alignedleft.com/work/relationship-visualizer.

I replaced the cell phone numbers with genes (DNA software) and built a weight based model to analyze relationships between genes in cancer. I am experimenting with a model for stem cells.
http://nextbigfuture.com/2014/01/simple-acid-bath-can-turn-blood-cells.html#more


问:
Question regarding ExtJS 4 GPL/commercial license
I am currently in the process of selecting a widget framework to be used for a new project. Current choices are Dojo/ExtJS4. We are leaning on ExtJS4 but might have some issues with the licensing.

From the Sencha license page:

Our open source license is the appropriate option if you are creating an open source application under a license compatible with the GNU GPL license v3.

However on the GPL FAQ:

http://www.gnu.org/licenses/gpl-faq.html#UnreleasedMods

A company is running a modified version of a GPL'ed program on a web site. Does the GPL say they must release their modified sources?

The GPL permits anyone to make a modified version and use it without ever distributing it to others. What this company is doing is a special case of that. Therefore, the company does not have to release the modified sources.

It is essential for people to have the freedom to make modifications and use them privately, without ever publishing those modifications. However, putting the program on a server machine for the public to talk to is hardly “private” use, so it would be legitimate to require release of the source code in that special case. Developers who wish to address this might want to use the GNU Affero GPL for programs designed for network server use.

Seems contradicting on what they have on Sencha's licensing page. Moreover, the webapp will be deployed on the cloud and will offer a subscription model. I've read that this is the so called ASP loophole and that the Affero GPL was made to address this. The project will have multiple modules, but certainly there would be backend/integration and frontend modules. The frontend will just consume exposed REST services and will be an entirely different application.

The question is, would there be any license issues if we use the GPL version and willing to offer the source code (frontend module only) which uses ExtJS for our future clients?

答:
If you read Sencha's Licensing FAQ you will see that they the front end and back end part of a single package:

Even if only the front-end uses Ext JS code, you should consider that the combination of front and back ends constitutes the application, and the source code for both back and front end would need to be provided to the application’s end users under GPLv3...

Sencha makes it pretty clear that if you are using ExtJS for anything non-open source you need a commercial license.


问:
Handling "unspecified" values in software
So I'm working on a software product where we have a number of fields that the customer can leave blank, some of which are numeric. To persist these in the database we use nullable columns. Easy peasy.

I'm considering the utility of an object oriented domain model and one thing that bugs me is the issue of nullable fields.

The reason is, in the world of Java and C# one often finds advice against having null values and indeed writing code with null checks all over the place sucks. And then you get null reference exceptions when you forget to check for null. And it's a mess. So a "good" approach is to initialize everything when you declare it.

Now, the idea of null actually makes sense for these fields... the customer did not enter a value thus it has "no" value (not 0, not -1, etc). But application programmers and programming languages seem to be configured for binary rather than ternary logic, and also for variables just darn well having a value rather than maybe having a value but also maybe not.

With object oriented design I presume one could come up with some clever system of representing cases where there is "no" value but I personally haven't done the analysis yet and the reason is I find incremental change more successfully sells to people than radical change does, so proposing an object oriented domain model that's "too object oriented" might kill the idea and thus my hopes of improving the structure of our software. I'd rather propose a "version 0" domain model that works and is easy to sell internally... and so this whole thing about null values weighs heavy on my mind.

Since we are using C# I could just define nullable numbers, its very easy one just adds a question mark. But I'm not convinced that just because it's possible it's also the best approach.

So, with all this background junk out of the way my question is: how have you/your company handled "nonexistent" values in an object oriented domain model, in what ways did you find it effective and in what ways did you find it ineffective?

My selection criteria for the "answer" will be the one that seems most "sellable" as defined in the background junk. But really I'd like to see what people come up with and learn some new things so any answer with some thought behind it will receive an upvote from me.

Note: I've seen other discussions about null values in other threads but nothing that quite lines up with what I want to talk about, hence a new question.

EDIT: My question's scope includes value typed properties like numbers. So in C# one way to allow for representation of a null purchase price would be to declare "PurchasePrice" as "decimal?" which is the nullable decimal type. I just see a number of disadvantages to numbers (for example) that can also be null, so I'm looking for an alternative.

EDIT 2: The Null Object Pattern makes sense for references, and using a nullable type for values appears as if it may be tractable with coalescing. What bothers me about coalescing null types is "what if someone forgets to coalesce and we're exposed to a null reference exception?"... and I suppose I could maybe use a static analysis tool which ensures that coalescing is used where expected to allay that worry.

EDIT 2': In a sense, if someone has made a conscious decision to make a field nullable they are adding the ability to represent an extra piece of information that would otherwise need another field to represent it such as a boolean HasValue. Does that mean the "anti-null" zealots I've met in the past were perhaps incorrect, and measured use of nullity can in fact improve a design?

答:
There is a pattern called NullObject.

The only reason why I would say this can sell is that your tests whether this object is NUll or not are in the NUll object and thus...
When your software grows there is exactly one place to look for NULL-value-behaviour.
Code duplication is removed suppose:

```<code>function1(x) {
    if x is NULL {
        handleit(x)
    }
}

function2(x) {
    if x is NULL {
        handleit(x)
    }
}
</code>```

The two functions are in a different location or class so the handleit(x) can not be reused (forgotten/typechecks) if it is not in the Null-Object.

There are other people to reason about software quality and why it is good.
Be aware that your design decision is about your developers now and future developers.

I used this pattern once and it worked quite well. I think if you answer the following question with yes then the Null Object is not too far from your choice:

Should the code that affects the object be in the object?

Edit1: value types

Seeing http://msdn.microsoft.com/en-us/library/ms173104.aspx
you can create own value types. So you can create own value type null objects.
Value types are an optimization of the programming language.
For code pieces where optimization is necessairy you can use them. And otherwise use the reference types.

Body:
There is a pattern called NullObject.

The only reason why I would say this can sell is that your tests whether this object is NUll or not are in the NUll object and thus...
When your software grows there is exactly one place to look for NULL-value-behaviour.
Code duplication is removed suppose:

function1(x) {
    if x is NULL {
        handleit(x)
    }
}

function2(x) {
    if x is NULL {
        handleit(x)
    }
}

The two functions are in a different location or class so the handleit(x) can not be reused (forgotten/typechecks) if it is not in the Null-Object.

There are other people to reason about software quality and why it is good.
Be aware that your design decision is about your developers now and future developers.

I used this pattern once and it worked quite well. I think if you answer the following question with yes then the Null Object is not too far from your choice:

Should the code that affects the object be in the object?

Edit1: value types

Seeing http://msdn.microsoft.com/en-us/library/ms173104.aspx
you can create own value types. So you can create own value type null objects.
Value types are an optimization of the programming language.
For code pieces where optimization is necessairy you can use them. And otherwise use the reference types.


问:
Make an app that communicates with an app on a server over wifi
This is a very broad question, and I'm just looking for a pointer in the right direction more than a specific answer, but it's something I've always wondered and never known.

Lets say I have a program that I wrote, and I put it on a server. Then, I write an android app that I want to use to control that program (give it inputs, basically)

To boil it down even further, what I want to do is have a program that sits on a server, and basically make an android app that is just a gui for that program, and it can be controlled from anywhere, I guess sort of like a remote printing over Wi-Fi type of thing.

I really know nothing about this or even where to begin. I'd appreciate even some vocab words that point me in the right direction.

答:
You need basically three things:

A server machine with a program on it that can receive TCP/IP or UDP requests over WIFI

An Android app that can send those requests.

Some code that maps the requests to actions on the server machine.

There are a number of open-source projects that demonstrate the concept.  Here's one.


答:
Have each screen take in the Manager in their constructor.

When you start your app, you create one instance of the manager and pass it around.

This is called Inversion of Control, and allows you to swap out the controller when configuration changes and in tests. Additionally, you can run several instances of your application or parts of your application in parallell (good for testing!). Lastly your manager will die with its owning object (the startup class).

So structure your app like a tree, where things above owns everything used below them. Don't implement an app like a mesh, where everybody knows everybody and find each other through global methods.

Title: So Singletons are bad, then what?

Body:
There has been a lot of discussion lately about the problems with using (and overusing) Singletons. I've been one of those people earlier in my career too. I can see what the problem is now, and yet, there are still many cases where I can't see a nice alternative - and not many of the anti-Singleton discussions really provide one.

Here is a real example from a major recent project I was involved in:

The application was a thick client with many separate screens and components which uses huge amounts of data from a server state which isn't updated too often. This data was basically cached in a Singleton "manager" object - the dreaded "global state". The idea was to have this one place in the app which keeps the data stored and synced, and then any new screens that are opened can just query most of what they need from there, without making repetitive requests for various supporting data from the server. Constantly requesting to the server would take too much bandwidth - and I'm talking thousands of dollars extra Internet bills per week, so that was unacceptable.

Is there any other approach that could be appropriate here than basically having this kind of global data manager cache object? This object doesn't officially have to be a "Singleton" of course, but it does conceptually make sense to be one. What is a nice clean alternative here?


答:
I think you are mistaking something here. The problem of null in languages like Java and C# is that reference types are null by default. Eg, the null is implicit. That means there is no way to express idea of reference type always having a valid value. You always have to check for null. Even if you are sure the value cannot possibly be null, the Murphy's law says it will happen sometime, so checking is necessary. There is no way to have compiler do the checking for you. Of course there are ways like code contracts, but those are relatively new in those languages and require additional work from developer to do right.

The way Nullable value types work is exactly how it should work. The compiler knows there is one additional state and knows how you work with the variable. So it can create an error when it sees there is possibility dereferrencing this null state. For example, you cannot add Nullable<int> and int simply because compiler knows there is possibility of first value being null. So it forces you to do the checking before hand. Even simple assignment from nullable to non-nullable type is checked by compiler simply thanks to it's type. No such thing is possible for reference types. Of course there is problem of programmer just adding .Value to every access and be done with it, but that is problem of programmer's discipline that no tool can fix.

Summed up. Your worries about nullable value types are completely unjustified because null is only problem when it is implicit and compiler cannot check for possible errors of accessing null value. Which is not the case of Nullable value types.

Title: Handling "unspecified" values in software

Body:
So I'm working on a software product where we have a number of fields that the customer can leave blank, some of which are numeric. To persist these in the database we use nullable columns. Easy peasy.

I'm considering the utility of an object oriented domain model and one thing that bugs me is the issue of nullable fields.

The reason is, in the world of Java and C# one often finds advice against having null values and indeed writing code with null checks all over the place sucks. And then you get null reference exceptions when you forget to check for null. And it's a mess. So a "good" approach is to initialize everything when you declare it.

Now, the idea of null actually makes sense for these fields... the customer did not enter a value thus it has "no" value (not 0, not -1, etc). But application programmers and programming languages seem to be configured for binary rather than ternary logic, and also for variables just darn well having a value rather than maybe having a value but also maybe not.

With object oriented design I presume one could come up with some clever system of representing cases where there is "no" value but I personally haven't done the analysis yet and the reason is I find incremental change more successfully sells to people than radical change does, so proposing an object oriented domain model that's "too object oriented" might kill the idea and thus my hopes of improving the structure of our software. I'd rather propose a "version 0" domain model that works and is easy to sell internally... and so this whole thing about null values weighs heavy on my mind.

Since we are using C# I could just define nullable numbers, its very easy one just adds a question mark. But I'm not convinced that just because it's possible it's also the best approach.

So, with all this background junk out of the way my question is: how have you/your company handled "nonexistent" values in an object oriented domain model, in what ways did you find it effective and in what ways did you find it ineffective?

My selection criteria for the "answer" will be the one that seems most "sellable" as defined in the background junk. But really I'd like to see what people come up with and learn some new things so any answer with some thought behind it will receive an upvote from me.

Note: I've seen other discussions about null values in other threads but nothing that quite lines up with what I want to talk about, hence a new question.

EDIT: My question's scope includes value typed properties like numbers. So in C# one way to allow for representation of a null purchase price would be to declare "PurchasePrice" as "decimal?" which is the nullable decimal type. I just see a number of disadvantages to numbers (for example) that can also be null, so I'm looking for an alternative.

EDIT 2: The Null Object Pattern makes sense for references, and using a nullable type for values appears as if it may be tractable with coalescing. What bothers me about coalescing null types is "what if someone forgets to coalesce and we're exposed to a null reference exception?"... and I suppose I could maybe use a static analysis tool which ensures that coalescing is used where expected to allay that worry.

EDIT 2': In a sense, if someone has made a conscious decision to make a field nullable they are adding the ability to represent an extra piece of information that would otherwise need another field to represent it such as a boolean HasValue. Does that mean the "anti-null" zealots I've met in the past were perhaps incorrect, and measured use of nullity can in fact improve a design?


问:
Would it make sense to add parameters of an inferred type to inheritance?
I'll write this in PHP (where this thought originated), but this is generic to any object-orientated language. Basically, this is an addition to abstract classes that defines the implementation of its subclasses. Obviously, this could never go into interfaces because it defines how classes will be implemented, an immediate contradiction. Here are two examples:

```<code>class Boat { }
class RowBoat extends Boat { }
class MotorBoat extends RowBoat { }
class Yacht extends MotorBoat { }

class Screwdriver { }
class SoftScrewdriver extends Screwdriver { }
class PhillipsScrewdriver extends Screwdriver { }

abstract class Parent {
    public child function useScrewdriver(? extends Screwdriver &$screwdriver);

    public child function canOperateSimpleBoat(? super Yacht $yacht);
}
class Child1 extends Parent {
    public function useScrewdriver(SoftScrewdriver &$screwdriver) { }

    public function canOperateSimpleBoat(RowBoat &$rowBoat) { }
}
class Child2 extends Parent {
    public function useScrewdriver(PhillipsScrewdriver &$screwdriver) { }

    public function canOperateSimpleBoat(MotorBoat &$motorBoat) { }
}
</code>```

I used Java bounded type parameter syntax to represent how the abstract methods would work. What do you see as the positives and negatives of this language element?

EDIT: It turns out that this is actually a solely PHP issue that I tried to make into a larger OOP idea. I've continued it here:

https://stackoverflow.com/questions/21919069/what-version-of-php-allows-type-hints-to-override-typeless-identifiers/

答:
Negative as it goes against polymorphism. Imagine situation:

```<code>Parent par = new Child1()
par.useCrewdriver(new PhillipsScrewdriver())
</code>```

What should happen in this case? The compiler doesn't know that the concrete instance in par only works with SoftScrewdriver. If this is an error, then it can only be checked during runtime and would be problematic for compiled language that focus on catching this kind of errors during compilation. And if you are fine with this error at runtime, then you can simply implement it yourself with simple type checking and conversion. And if you can implement it yourself, there is not big need to extend the compiler.

Body:
Negative as it goes against polymorphism. Imagine situation:

Parent par = new Child1()
par.useCrewdriver(new PhillipsScrewdriver())

What should happen in this case? The compiler doesn't know that the concrete instance in par only works with SoftScrewdriver. If this is an error, then it can only be checked during runtime and would be problematic for compiled language that focus on catching this kind of errors during compilation. And if you are fine with this error at runtime, then you can simply implement it yourself with simple type checking and conversion. And if you can implement it yourself, there is not big need to extend the compiler.


问:
Building a web app with encrypted MySQL database entries?
I have some experience in building PHP based websites with MySQL access, storing encrypted user details, but all other fields being plain text. My most recent project will require sensitive data to be stored in the database. All of which I'm hosting myself.

I want to set up a system where a user can access his own entries and see the plain text results, but even if he was able to access someone else's they would be encrypted, unintelligible strings.

I have an idea of how to accomplish this, but perhaps it's not optimal or there exist tools to do this already in a more efficient way.

Store username as plain text, and password encrypted with sha1(). Or both encrypted with sha1().

Take the user's password (not the encrypted one, but the one he typed in and use it do define a key specific to that username and password, which will then be stored as a session variable.

Encrypt, or decrypt all of that users data with that key.

In my opinion even if someone gained access to the database and saw a list of plain text usernames and encrypted passwords they couldn't figure out the specific key since it's not stored anywhere. Therefore even if access was gained, they couldn't decipher the content of the sensitive database fields. Of course I'm building in ways to stop them accessing the database anyway, but as a catch-all effort this seems like a good set of steps.

Could the experts please comment on this, and offer some advice? Thanks a lot.

答:
According to MySQL, AES encryption (Advanced Encryption Standard) is the best method available for providing reversible encryption and decryption in SQL.

Formerly known as Rijndael, the AES_ENCRYPT and AES_DECRYPT functions are now built-in to MySQL so you can take user data, encrypt it with a salt, store it in your database, then extract it again later and decrypt it.

Define your salt

You'll need to apply a salt to the data that you encrypt. This is a special code that the encryption algorithm uses which works a bit like a key.

You'll need to provide the exact same key back to decrypt the data, and if an attacker should gain access to your database, they won't be able to decipher it without knowing the salt.

If you define your salt in PHP like this, you'll be able to pull the constant into your SQL statements more easily.

if(!define('SALT')) define('SALT','897sdn9j98u98jk');

To insert data into your MySQL database and encrypt the sensitive information, you'll need to issue a command like this, along with your salt.

INSERT INTO your_table (username,email,shoe size) VALUES ('$username', AES_ENCRYPT('$email','".SALT."'), AES_ENCRYPT('$shoesize','".SALT."'));

This will insert the username in plain text, as it's non-sensitive, but encrypt the user's email and shoesize, to prevent them from being viewed without access to the salt.

At some point, you're going to need to access some of the data you stored in its encrypted form, and you can do this very easily using the AES_DECRYPT function of MySQL and the same salt you used when you encrypted the data and inserted it.

SELECT username, AES_DECRYPT('email','".SALT."') AS email,
  AES_DECRYPT('shoesize','".SALT."') AS shoesize FROM your_table WHERE username ='fred';

If you SELECT the encrypted data without running it through AES_DECRYPT or with the wrong or no salt, you'll get an ugly, unreadable string of odd characters. This means if an attacker manages to access your database, but does not have access to your server to view the salt, they won't be able to read any of the data you've stored. At least, not without going to great lengths to try and decrypt the data.

Updating encrypted records is very similar to insertion. Basically, you just apply the same salt and re-issue the AES_ENCRYPT command to re-encrypt the data again and lock it away safely.

UPDATE your_table SET email = AES_ENCRYPT('$email','".SALT."'), shoesize = AES_ENCRYPT('$shoesize','".SALT."') WHERE username= 'fred';

Searching encrypted data using both AES_ENCRYPT and AES_DECRYPT

Things get a little bit more complicated when you need to search for data that's encrypted and then display it in its unencrypted form.

Say you wanted to search for a user using their email address, but you'd encrypted that in the database. First, you'd need to encrypt the email address you want to search for with AES_ENCRYPT and your salt, and then you'd need to use AES_DECRYPT to ensure that MySQL decrypted it, returning it in a readable format.

You can achieve this, using code a bit like this:

SELECT user_username,
  AES_DECRYPT(email,'".SALT."') AS email,
  AES_DECRYPT(shoesize,'".SALT."') AS shoesize
  FROM your_table WHERE
  (email = AES_ENCRYPT('$q','".SALT."'));

For further informations, please see this link: http://dev.mysql.com/doc/refman/5.1/en/encryption-functions.html


问:
DI or Factory Pattern ? Both ? or a different apprach?
Lets say we have an abstract class called BaseSwitch, inherited by concrete implementations Switch A and Switch B, Each Switch representing a real-life switch (A telephony tool which among its responsibilities is writing CDR; all data records of calls hitting the switch).

Each Switch in real life writes CDR in a different format and to different sources, say some switch writes to a text file another writes to a MySQL database.

The Switches as entities and CDR details are defined by the system's end user

My goal is writing Importer classes responsible for importing CDR based on the source of the data determined by the switch entity into my system, but hiding the Importer from the switch classes.

The layer responsible for importing the CDR will loop upon switches, and instatiate an 'Importer' object, based on the CDR format defined in each switch.

Can anyone suggest an approach to use ?

EDIT :
More clarification Below :

public class SwitchBase
    {
        public abstract string CDRFormat { get; }
    }

```<code>public class SwitchA:SwitchBase
{
    public override string abc
    {
        get { return "Text"; }
    }

}

public class SwitchB : SwitchBase
{
    public override string CDRFormat
    {
        get { return "MySQLDatabase"; }
    }
}

public class CDR
{ }

public class MySQLImporter
{
    ICollection<CDR> GetCDR()
    {
        //DoSomething
    }
}

public class TextImporter
{
    ICollection<CDR> GetCDR()
    {
        //DoSomething
    }
}
</code>```

答:
The Factory Pattern allows objects having different types but conforming to the same interface to be created, the specific type which is created being based on some condition. Seems particularly appropriate here.

So create some static methods with different overloads that each accept a different parameter signature and return the appropriate object (polymorphism), or create a single static method and put a switch statement in it that switches over a method parameter and returns the appropriate object.

```<code>public static class MyCDRFactory
{
    public static ICDRInterface Create(CDRFormat format)
    {
        switch (format)
            case CDRFormat.Alpha: return new CDRAlpha();

            case CDRFormat.Beta: return new CDRBeta();

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

ICDRInterface implementations:

```<code>public Class CDRAlpha: ICDRInterface
{
    // Implementation for Alpha format goes here
}

public Class CDRBeta: ICDRInterface
{
    // Implementation for Beta Format goes here
}
</code>```

Usage:

```<code>var processor = MyCDRFactory.Create(CDRFormat.Alpha);
</code>```

OwnerDisplayName: Siraj Mansour

Body:
The Factory Pattern allows objects having different types but conforming to the same interface to be created, the specific type which is created being based on some condition. Seems particularly appropriate here.

So create some static methods with different overloads that each accept a different parameter signature and return the appropriate object (polymorphism), or create a single static method and put a switch statement in it that switches over a method parameter and returns the appropriate object.

public static class MyCDRFactory
{
    public static ICDRInterface Create(CDRFormat format)
    {
        switch (format)
            case CDRFormat.Alpha: return new CDRAlpha();

            case CDRFormat.Beta: return new CDRBeta();

        // ..etc
    }
}

ICDRInterface implementations:

public Class CDRAlpha: ICDRInterface
{
    // Implementation for Alpha format goes here
}

public Class CDRBeta: ICDRInterface
{
    // Implementation for Beta Format goes here
}

Usage:

var processor = MyCDRFactory.Create(CDRFormat.Alpha);

OwnerDisplayName: Robert Harvey


问:
Testing vs Don't Repeat Yourself (DRY)
Why is repeating yourself by writing tests so highly encouraged?

It seems that tests basically express the same thing as the code, and hence is a duplicate (in concept, not implementation) of the code. Wouldn't the ultimate target of DRY include elimination of all test code?

答:
One of the biggest challenges to building software is to capture requirements; that is to answer the question, "what should this software do?"  Software needs exact requirements to accurately define what the system needs to do, but those who define the needs for software systems and projects often include people who do not have a software or formal (mathematics) background.  The lack of rigor in requirements definition forced software development to find a way to validate software to requirements.

The development team found themselves translating the colloquial description for a project into more rigorous requirements.  The testing discipline has coalesced as the checkpoint for software development, to bridge the gap between what a customer says they want, and what software understands they want.  Both the software developers and the quality/testing team form understanding of the (informal) specification, and each (independently) write software or tests to ensure that their understanding conform.  Adding another person to understand the (imprecise) requirements added questions and different perspective to further hone the precision of the requirements.

Since there has always been acceptance testing, it was natural to expand the testing role to write automated and unit tests.  The problem was that meant hiring programmers to do testing, and thus you narrowed the perspective from quality assurance to programmers doing testing.

That all said, you are probably doing testing wrong if your tests differ little from the actual programs.  Msdy suggestion would be to focus more on what in the tests, and less on how.

The irony is that rather than capture a formal specification of requirements from the colloquial description, industry has chosen to implement point tests as code to automate testing.  Rather than produce formal requirements which software could be built to answer, the approach taken has been to test a few points, rather than approach building software using formal logic.  This is a compromise, but has been fairly effective and relatively successful.

Title: Testing vs Don't Repeat Yourself (DRY)


问:
Why should passwords be encrypted if they are being stored in a secure database?
I have a web service. Right now, I have passwords stored in plain text in a MySQL table on my server. I know this isn't the best practice, and that is why I am working on it.

Why should passwords be encrypted if they are being stored in a secure database? I realize that if someone hacks in to my database they will get everyone's password. But I have other problems if someone gets in my database, for example, deleting data.

The scenario I can think of is that you are hacked. You restore a database from a couple of hours ago and everything is well. However, if your passwords are plaintext... The thief has all the passwords and you have to reset them all. Hassle to your users.

If the passwords were encrypted, you could just restore to previous database. Is this correct thinking?

答:
The scenario I can think of is that you are hacked.

Another scenario you need to think of: someone slipped your DBA (or whoever else can run select queries on your DB) $100, to give them the users' passwords. Or social engineers some intern to do that.

Then they use those passwords to log in to user's Gmail... or commerce site... (because people are ... less than smart shall we say - and use the same password across sites).

Then the irate user sues your company for exposing their password.

NOBODY (including people in your company) should be able to read plain text password. Ever. There's no legitimate business or technical need for that.


问:
Spending a good fortune on a certificate holding Scrum Master or a Veteran XP coach?
There is a very prestigious company that delivers a well-sold software about financial systems.  It has more that 20 years of history, and is staffed with about 20 programmers and much larger number of managerial staff.
Dissatisfied customers have reported strange bugs and no one has a clue what is wrong, hard to read code, and customization is prohibitively expensive. In a word, the software is rotten.

The company decided to spend a fortune and found the Agile thing as the remedy but they are stuck about what it is they need most urgently. Is it about the process or the developers or both? The challenge breaks down to the following options:

They can hire a certificate holding Scrum Master to teach them
Scrum. When asked about the value of doing it, the SM responded: "I
will prepare them to embrace Agile and only then they can go Agile
and save the product".

They can as well hire a veteran XP coach. When posed with the
same question he responded : "The most urgent problem is with the
programmers and not the management, XP will save the product from
rot and only then Scrum will make sense"

Developers are far from capable of doing agile programming practices at the moment. No unit tests, no pair programmings, no CI (huh? what is it?) ... you get the idea.

Some say they would be far better trying to improve their programming first (hire option 2) and then go with the process. Many say quite the opposite. Any insights ?

答:
I don't think this is an "XP or Scrum?" question. The question might be best phrased as "How do I improve the quality of this existing product?"

Secondly, As another poster pointed out, your product appears to be in "maintenance mode" rather than new product development. I would rarely advise Scrum for purely maintenance tasks.

So, I'm thinking a two-prong approach may serve you best.

With regard to quality, I'd say that helping the team to implement things like unit testing, Test Driven Development, Behaviour Driven Development and Refactoring would be a great starting point. Education first, then practice.

Next, to help with managing the way in which the product gets fixed, try something like Kanban.


问:
Best practice or design patterns for retrieval of data for reporting and dashboards in a domain-rich application
First, I want to say this seems to be a neglected question/area, so if this question needs improvement, help me make this a great question that can benefit others! I'm looking for advice and help from people who have implemented solutions that solve this problem, not just ideas to try.

In my experience, there are two sides of an application - the "task" side, which is largely domain driven and is where the users interact richly with the domain model (the "engine" of the application) and the reporting side, where users get data based on what happens on the task side.

On the task side, it's clear that an application with a rich domain model should have business logic in the domain model and the database should be used mostly for persistence. Separation of concerns, every book is written about it, we know what to do, awesome.

What about the reporting side? Are data warehouses acceptable, or are they bad design because they incorporate business logic in the database and the very data itself? In order to aggregate the data from the database into data warehouse data, you must have applied business logic and rules to the data, and that logic and rules didn't come from your domain model, it came from your data aggregating processes. Is that wrong?

I work on large financial and project management applications where the business logic is extensive. When reporting on this data, I will often have a LOT of aggregations to do to pull the information required for the report/dashboard, and the aggregations have a lot of business logic in them. For performance sake, I have been doing it with highly aggregated tables and stored procedures.

As an example, let's say a report/dashboard is needed to show a list of active projects (imagine 10,000 projects). Each project will need a set of metrics shown with it, for example:

total budget

effort to date

burn rate

budget exhaustion date at current burn rate

etc.

Each of these involves a lot of business logic. And I'm not just talking about multiplying numbers or some simple logic. I'm talking about in order to get the budget, you have to apply a rate sheet with 500 different rates, one for each employee's time (on some projects, other's have a multiplier), applying expenses and any appropriate markup, etc. The logic is extensive. It took a lot of aggregating and query tuning to get this data in a reasonable amount of time for the client.

Should this be run through the domain first? What about performance? Even with straight SQL queries, I'm barely getting this data fast enough for the client to display in a reasonable amount of time. I can't imagine trying to get this data to the client fast enough if I am rehydrating all these domain objects, and mixing and matching and aggregating their data in the application layer, or trying to aggregate the data in the application.

It seems in these cases that SQL is good at crunching data, and why not use it? But then you have business logic outside your domain model. Any change to the business logic will have to be changed in your domain model and your reporting aggregation schemes.

I'm really at a loss for how to design the reporting/dashboard part of any application with respect to domain driven design and good practices.

I added the MVC tag because MVC is the design flavor du jour and I am using it in my current design, but can't figure out how the reporting data fits into this type of application.

I'm looking for any help in this area - books, design patterns, key words to google, articles, anything. I can't find any information on this topic.

EDIT AND ANOTHER EXAMPLE

Another perfect example I ran across today. Customer wants a report for Customer Sales Team. They want what seems like a simple metric:

For each Sales person, what is their annual sales to date?

But that is complicated. Each sales person participated in multiple sales opportunities. Some they won, some they didn't. In each sales opportunity, there are multiple sales people who are each allocated a percentage of credit for the sale per their role and participation. So now imagine going through the domain for this...the amount of object rehydration you would have to do to pull this data from the database for every Sales person:

Get all the SalesPeople->

  For each get their SalesOpportunities->

  For each get their percentage of the sale and calculate their Sales amount

  then Add up all their SalesOpportunity Sales amount.

And that's ONE metric. Or you can write a SQL query which can do it quickly and efficiently and tune it to be fast.

EDIT 2 - CQRS Pattern

I've read about the CQRS Pattern and, while intriguing, even Martin Fowler says it's not tested. So how has this problem BEEN solved in the past. This has to have been faced by everyone at some point or another. What is an established or well-worn approach with a track record of success?

Edit 3 - Reporting Systems/Tools

Another thing to consider in this context is reporting tools. Reporting Services/Crystal Reports, Analysis Services and Cognoscenti, etc. all expect data from SQL/database. I doubt your data will come through your business later for these. And yet they and others like them are a vital part of the reporting in a lot of large systems.
How is the data for these properly handled where there is even business logic in the data source for these systems as well as possibly in the reports themselves?

答:
Retrieving large amounts of information over wide area networks, including the Internet, is problematic due to issues arising from latency of response, lack of direct memory access to data serving resources, and fault tolerance.

This question describes a design pattern for solving the issues of handling results from queries that return large amounts of data. Typically these queries would be made by a client process across a wide area network (or Internet), with one or more middle-tiers, to a relational database residing on a remote server.

The solution involves implementing a combination of data retrieval strategies, including the use of iterators for traversing data sets and providing an appropriate level of abstraction to the client, double-buffering of data subsets, multi-threaded data retrieval, and query slicing.

OwnerDisplayName: Richard DesLonde


问:
How to limit time period to another period?
For a project planning I have an initial period, lets call it PPStart-PPEnd.

The planning is associated with a project. This also has a period PrjStart-PrjEnd. PrjStart and PrjEnd are fixed, and can be unbound, i.e. the project start time or end time are not defined.

PPStart-PPEnd should be adjusted so that people can only plan tasks in the valid project period. If that changes the duration, fine.

How do I efficiently limit PPStart-PPEnd to PrjStart-PrjEnd without having to go over all the possible combinations?

Maybe first detecting overlapping periods is a good start?

4 examples on a time axis ([-- = bound, <-- = unbound):

```<code>Project planning period:
                              [---PPStart-PPEnd---]
Project periods relative to ppp:
                                    [---PrjStart-PrjEnd---]   PPStart should be set to PrjStart, PPEnd unchanged
                     [---PrjStart-PrjEnd---]                  PPEnd should be set to PrjEnd, PPStart unchanged
                     [---PrjStart-PrjEnd------------------->  No adjustments
    [---PrjStart-PrjEnd---]                                   PPStart should be set to PrjStart and PPEnd to PrjEnd.
</code>```

Cases like that last one make it complex.

答:
Answering my own question. There was no 'definitive' 'smart' answer yet.

The best I can come up with is still a bunch of if statements - meaning it does not satisfy my own question, but at least it's a complete schema covering all cases.

Schematically, these are what has to happen (first line is the proposed project plan period that has to be adjusted):

```<code>              ********************                 Suggested PPStart-PPEnd = 1 year
[--------]                          [--------]     PPStart := PrjStart   PPEnd := PrjEnd
          [--------]                               PPEnd   := PrjEnd
                               [--------]          PPStart := PrjStart   PPEnd unchanged, but let's take PPEnd := PPStart + 1 year
                    [--------]                     PPStart := PrjStart   PPEnd := PrjEnd
          [-------------------------]              -nothing-
          <--------]                               PPEnd   := PrjEnd
                               [-------->          PPStart := PrjStart   PPEnd unchanged, but let's take PPEnd := PPStart + 1 year
          <------------------------->              -nothing-
          <-------------------------]              -nothing-
          [------------------------->              -nothing-
</code>```

And then what's left is putting the if statements in a smart order

Body:
Answering my own question. There was no 'definitive' 'smart' answer yet.

The best I can come up with is still a bunch of if statements - meaning it does not satisfy my own question, but at least it's a complete schema covering all cases.

Schematically, these are what has to happen (first line is the proposed project plan period that has to be adjusted):

              ********************                 Suggested PPStart-PPEnd = 1 year
[--------]                          [--------]     PPStart := PrjStart   PPEnd := PrjEnd
          [--------]                               PPEnd   := PrjEnd
                               [--------]          PPStart := PrjStart   PPEnd unchanged, but let's take PPEnd := PPStart + 1 year
                    [--------]                     PPStart := PrjStart   PPEnd := PrjEnd
          [-------------------------]              -nothing-
          <--------]                               PPEnd   := PrjEnd
                               [-------->          PPStart := PrjStart   PPEnd unchanged, but let's take PPEnd := PPStart + 1 year
          <------------------------->              -nothing-
          <-------------------------]              -nothing-
          [------------------------->              -nothing-

And then what's left is putting the if statements in a smart order


问:
Tracking correct order details in commerce database when modifying 'products'
I am implementing an ecommerce database. This is slightly different than most as the 'products' that are for sale are for services provided. For example a user (vendor) of the system may define a service to 'wash your car'.

```<code>Table: Services
--------------------------------------------------
| ID (pk) |      Title       |    Description    |
--------------------------------------------------
     1       Home Services      wash your car
</code>```

I have omitted a number of columns, but should still be able to make my point.

A client can then purchase the Home Services. So I have an orders table with a FK to the the Services table. Standard ecommerce stuff.

The issue I have is what happens if the vendor decides to slightly update the description or even the title? This may have the affect of changing the entire service. For a normal commerce site, you'd add a discrete product. If this product changed, you would create a new product and discontinue the old one. With the packages, we need to allow updates as the description is the product and the sales pitch (maybe thats my problem though - maybe separate the two?) so I have to allow changes.

For example they could change the description to 'wash your car and clean your house'.

The obvious issue with this is that existing orders will still reference the same PK on the services table but the service is now different.

I'm wondering what the best solution is to allow changes to be added, but maintain the correct data for existing orders. One solution I thought of is to not update the row, but add a new one and a version number

```<code>Table: Services
------------------------------------------------------------------------------
| ID (pk) |      Title       |            Description             |  Version |
------------------------------------------------------------------------------
     1       Home Services     wash your car                           1
     2       Home Services     wash your car and clear your house      2
</code>```

We can now access the correct information for previous orders, and existing customers can purchase the new home services option.

This feels like a sensible way to do it, but want to see if anyone knew of any other solutions?

One other solution is to allow updates on the services table, but then for each order, save the description and title (similar to how sometimes in commerce schemas the final price is saved directly to the order). Issue I have with this is a lot of duplicate data being saved.

答:
For a normal commerce site, you'd add a discrete product. If this
  product changed, you would create a new product and discontinue the
  old one.

The moment you assign a new ID (which is the PK) to the updated row ('wash your car and clear your house') you are logically creating a new product and all your existing FK references will break.

```<code>Table: Services
------------------------------------------------------------------------------
| ID (pk) |      Title       |            Description             |  Version |
------------------------------------------------------------------------------
     1       Home Services     wash your car                           1
     2       Home Services     wash your car and clear your house      2
</code>```

This represents two unique services since their IDs are different and your version column has no use. You cannot track that these two rows are actually the same service that has been modified by the provider.

What you need to do is make the ID and the version a composite key and reference them from your other tables as FK. This way each order will point to a specific version of the service that is offered and will not cause any conflicts.

So your ORDERS table can have the foreign key defined as (ID,VERSION) which point to the composite (ID,VERSION) in SERVICES table.

e.g.

```<code>Table: Services
-----------------------------------------------------------------------------------
| ID (ck) |      Title       |            Description             |  Version (ck) |
-----------------------------------------------------------------------------------
     1       Home Services     wash your car                           1
     1       Home Services     wash your car and clear your house      2
</code>```

In this case, although your FKs will still have different FKs for (1,1) and (1,2) you can do a query where you search for ID=1 and you get the entire history of modification for service whose Id is 1. And your orders will still point to the correct version depending on when they were placed.

This may or may not be supported in your database so check this beforehand.

Some useful links:

MySQL: https://stackoverflow.com/questions/10565846/use-composite-primary-key-as-foreign-key

PostgreSQL: https://stackoverflow.com/questions/8575046/foreign-key-to-composite-key

Body:
For a normal commerce site, you'd add a discrete product. If this
  product changed, you would create a new product and discontinue the
  old one.

The moment you assign a new ID (which is the PK) to the updated row ('wash your car and clear your house') you are logically creating a new product and all your existing FK references will break.

Table: Services
------------------------------------------------------------------------------
| ID (pk) |      Title       |            Description             |  Version |
------------------------------------------------------------------------------
     1       Home Services     wash your car                           1
     2       Home Services     wash your car and clear your house      2

This represents two unique services since their IDs are different and your version column has no use. You cannot track that these two rows are actually the same service that has been modified by the provider.

What you need to do is make the ID and the version a composite key and reference them from your other tables as FK. This way each order will point to a specific version of the service that is offered and will not cause any conflicts.

So your ORDERS table can have the foreign key defined as (ID,VERSION) which point to the composite (ID,VERSION) in SERVICES table.

e.g.

Table: Services
-----------------------------------------------------------------------------------
| ID (ck) |      Title       |            Description             |  Version (ck) |
-----------------------------------------------------------------------------------
     1       Home Services     wash your car                           1
     1       Home Services     wash your car and clear your house      2

In this case, although your FKs will still have different FKs for (1,1) and (1,2) you can do a query where you search for ID=1 and you get the entire history of modification for service whose Id is 1. And your orders will still point to the correct version depending on when they were placed.

This may or may not be supported in your database so check this beforehand.

Some useful links:

MySQL: https://stackoverflow.com/questions/10565846/use-composite-primary-key-as-foreign-key

PostgreSQL: https://stackoverflow.com/questions/8575046/foreign-key-to-composite-key


问:
What changes can I make to my IDE to minimize the effect of my dyslexia?
I program and I am dyslexic. My vision is excellent. I do poorly processing symbols and am a visual thinker.

When I code, I'm slower than normal people because I am unpredictably unaware of the errors I make. I am learning python and the text only development environments cause me a lot of visual stress; I am using Wingware which is somewhat helpful, but cant complete assignments in the time given.

Can you suggest an accommodation that would help me?

What adaptations would be helpful to me?

Is there any way I can automatically find, highlight and fix these kinds of errors?

Proofreading, I see what I expect to see or something familiar. I don't notice typos, skip lines etc and the bugs turn up in testing. Even copy & pasting I can miss lines and cause errors.

Blocks of text from margin to margin give me headaches as do some color combinations

I do not process text as symbols, rather as objects that can be rotated, transposed so that the digits in a number move to different places, I may perceive "123" AS "132", THE LETTERS "pddq", look the same to me. I think of these as tricky - the same shape rotated and reflected.

答:
Semantic Highlighting

zwabel provides a great explanation in the post C++ IDE Evolution: From Syntax Highlighting to Semantic Highlighting:

The additional structure [of semantic highlighting] splits the
code-blobs up, and makes them perfectly readable.

[...]
my favorite
part of the semantic highlighting: Local Variable Colorization. That
colorization assigns a semi-unique color to each variable in a local
context. This allows much easier distinguishing those variables,
largely without reading their full name at all.

(emphasis mine)

This will (hopefully) allow you to recognize a miss-type due to the instant colour feedback when a variable is highlighted differently.

IDEs which support Semantic Highlighting

(based on a cursory Google search):

KDevelop4

Scala IDE for eclipse

Eclipse

Qt Creator

emacs (sort of)

vim (via plugins)

Code::Blocks (via plugin)

NetBeans (for Python and possibly others)

Visual Studio

IntelliJ IDEA (via plugin)

ContentLicense: CC BY-SA 4.0


问:
How do I traverse a tree without using recursion?
I have a very large in memory node tree and need to traverse the tree. Passing the returned values of each child node to their parent node. This has to be done until all the nodes have their data bubble up to the root node.

Traversal works like this.

```<code>private Data Execute(Node pNode)
{
    Data[] values = new Data[pNode.Children.Count];
    for(int i=0; i < pNode.Children.Count; i++)
    {
        values[i] = Execute(pNode.Children[i]);  // recursive
    }
    return pNode.Process(values);
}

public void Start(Node pRoot)
{
    Data result = Execute(pRoot);
}
</code>```

This works fine, but I'm worried that the call stack limits the size of the node tree.

How can the code be rewritten so that no recursive calls to Execute are made?

答:
You can't traverse a data structure in the shape of a tree without using recursion - if you don't use the stack frames and function calls provided by your language, you basically have to program your own stack and function calls, and it is unlikely that you manage to do it within the language in  more efficient manner way than the compiler writers did on the machine that your program would run on.

Therefore, avoiding recursion for fear of running into resource limits is usually misguided. To be sure, premature resource optimization is always misguided, but in this case it is likely that even if you measure and confirm that memory usage is the bottleneck, you will probably not be able to improve on it without dropping down to the level of the compiler writer.


答:
Here is a general purpose tree traversal implementation that doesn't use recursion:

```<code>public static IEnumerable<T> Traverse<T>(T item, Func<T, IEnumerable<T>> childSelector)
{
    var stack = new Stack<T>();
    stack.Push(item);
    while (stack.Any())
    {
        var next = stack.Pop();
        yield return next;
        foreach (var child in childSelector(next))
            stack.Push(child);
    }
}
</code>```

In your case you can then call it like so:

```<code>IEnumerable<Node> allNodes = Traverse(pRoot, node => node.Children);
</code>```

Use a Queue instead of a Stack for a breath first, rather than depth first, search.  Use a PriorityQueue for a best first search.

Title: How do I traverse a tree without using recursion?

Body:
I have a very large in memory node tree and need to traverse the tree. Passing the returned values of each child node to their parent node. This has to be done until all the nodes have their data bubble up to the root node.

Traversal works like this.

```<code>private Data Execute(Node pNode)
{
    Data[] values = new Data[pNode.Children.Count];
    for(int i=0; i < pNode.Children.Count; i++)
    {
        values[i] = Execute(pNode.Children[i]);  // recursive
    }
    return pNode.Process(values);
}

public void Start(Node pRoot)
{
    Data result = Execute(pRoot);
}
</code>```

This works fine, but I'm worried that the call stack limits the size of the node tree.

How can the code be rewritten so that no recursive calls to Execute are made?

Body:
Here is a general purpose tree traversal implementation that doesn't use recursion:

public static IEnumerable<T> Traverse<T>(T item, Func<T, IEnumerable<T>> childSelector)
{
    var stack = new Stack<T>();
    stack.Push(item);
    while (stack.Any())
    {
        var next = stack.Pop();
        yield return next;
        foreach (var child in childSelector(next))
            stack.Push(child);
    }
}

In your case you can then call it like so:

IEnumerable<Node> allNodes = Traverse(pRoot, node => node.Children);

Use a Queue instead of a Stack for a breath first, rather than depth first, search.  Use a PriorityQueue for a best first search.


问:
Short Sequential Search vs. Regular Sequential Search
Assuming a list of elements is sorted in ascending order, we search sequentially from the first element comparing the target to successive elements either until we find the target (succeed) or until the current element is greater than the target or we reach the end of the list (fail).

Is Short Sequential Search ever more efficient than regular sequential search? If so, when?

答:
Every search algorithm eventually looks at every element in at least one case (otherwise they couldn't find it if it is the desired value), and all search algorithms differ in the order in which they look at these elements for at least one input (otherwise they'd be effectively identical). So yes, every algorithm is faster than some other algorithm on at least one input.

For instance, a fast sequential search will be faster if the element you wanted to find happens to be at the very beginning, while a binary search will be faster if it is exactly in the middle. For an instance of your exact example, you should explain what precisely you mean by "regular sequential search".


问:
Algorithm for Learning development
This is a fairly general question. I know a bit of Perl and Python and I am looking to learn programming in more depth so that once I get the hang of it I can start developing applications and then websites.

I would like to know of an algorithm (sequence of steps :)) that could describe my approach towards learning programming in general. I have posted small questions on Perl/Python and I have recieved great help from everyone.

Note:- I am not in a hurry to learn. I know it takes time and that's fine.

Please give any suggestions you think are valid. Also, please don't push me to learn Lisp, Haskell etc - I am a beginner.

答: Best way is to learn basics/fundamentals of a programming language and then join a company as a junior developer (contractor). This will be the fastest way to learn and make money as well for your time ;)</p>

Title: Algorithm for Learning development


问:
Scala class with constructor requiring parameter of the same Class type
I can't remember but recently in one of the APIs I saw something like this class A (member:A){}. Scala does support it and there is no problem creating such a class but how do we initiate it and what purpose would such a class serve?

答:
Something like var childNode = new Node(parentNode).  You'd use it whenever you want a reference to anything of the same type.  In this case, it might be reasonable to allow a null-valued parameter:

```<code>var root = new Node(null)
var child = new Node(root)
</code>```

Body:
Something like var childNode = new Node(parentNode).  You'd use it whenever you want a reference to anything of the same type.  In this case, it might be reasonable to allow a null-valued parameter:

var root = new Node(null)
var child = new Node(root)


问:
Is it okay to define a [] method in ruby's NilClass?
Ruby by default does not include the method [] for NilClass

For example, to check if foo["bar"] exists when foo may be nil, I have to do:

```<code>foo = something_that_may_or_may_not_return_nil
if foo && foo["bar"]
  # do something with foo["bar"] here
end
</code>```

If I define this method:

```<code>class NilClass
  def [](arg)
    nil
  end
end
</code>```

Something like that would make this possible, even if foo is nil:

```<code>if foo["bar"]
  # do something with foo["bar"]
end
</code>```

Or even:

```<code>if foo["bar"]["baz"]
  # do something with foo["bar"]["baz"] here
end
</code>```

Question:
Is this a good idea or is there some reason ruby doesn't include this functionality by default?

EDIT July 2017: My core complaint was the unwieldy foo && foo["bar"] && foo ["bar"]["baz"] idiom required to access nested values when at any point the value may be nil. As of Ruby 2.3, Array#dig and Hash#dig exist, which addresses my concern. Now I can use the following idiom!

```<code>if foo && foo.dig("bar", "baz")
  # do something
end

# Note that errors will still occur if a value isn't what you expect. e.g.
foo = { "a" => { "b" => "c" } }
foo && foo.dig("a", "b", "c") # raises TypeError: String does not have #dig method
</code>```

答:
Why does something_that_may_or_may_not_return_nil have to return nil? And if you don't want to change that method, just wrap it in another method that returns an empty hash if the wrapped method returns nil.

As for nesting, you can use Hash's default_proc to return empty hashes when a key isn't found:

```<code># self-referential, to provide arbitrary depth
default_proc = ->(h,k){ Hash.new(&default_proc) }
some_hash.default_proc = default_proc
</code>```

The above lets you access deeply undefined entries without making any changes. But you also need to use empty? instead of treating the result as a simple boolean.

```<code>some_hash[:a][:b][:c].empty?
</code>```

If you want a solution that will also store those new empty hashes into the parent, use this default_proc instead:

```<code>default_proc = ->(h,k){ h[k] = {}.tap{|newh| newh.default_proc = default_proc } }
# This will auto-vivify:
some_hash = {}
some_hash.default_proc = default_proc
some_hash[:a][:b][:c]
some_hash  # {:a=>{:b=>{:c=>{}}}}
</code>```

Also, Rails provides the try method, that only calls the named method if the receiver isn't nil. Yeah, it's a lot uglier.

```<code>foo.try(:[], 'bar').try(:[], 'baz')
</code>```

It might be better to wrap the arbitrarily-deep hash into a class that hides away the ugliness. For example, does the ['bar']['baz'] entry have some real-world meaning? If so, you can put a method on that class and have that method reach into that depth without the caller needing to worry about it.

Body:
Why does something_that_may_or_may_not_return_nil have to return nil? And if you don't want to change that method, just wrap it in another method that returns an empty hash if the wrapped method returns nil.

As for nesting, you can use Hash's default_proc to return empty hashes when a key isn't found:

# self-referential, to provide arbitrary depth
default_proc = ->(h,k){ Hash.new(&default_proc) }
some_hash.default_proc = default_proc

The above lets you access deeply undefined entries without making any changes. But you also need to use empty? instead of treating the result as a simple boolean.

some_hash[:a][:b][:c].empty?

If you want a solution that will also store those new empty hashes into the parent, use this default_proc instead:

default_proc = ->(h,k){ h[k] = {}.tap{|newh| newh.default_proc = default_proc } }
# This will auto-vivify:
some_hash = {}
some_hash.default_proc = default_proc
some_hash[:a][:b][:c]
some_hash  # {:a=>{:b=>{:c=>{}}}}

Also, Rails provides the try method, that only calls the named method if the receiver isn't nil. Yeah, it's a lot uglier.

foo.try(:[], 'bar').try(:[], 'baz')

It might be better to wrap the arbitrarily-deep hash into a class that hides away the ugliness. For example, does the ['bar']['baz'] entry have some real-world meaning? If so, you can put a method on that class and have that method reach into that depth without the caller needing to worry about it.


问:
How do I explain a ruby method with a real-world analogy?
I am looking for a good analogy to help the concept of a method in ruby stick in my head. When I truly understand a concept, an image flashes in my mind that relates something physical to the abstract concepts I am trying to learn.

For example, someone explained the concept of a variable to me in the following way:

A variable is like a box you can put things in. The name of the variable is like taking a sharpie and writing a word, like "forks" on the side of the box. Picking a good name is important. You can stick anything in the box, but if you write 'forks' on the side of the box, you would expect forks to be in the box. You can put anything in the box, then carry it around to various people, and tell them "there are forks in this box." When they need a fork, they go to the fork box and get out a fork.

That's the sort of physical, image-based, concrete analogy I am looking for for a ruby method.

Right now most definitions I have found are useless to me. For example, at turtorialspoint, the first result for the google search 'what is a ruby method,' has the folowing definition.

Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit.

Let me give you an example of why this definitions is useless to me. I'm going to replace every word and concept in this definition that I don't understand with the word 'blah.'

Ruby blah are very similar to blah in any other programming language. Ruby blah are used to blah one or more blah blah into a single blah.

In summary, can I get a good, physical analogy for the concept of a method in ruby?

答:
You can use a microwave manually, by setting the time you want to use it for. You might want to melt butter for 15 seconds, so you push 1, 5, and "Start".

But the microwave also comes with convenient buttons you can use, like defrost, popcorn, rice, etc. If you think of them as ruby methods, it would be:

```<code>food_item.bacon
food_item.defrost
food_item.rice
</code>```

You don't have to put the time manually. The microwave already knows what to because someone  wrote those methods:

```<code>def bacon
    # Push the buttons to cook bacon, 8:00 minutes
    push 8
    push 0
    push 0
    push "Start"
end
</code>```

If you melt butter often, you could add a convenient button/method:

```<code>def butter
    # Push the buttons to melt butter, 15 seconds
    push 1
    push 5
    push "Start"
end
</code>```

And then you could just push the butter button, or call it in your code:

food_item.butter

... now I'm hungry :/

Body:
You can use a microwave manually, by setting the time you want to use it for. You might want to melt butter for 15 seconds, so you push 1, 5, and "Start".

But the microwave also comes with convenient buttons you can use, like defrost, popcorn, rice, etc. If you think of them as ruby methods, it would be:

food_item.bacon
food_item.defrost
food_item.rice

You don't have to put the time manually. The microwave already knows what to because someone  wrote those methods:

def bacon
    # Push the buttons to cook bacon, 8:00 minutes
    push 8
    push 0
    push 0
    push "Start"
end

If you melt butter often, you could add a convenient button/method:

def butter
    # Push the buttons to melt butter, 15 seconds
    push 1
    push 5
    push "Start"
end

And then you could just push the butter button, or call it in your code:

food_item.butter

... now I'm hungry :/


答:
From another perspective:

A method is an action you can ask something (usually stored in a variable) to perform for you.

For instance, you could ask a whiteboard to erase itself. It doesn't matter how it's done, it might be a fancy electronic whiteboard with self erasing capabilities, or when you push the erase button it calls downstairs and an someone comes up and erases the whiteboard for you.
But the result is what matters: you have a dirty whiteboard, when you call the erase method it gets cleaned.

Similarly, you could have a microwave.cook( meal, duration, power ) method - where you give the microwave your meal, set a duration and power, and press the cook button. The result (the return value of the method) is a cooked meal (or it could mutate the meal object you're passing to make it cooked).

You have complex methods (shuttle.go_to_the_moon), and simple methods (meal.are_you_cooked?) - that don't do anything, but just ask the object its state. The implementation of a method is like the recipe from the perspective of the object: as a whiteboard, to erase myself, I need to issue a call to the cleaning department and tell them I need to be cleaned. If you're writing the method, you obviously need to figure it out. But if you're just calling it, you don't need to care.

(I don't like the recipe analogy much though, as it's code centric, and when you design software code doesn't matter as much as how you call it).

Title: How do I explain a ruby method with a real-world analogy?

Body:
I am looking for a good analogy to help the concept of a method in ruby stick in my head. When I truly understand a concept, an image flashes in my mind that relates something physical to the abstract concepts I am trying to learn.

For example, someone explained the concept of a variable to me in the following way:

A variable is like a box you can put things in. The name of the variable is like taking a sharpie and writing a word, like "forks" on the side of the box. Picking a good name is important. You can stick anything in the box, but if you write 'forks' on the side of the box, you would expect forks to be in the box. You can put anything in the box, then carry it around to various people, and tell them "there are forks in this box." When they need a fork, they go to the fork box and get out a fork.

That's the sort of physical, image-based, concrete analogy I am looking for for a ruby method.

Right now most definitions I have found are useless to me. For example, at turtorialspoint, the first result for the google search 'what is a ruby method,' has the folowing definition.

Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit.

Let me give you an example of why this definitions is useless to me. I'm going to replace every word and concept in this definition that I don't understand with the word 'blah.'

Ruby blah are very similar to blah in any other programming language. Ruby blah are used to blah one or more blah blah into a single blah.

In summary, can I get a good, physical analogy for the concept of a method in ruby?


答:
An object is an entity with identity, state and behaviour.

Make an analogy with. say. living organisms.

Identity is pretty easy - two organism are same when they are equal (in state and behaviour), but also occupy the same space (eg. it is the same dog, just two people call him with two different names).

State are variables, that is, physical attributes. Skin colour, eye colour, health ... those are all parts of the state; when simulated in a program, it will be variables.

Behaviour is, well, how an object changes its own or external state when reacting to a stimulusl. These are methods. Lots of instances of the same class (lots of dogs with the same breed) share the same basic behaviour based on their state (the methods are defined in the class; while attributes are defined in an instance; method manipulate instance variables). Plus there is individual pattern of behaviour (singleton class).


问:
Why is it bad to use redundancy with logical operators?
I'm moving over to work on a library that a fellow developer has been writing. It's full of == true and == false, which I find crazy frustrating to read.

I've tried asking him to quit doing it, but he just says that it makes it more straightforward to understand what is going on. Is there a good reason why this isn't a great practice? Or is it purely a stylistic thing?

答:
The bigger the code the more time it takes to read and the more chance you have to misunderstand something.

== true is 7 characters that contribute nothing to the code and thus is pure cost, no benefit.

I wouldn't be so harsh on == false, though.  You can make an argument between negation and a comparison to false, while you can argue negation is superior it's not absolutely trumped like in the == true case.


答:
I too find this frustrating, up there with

```<code>if (condition)
    return true;
else
    return false;
</code>```

It indicates to me a lack of understanding of what booleans do. Any additional complexity in code is a potential source of bugs, although this one is trivial enough I could put it off to stylistic differences. You can get used to anything.

Title: Why is it bad to use redundancy with logical operators?

Body:
I'm moving over to work on a library that a fellow developer has been writing. It's full of == true and == false, which I find crazy frustrating to read.

I've tried asking him to quit doing it, but he just says that it makes it more straightforward to understand what is going on. Is there a good reason why this isn't a great practice? Or is it purely a stylistic thing?

Body:
I too find this frustrating, up there with

if (condition)
    return true;
else
    return false;

It indicates to me a lack of understanding of what booleans do. Any additional complexity in code is a potential source of bugs, although this one is trivial enough I could put it off to stylistic differences. You can get used to anything.


答:
It isn't, in general.  For compiled languages the expression will be likely reduced to the same machine code, and in interpreted languages the explicit test will help reduce the chance of unwanted code insertion.

Consider the following JavaScript function, to, say, tally votes on a hypothetical ballot measure.

```<code>function recordVote(YesOrNo) {
  if(YesOrNo == true) {
    voteYes();
  } elseif (YesOrNo == false) {
    voteNo();
  }
}
</code>```

If you call recordVote(true) or recordVote(false), the interior method fires as expected.  And, if you improperly call recordVote(42), recordVote(null), or recordVote("false"), you get no action -- which is desired for a voting app.  (especially since the standard test for truthyness, of if(YesOrNo), would cause that last one to record a vote incorrectly.

Of course, note that the small benefits you get from the above are inferior to consistency in your code.  If the library's already full of them, don't remove them -- but don't add them if it isn't.  (Unless, of course, you're refactoring everything anyway and have some arbitrary style rule to force your source code to be as small as possible...)

Body:
It isn't, in general.  For compiled languages the expression will be likely reduced to the same machine code, and in interpreted languages the explicit test will help reduce the chance of unwanted code insertion.

Consider the following JavaScript function, to, say, tally votes on a hypothetical ballot measure.

function recordVote(YesOrNo) {
  if(YesOrNo == true) {
    voteYes();
  } elseif (YesOrNo == false) {
    voteNo();
  }
}

If you call recordVote(true) or recordVote(false), the interior method fires as expected.  And, if you improperly call recordVote(42), recordVote(null), or recordVote("false"), you get no action -- which is desired for a voting app.  (especially since the standard test for truthyness, of if(YesOrNo), would cause that last one to record a vote incorrectly.

Of course, note that the small benefits you get from the above are inferior to consistency in your code.  If the library's already full of them, don't remove them -- but don't add them if it isn't.  (Unless, of course, you're refactoring everything anyway and have some arbitrary style rule to force your source code to be as small as possible...)


答:
I agree with your point, and I too find it frustrating to read; however, when you have a lone negated if condition like so:

```<code>if(!condition)
    doThis();
</code>```

I've been told by a few senior devs that it can be easy to miss the negation operator when reviewing code and they prefer to see:

```<code>if(condition == false)
    doThis();
</code>```

I agree with you that it is too verbose; however, it seems that in some instances like the one I described, some people would rather have that.

Body:
I agree with your point, and I too find it frustrating to read; however, when you have a lone negated if condition like so:

if(!condition)
    doThis();

I've been told by a few senior devs that it can be easy to miss the negation operator when reviewing code and they prefer to see:

if(condition == false)
    doThis();

I agree with you that it is too verbose; however, it seems that in some instances like the one I described, some people would rather have that.


答:
Depending on the language, the semantics are not so trivial. In Python:

```<code>class X:
    def __cmp__(self, other):
        return 1
    def __nonzero__(self):
        return False

if X():
    print "'X()' evaluated to: true"
else:
    print "'X()' evaluated to: false"

if X() == False:
    print "'X() == False' evaluated to: true"
else:
    print "'X() == False' evaluated to: false"

if X() == 0:
    print "'X() == 0' evaluated to: true"
else:
    print "'X() == 0' evaluated to: false"

if X() is False:
    print "'X() is False' evaluated to: true"
else:
    print "'X() is False' evaluated to: false"

if X() is None:
    print "'X() is None' evaluated to: true"
else:
    print "'X() is None' evaluated to: false"
</code>```

prints

```<code>'X()' evaluated to: false
'X() == False' evaluated to: false
'X() == 0' evaluated to: false
'X() is False' evaluated to: false
'X() is None' evaluated to: false
</code>```

Certainly one can make a case, even in python, for ignoring the operator. The problem is that it may be misleading for who wrote the code ("python must be just like [whatever-language], so I'll leave the equality operator implicit") and for who reads it ("was he really intending to eq compare implicitly or should it be an explicit is?").

It is very time consuming to track down bugs caused by implicit boolean checks that should be explicit (and correct).

Body:
Depending on the language, the semantics are not so trivial. In Python:

class X:
    def __cmp__(self, other):
        return 1
    def __nonzero__(self):
        return False

if X():
    print "'X()' evaluated to: true"
else:
    print "'X()' evaluated to: false"

if X() == False:
    print "'X() == False' evaluated to: true"
else:
    print "'X() == False' evaluated to: false"

if X() == 0:
    print "'X() == 0' evaluated to: true"
else:
    print "'X() == 0' evaluated to: false"

if X() is False:
    print "'X() is False' evaluated to: true"
else:
    print "'X() is False' evaluated to: false"

if X() is None:
    print "'X() is None' evaluated to: true"
else:
    print "'X() is None' evaluated to: false"

prints

'X()' evaluated to: false
'X() == False' evaluated to: false
'X() == 0' evaluated to: false
'X() is False' evaluated to: false
'X() is None' evaluated to: false

Certainly one can make a case, even in python, for ignoring the operator. The problem is that it may be misleading for who wrote the code ("python must be just like [whatever-language], so I'll leave the equality operator implicit") and for who reads it ("was he really intending to eq compare implicitly or should it be an explicit is?").

It is very time consuming to track down bugs caused by implicit boolean checks that should be explicit (and correct).