问:
Advice on architecture (WCF / MVC)
First of all, the basics.

N-tier application: presentation, business layer, database. It is an old .NET 2.0 (WSE + WinForms) application, a bit more tightly coupled than I'd like, and the requirement is to upgrade it to a newer architecture, while at the same time eliminating the less-than-ideal design choices made 10+ years ago (e.g. use DTOs instead of datatables/DB views directly on the client etc.).

I'm thinking of going by the following design, in broad strokes:

Create a business logic layer class that will include all business logic, validations etc., using a data access class for CRUD operations.

Expose this BLL using a WCF service layer as a wrapper for its methods.

Consume the WCF service by the new client (WPF probably).

To centralize all WCF-related operations in the client project, I will create a helper class that handles the connection to the WCF service and acts like a Façade to the service operations.

Now, at the same time, there will be a new Web application (MVC) that will use some of the operations defined in the BLL. However, due to outsourcing and other reasons out of the scope of this question, what I particularly don't want is for the MVC controller developer to use (or even know of) e.g. BLLAssembly.WCFOnlyMethod(). Conversely, I wouldn't want the WCF service developer to be able to use BLLAssembly.WebOnlyMethod(). I guess both of those cases can be covered by using conditional compilation symbols in the BLL assembly (e.g. WEB_ONLY / WCF_ONLY), but of course this means two different versions of it, one for each project.

So, my question is:

Given the fact that there will be a single BLL in order to maximize code reuse, what is the optimal approach for referencing the BLL from the WCF service and the MVC controller?

The WCF service will have a hard-reference to the BLL, that much I can say with relative certainty. Client-side, the helper class will have a reference to the WCF service interface, which will be implemented by the proxy. That way the WPF client is not affected by internal changes in the BLL, as it should be.

Should the MVC controller have a hard-reference to (its version of) the BLL assembly as well?

Should I use a WCF service for the MVC project, as discussed here (Is this breaking SOA?) or is that overkill? The production server(s) will be the same for both projects.

Should I have the MVC controller reference an interface, instead of the actual BLL assembly? I would still need to instantiate an actual class implementing that interface, of course, so somehow the assembly should be passed to the MVC project... or I could use a WCF service (see above).

Or should I abandon the notion of a common BLL between the projects altogether?

Thanks in advance for any advice.

答:
You can have a common BLL component, exposed as a web service quite happily. Simply expose 2 interfaces on the WCF side of things that are implemented by the same methods in the BLL. Both thick clients and the MVC website will make calls to this common WCF webservice, but each using a different interface.

So you have a Website only web service the web site can call, and another one for the thick clients. Only allow the website devs to access the first service by not giving them the security keys to access it - you'll have some form of security to prevent unauthorised users but you'll also have some for of security to restrict access to rogue applications too.

Title: Advice on architecture (WCF / MVC)


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
Allow to namespace a file from the include call, something like this

```<code>include('mytemplate.php', 'MyNamespace');
</code>```

or

```<code>include 'mytemplate.php' use MyNamespace;
</code>```

And start allowing us to import ("use") namespaces without prefix:

```<code>use OtherNamespace as self;
</code>```

(instead of having to import each individual class in order to use it without a namespace prefix)

ContentLicense: CC BY-SA 2.5

Body:
Allow to namespace a file from the include call, something like this

include('mytemplate.php', 'MyNamespace');

or

include 'mytemplate.php' use MyNamespace;

And start allowing us to import ("use") namespaces without prefix:

use OtherNamespace as self;

(instead of having to import each individual class in order to use it without a namespace prefix)


问:
return a object without returning the reference
i'm having some trouble with returning objects and lists of objects. To problem is I want to return a object in my example an developer but I don't want to give the reference.
What's the best approach for this? First i thought just returning a new Developer:

```<code>public Developer getDeveloper(int index){
    Developer d =  developers.get(index);
    return new Developer(d.getName());
}
</code>```

But this looks good for simple objects but what if i have a developper object that has a instance field that is also a object or a list?

An other question is about lists i return a list of developers:

```<code>public List<Developer> getDeveloppers(){
    return Collections.unmodifiableList(this.developers);
}
</code>```

So the list is now non modifiable but I think the objects are not... how can i return a list with unmodifiable objects?

The example code:

```<code>import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Project {

    private List<Developer> developers;
    private String name;

    public Project(){
        this("DEFAULT");
    }

    public Project(String name){
        this.setName(name);
        this.developers = new ArrayList<Developer>();
    }

    public List<Developer> getDeveloppers(){
        return Collections.unmodifiableList(this.developers);
    }

    public Developer getDeveloper(int index){
        Developer d =  developers.get(index);
        return new Developer(d.getName());
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

The developer class, note this one has no instance object:

```<code>public class Developer {

    private String name;

    public Developer(String name){
        this.name = name;
    }

    public String getName(){
        return this.name;
    }
}
</code>```

Help would be appreciated! Regards

答:
You can make the objects immutable:

```<code>public class Developer {

    private final String name;

    public Developer(String name){
        this.name = name;
    }

    public String getName(){
        return this.name;
    }

}
</code>```

Then there will be no issue with returning the reference.

Otherwise you can map each developer to a unmodifiable view of itself:

```<code>public Stream<IDeveloper> getDeveloppers(){
    return this.developers.map(dev => dev.unmoddifiableView());
}
</code>```

Where unmoddifiableView() returns an instance of IDeveloper that doesn't allow changes:

```<code>private static IDeveloper readOnlyView = new UnmodifiableDeveloper(this);

public IDeveloper unmoddifiableView(){
    return readOnlyView;
}
</code>```

And UnmodifiableDeveloper delegates all getters to the constructor parameter.

ContentLicense: CC BY-SA 3.0

Body:
You can make the objects immutable:

public class Developer {

    private final String name;

    public Developer(String name){
        this.name = name;
    }

    public String getName(){
        return this.name;
    }

}

Then there will be no issue with returning the reference.

Otherwise you can map each developer to a unmodifiable view of itself:

public Stream<IDeveloper> getDeveloppers(){
    return this.developers.map(dev => dev.unmoddifiableView());
}

Where unmoddifiableView() returns an instance of IDeveloper that doesn't allow changes:

private static IDeveloper readOnlyView = new UnmodifiableDeveloper(this);

public IDeveloper unmoddifiableView(){
    return readOnlyView;
}

And UnmodifiableDeveloper delegates all getters to the constructor parameter.


问:
Why does C++ not have a "pure" keyword for virtual functions?
I have always wondered why we code

```<code>virtual void MyFunction() = 0;
</code>```

and not

```<code>pure virtual void MyFunction();
</code>```

Is there a reference for the basis of this decision?

答:
From The Design and Evolution of C++ - Bjarne Stroustrup - Addison-Wesley (ISBN 0-201-54330-3) - chapter 13.2.3:

The curious = 0 syntax was chosen over the obvious alternative of introducing a new keyword pure or abstract because at the time I saw no chance of getting a new keyword accepted. Had I suggested pure, Release 2.0 would have shipped without abstract classes. Given a choice between a nicer syntax and abstract classes, I chose abstract classes. Rather than risking delay and incurring the certain fights over pure, I used the tradition C and C++ convention of using 0 to represent not there.

Anyway looking at the C++ standard (§ 9.2 - Class members) = 0 is called pure-specifier.


问:
Short circuit evaluation, is it bad practice?
Something that I've known for a while but never considered is that in most languages it is possible to give priority to operators in an if statement based on their order. I often use this as a way to prevent null reference exceptions, e.g.:

if (smartphone != null && smartphone.GetSignal() > 50)
{
   // Do stuff
}
```

In this case the code will result in first checking that the object is not null and then using this object knowing that it exists. The language is clever because it knows that if the the first statement if false then there is no point even evaluating the second statement and so a null reference exception is never thrown. This works the same for and and or operators.

This can be useful in other situations too such as checking that an index is in the bounds of an array and such a technique can be performed in various languages, to my knowledge: Java, C#, C++, Python and Matlab.

My question is: Is this sort of code a representation of bad practice? Does this bad practice arise from some hidden technical issue (i.e. this could eventually result in an error) or does it lead to a readability issue for other programmers? Could it be confusing?

答:
No, this is not bad practice.  Relying on short-circuiting of conditionals is a widely accepted, useful technique--as long as you are using a language that guarantees this behavior (which includes the vast majority of modern languages).

Your code example is quite clear and, indeed, that is often the best way to write it. Alternatives (such as nested if statements) would be messier, more complicated, and therefore harder to understand.

A couple of caveats:

Use common sense regarding complexity and readability

The following is not such a good idea:

if ((text_string != null && replace(text_string,"$")) || (text_string = get_new_string()) != null)
```

Like many "clever" ways of reducing the lines in your code, over-reliance on this technique can result in hard-to-understand, error-prone code.

If you need to handle errors, there is often a better way

Your example is fine as long as it is a normal program state for smartphone to be null.  If, however, this is an error, you should incorporate smarter error handling.

Avoid repeated checks of the same condition

As Neil points out, many repeated checks of the same variable in different conditionals are most likely evidence of a design flaw.  If you have ten different statements sprinkled through your code that should not be run if smartphone is null, consider whether there is a better way to handle this than checking the variable each time.

This isn't really about short-circuiting specifically; it's a more general problem of repetitive code.  However, it is worth mentioning, because it is quite common to see code that has many repeated statements like your example statement.

ContentLicense: CC BY-SA 4.0

Body:
No, this is not bad practice.  Relying on short-circuiting of conditionals is a widely accepted, useful technique--as long as you are using a language that guarantees this behavior (which includes the vast majority of modern languages).

Your code example is quite clear and, indeed, that is often the best way to write it. Alternatives (such as nested if statements) would be messier, more complicated, and therefore harder to understand.

A couple of caveats:

Use common sense regarding complexity and readability

The following is not such a good idea:

if ((text_string != null && replace(text_string,"$")) || (text_string = get_new_string()) != null)

Like many "clever" ways of reducing the lines in your code, over-reliance on this technique can result in hard-to-understand, error-prone code.

If you need to handle errors, there is often a better way

Your example is fine as long as it is a normal program state for smartphone to be null.  If, however, this is an error, you should incorporate smarter error handling.

Avoid repeated checks of the same condition

As Neil points out, many repeated checks of the same variable in different conditionals are most likely evidence of a design flaw.  If you have ten different statements sprinkled through your code that should not be run if smartphone is null, consider whether there is a better way to handle this than checking the variable each time.

This isn't really about short-circuiting specifically; it's a more general problem of repetitive code.  However, it is worth mentioning, because it is quite common to see code that has many repeated statements like your example statement.


问:
Can *any* program task be expressed without state?
This is a theoretical question, but after many years of programming in what I now realize is "normal" imperative technique, using C++ mainly, I've discovered this other world of functional programming, which I stumbled upon accidentally while casually learning JavaScript.

This has led me to wonder if you could technically replace any complete state-oriented program with a different implementation that is purely functional and without state?

It's an intriguing idea and I must admit that there is a clarity and elegance in functional programming that has really blown my mind.

答:
State means the ability to respond to a present stimulus in an manner that depends on past stimuli, not just based on the present stimulus.

Purely functional programs are just functions. Thus for practical applications the purely functional program inputs a pair (old_state * present_stimulus) and outputs a pair (new_state * present_response). An external, stateful "looper" is needed to wait for the next stimulus and propagate the state.

A purely functional program doesn't intrinsically have state, and -can't- be used for practical applications directly.

Thus no state-oriented program can be replaced with a different implementation that is purely functional and without state.


问:
Spartan programming... What is it good for?
We are being forced to use Spartan programming on a project, to everybody's dismay. So I get it, it makes the methods really short and it handles the simple cases first. But is it really worth the price of the code looking like something out of the Obfuscated C Code contest? </p>

<p>Can you see it being useful for something? </p>

答:
Many of the tenants of Spartan programming just seem like good practise to me. For example, keeping methods short, minimizing the scope of variables, minimizing the number of parameters to a method, or methods to a class, etc. These are all good things and exactly what you should be striving for.

But then there's stuff like minimizing character count, minimizing token counts, ternarization (seriously?), etc which really make no sense.

I think my main problem with it is exemplified by this quote:

But, spartan programming is more than just a technical coding style, in that is has a single underlying, unifying principle---minimalism and simplicity taken to extremes.

Anything "taken to extremes" rings alarm bells to me.


答:
There are plenty of situations where I want to check one condition first, and only want to check a second condition if the first condition succeeded. Sometimes purely for efficiency (because there is no point checking the second condition if the first already failed), sometimes because otherwise my program would crash (your check for NULL first), sometimes because otherwise the results would be awful. (IF (I want to print a document) AND (printing a document failed)) THEN display an error message - you don't want to print the document and check whether printing failed if you didn't want to print a document in the first place!

So there was a HUGE need for guaranteed short circuit evaluation of logical expressions. It wasn't present in Pascal (which had non-guaranteed short circuit evaluation) which was a major pain; I have first seen it in Ada and C.

If you really think this is "bad practice", then please take any moderately complex bit of code, rewrite it so that it will work fine without short circuit evaluation, and come back and tell us how you liked it. This is like being told that breathing produces carbon dioxide and asking if breathing is a bad practice. Try without it for a few minutes.

Title: Short circuit evaluation, is it bad practice?

Body:
Something that I've known for a while but never considered is that in most languages it is possible to give priority to operators in an if statement based on their order. I often use this as a way to prevent null reference exceptions, e.g.:

if (smartphone != null && smartphone.GetSignal() > 50)
{
   // Do stuff
}
```

In this case the code will result in first checking that the object is not null and then using this object knowing that it exists. The language is clever because it knows that if the the first statement if false then there is no point even evaluating the second statement and so a null reference exception is never thrown. This works the same for and and or operators.

This can be useful in other situations too such as checking that an index is in the bounds of an array and such a technique can be performed in various languages, to my knowledge: Java, C#, C++, Python and Matlab.

My question is: Is this sort of code a representation of bad practice? Does this bad practice arise from some hidden technical issue (i.e. this could eventually result in an error) or does it lead to a readability issue for other programmers? Could it be confusing?


答:
You can avoid explicit mutable state as long as you don't have to interact with the outside world.

In JavaScript in order for you program to actually have an effect beyond taking up processor cycles, you have to modify the Dom or the Window object, and these API's are stateful. But I suppose you could create a wrapper which passed the Dom and Window objects as parameters to the JavaScript code, and then received a new Dom/Window as output. This would isolate the JavaScript code from mutable state.

Of course you are still relying on state, since the browser window and DOM is stateful by nature. Any interactive application is inherently stateful, but you can still structure your code in such away as to minimize explicit state.

A different question is if it is a good idea. Even Haskell, which is a pure functional language by design,  includes the 'state' monad, which allows you to simulate mutable state. This shows that explicit mutable state sometimes really is a desirable pattern.

Title: Can *any* program task be expressed without state?

Body:
This is a theoretical question, but after many years of programming in what I now realize is "normal" imperative technique, using C++ mainly, I've discovered this other world of functional programming, which I stumbled upon accidentally while casually learning JavaScript.

This has led me to wonder if you could technically replace any complete state-oriented program with a different implementation that is purely functional and without state?

It's an intriguing idea and I must admit that there is a clarity and elegance in functional programming that has really blown my mind.


答:
Think about how you would implement a "state machine" in a programming language without state.

You could probably actually do it but you would end up using function names as storage.
Ending up with gobblyday gook like:

```<code>if (sm.atBegining()) sm.start() else if (sm.done()) sm.stop() ) else sm.progress()
</code>```

Body:
Think about how you would implement a "state machine" in a programming language without state.

You could probably actually do it but you would end up using function names as storage.
Ending up with gobblyday gook like:

if (sm.atBegining()) sm.start() else if (sm.done()) sm.stop() ) else sm.progress()


答:
This is an accentuation Compactness of the Cs.

Correctness

Completeness

Compactness

No one cares about your code if it isn't correct.

If your code isn't complete (handles every case), then there are bugs.

If it isn't compact than you are wasting memory or clock cycles ( compiler optimizations aside )

Note the order here is paramount. The most Compact program is rarely correct. E.G.

```<code>void main() {
 return 1;
}
</code>```

Title: Spartan programming... What is it good for?

Body:
We are being forced to use Spartan programming on a project, to everybody's dismay. So I get it, it makes the methods really short and it handles the simple cases first. But is it really worth the price of the code looking like something out of the Obfuscated C Code contest? </p>

<p>Can you see it being useful for something? </p>

Body:
This is an accentuation Compactness of the Cs.

Correctness

Completeness

Compactness

No one cares about your code if it isn't correct.

If your code isn't complete (handles every case), then there are bugs.

If it isn't compact than you are wasting memory or clock cycles ( compiler optimizations aside )

Note the order here is paramount. The most Compact program is rarely correct. E.G.

void main() {
 return 1;
}


问:
Quit a program in main or in function?
Lets say I have a void method/function to check the arguments of the program:

```<code>void check(int argc, String argv){
    //some irrelevant code
}
</code>```

In this function I have some checks to validate the correctness of the arguments. For example if there are too much or if they're not recognized.

Should I just quit the program in this function as in example 1, or should I give it a return value and quit it in main()?

Example 1

```<code>void check(int argc, String argv){
    if(argc > 4){
        print("Too many arguments!");
        exit(-1);
    }
    //code
}
</code>```

Example 2

```<code>int check(int argc, String argv){
    if(argc > 4){
        print("Too many arguments!");
        return -1;
    }
    //code
}

int main(int argc, String argv){
    if(check(argc, argv) == -1){
        return -1;
    }
}
</code>```

答:
Leave it to your main function to quit the program. Your check function's sole purpose should be to check parameters and return a valid / invalid state. IMHO it shouldn't even be responsible of printing the end user message.

The least responsibility you give to a method, the easier it will be to read, reuse, document and test.

Title: Quit a program in main or in function?


答: In my opinion only the main() function should be responsible for stopping the program. Having a separate function to check the validity of the arguments makes this part easier to test. And think about what happens if your program expands; if you suddenly had half a dozen methods that could potentially cause the program to exit then I think you would run into problems.</p>

Title: Quit a program in main or in function?

Body:
Lets say I have a void method/function to check the arguments of the program:

```<code>void check(int argc, String argv){
    //some irrelevant code
}
</code>```

In this function I have some checks to validate the correctness of the arguments. For example if there are too much or if they're not recognized.

Should I just quit the program in this function as in example 1, or should I give it a return value and quit it in main()?

Example 1

```<code>void check(int argc, String argv){
    if(argc > 4){
        print("Too many arguments!");
        exit(-1);
    }
    //code
}
</code>```

Example 2

```<code>int check(int argc, String argv){
    if(argc > 4){
        print("Too many arguments!");
        return -1;
    }
    //code
}

int main(int argc, String argv){
    if(check(argc, argv) == -1){
        return -1;
    }
}
</code>```


答:
Do 1 thing at a time in your functions, that way you can document and reuse them.

So if your check function simply checks a value and returns a boolean, you can reuse it anywhere you have similar requirements.

If it exits, then it is only valuable in this 1 program.

As a best practice, exiting within functions is not a good thing to do, there are cases where you will do this (generally on unrecoverable error) but unless there is an absolute, obvious need to do so, keep exiting only at the end of main().

Title: Quit a program in main or in function?


答:
I'm hesitant to terminate operation in a method other than the main method, simply because it makes it harder to reuse the operation without modification, either in your application or in another application. I would prefer returning an error condition from the method that can be checked by the caller or throwing an exception or whatever similar mechanisms your language or style guide calls for.

One exception could be helper functions for your main method. For example, if you've encapsulated your main routine by itself in a single file and have methods that exist only to initialize and launch your application, then I would consider it acceptable to exit from these methods if execution cannot proceed.

Title: Quit a program in main or in function?


问:
How do workflow tools (jBPM) keep transactional state consistent?
I'm looking at jBPM specifically, but I think this applies with other systems too.

As I understand it..

When placing an item into a workflow, one does not generally put a reference to that item, one puts the whole serialized item or document into the workflow. This means that the state of the workflow and the item undergoing workflow can all be kept in the workflow systems database, making it easy to make atomic updates.

At the end of a workflow, or sometimes in explicit steps along the way, calls can be made to downstream services, and these may make changes to the state of their databases. How does one handle this?

Is it:

The workflow and services should all be deployed in a single application server container, and a transaction manager used to keep everything consistent?

You call a service, then the workflow state is updated, but not in a transaction. Failure and restart of the workflow may cause duplicate calls to be made, if the state update failed.

You decouple them using a transactional JMS queue. Then downstream systems can read from that queue in their own transaction. Updates happen transactionally and in the correct order.

Or something else, or whatever combination of the above that you like.

I should add, where I work we have micro-services (whatever that means). It means we do not have an application server, so global transactions accross service end-points are not possible (no ws-tx either, the services are REST/json). Is the JMS solution the only one that is open to us?

答:
Not being a Java guy my answer may be disappointing.

"When placing an item into a workflow, one does not generally put a reference to that item, one puts the whole serialized item or document into the workflow"

I think the word "generally" is key here. The decision about placing the a reference or the whole item should be case by case. If the object is constant across workflow instances and the workflow needs to know when it changes,  do not place it on the workflow. Use a reference instead. It's easier than creating a mechanism to notify instances abut the change. Registry data is my prime example.

How you update the database from the workflow instance is also a case by case decision. Some updates should be atomic (the workflows should not be allowed to continue to order fulfillment if the database transaction updating the client balance fails).Even if not in a transaction the workflow can be modeled around it.

Other times the workflow can continue even if database fails to update with just a warning to the user("We were unable to update your address in our registry at this time, but your order will be delivered to the new address" ). You can also queue the update.

So, use transactions when you must, fail gracefully when you need to and queue things that are not time sensitive.

No silver bullet. Sorry.


问:
Using ESB for database synchronisation / replication
We're starting to look at implementing an ESB / Microservices architecture. I (think) I know about the concepts, but there's one thing I don't seem to be able to get a good idea about: data replication / synchronisation.

Creating an event for each and every table (maybe even multiple (create,update,delete)) seems like overkill to me, if it's just to synchronize data. Wouldn't an ETL / SQL Replication solution be much easier, in cases where no business logic will be exectute, as it's just to update the local cache/db of the server?

What strategies would you advise?

Simple example, we have an application that manages all product data, we want to build an API (Web Service) that is going to serve a Mobile App that will display that data.

There are several options:

API directly accesses the database

API has a local database that's being kept up to date using ESB messages

API has a local database that's being kept up to date using some replication tool

API has a local database that's updated once a day using a batch operation.

In my opinion the reason to use messages would be to further uncouple the systems as the database structure behind it can be changed without affecting the system in that scenario. For all other means and purposes 3/4 seem much let complex, which in my opionion meets the KISS principle.

What would you advice? Where can I get some sort of flowchart/decision tree example on what alternative to use when?

答:
You need to look at what the root problem is.

Are you seeking data redundancy?

Are you seeking minimal data access times?

Are you seeking sharing data across separate environments?

Are you seeking to minimize security vulnerabilities with access to the data?

Once you decide what the highest priority is, then you can work on finding the best solution.

For data redundancy and access times the most likely solution is using SQL replication.  The goal of replication (which those products are very good at) is data redundancy & minimizing access times through slave database servers.  This option allows all points to have access to nearly the same data, you just need to monitor replication lag to ensure it stays within business requirements.

For separate environment concerns, I  believe either an ESB or automated batch operation is preferable.  This enables additional manipulation to occur before/during the operations to ensure any variances between servers can be resolved at data import time.

To minimize security vulnerabilities I would recommend a non-automated batch operation that has an appropriate level of security checks to ensure data validity.  By not automating this operation it allows a human to confirm that there are no outstanding issues that may cause data corruption.

For any decision, big or small, you need to do a cost-benefit analysis before implementing any changes.  You need to take into consideration:

Development time

Development cost

Future use of the solution

Expected performance

Complexity of the solution

Maintainability of the solution


答:
There's no direct way to do what you're describing. However, you have a few options which will hopefully achieve what you want:

Have an interface which contains only the accessors, and not the mutators, and make sure your return type is of the interface rather than the concrete class.

Have a way of cloning a class- this might be an external method, or a .clone() method on the class. This should return a new instance of the class, but the state representing the same information (e.g. the name would be the same). Then instead of returning the original class, return a copy. These will still be mutable, but changes to these instances won't affect the originals.

Have a second class which represents an immutable "view" on the first class. This is what ratchet freak describes in his answer. Again, you will need some method which can create an instance of the view from an instance of the original class.

Design your classes so that you don't need to do this.

Assuming these are classes you control, 4 is my overwhelming favorite option, and should definitely be your first aim until you have a good reason to rule it out. Some reasons:

1,2, and 3 all require annoying additions to your code (interfaces or methods). Especially with 2 and 3, if this is something that you do a lot throughout your code, you're creating significant maintenance work for yourself.

A class should be responsible for its own encapsulation. You're turning this idea on its head by making the class open, and having it depend on the kindness of strangers to find ways to pass it around which will give it some protection. Now instead of having this responsibility centralized in one place which will always take care of itself, every time you use this class in a different place, you as a developer have to remember these extra rules about how to use and pass it around.

One really useful aspect about encapsulation is that it allows a class to make assumptions about its state, as long as it also takes responsibility for keeping these assumptions true. An example might be a Fraction class. If this class manages its own encapsulated state and keeps itself in a reduced form, then its equals method can look like:

```<code>equals(Object obj) {
    return obj.numerator = numerator  && obj.denominator = denominator;
}
</code>```

If numerator and denominator weren't encapsulated though, it couldn't be sure that it was in a reduced form any more and would have to use more complex logic to ensure that, for example 1/2 and 2/4 compared as equal. This is called a class invariant. Just hoping that every time you use your class you'll remember to protect its invariants is a sure route to bugs and probably to horribly coupled code. This is another facet of the previous bullet point- you're turning the responsibility of encapsulation inside out if you rely on every class which uses this one to remember to call .clone() or whatever.

If you do find yourself in a situation where you have to do this (or the costs of not doing it are too high), then all other things being equal I'd recommend option 1, as it's a relatively natural use of interfaces.

Title: return a object without returning the reference

Body:
i'm having some trouble with returning objects and lists of objects. To problem is I want to return a object in my example an developer but I don't want to give the reference.
What's the best approach for this? First i thought just returning a new Developer:

```<code>public Developer getDeveloper(int index){
    Developer d =  developers.get(index);
    return new Developer(d.getName());
}
</code>```

But this looks good for simple objects but what if i have a developper object that has a instance field that is also a object or a list?

An other question is about lists i return a list of developers:

```<code>public List<Developer> getDeveloppers(){
    return Collections.unmodifiableList(this.developers);
}
</code>```

So the list is now non modifiable but I think the objects are not... how can i return a list with unmodifiable objects?

The example code:

```<code>import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Project {

    private List<Developer> developers;
    private String name;

    public Project(){
        this("DEFAULT");
    }

    public Project(String name){
        this.setName(name);
        this.developers = new ArrayList<Developer>();
    }

    public List<Developer> getDeveloppers(){
        return Collections.unmodifiableList(this.developers);
    }

    public Developer getDeveloper(int index){
        Developer d =  developers.get(index);
        return new Developer(d.getName());
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

The developer class, note this one has no instance object:

```<code>public class Developer {

    private String name;

    public Developer(String name){
        this.name = name;
    }

    public String getName(){
        return this.name;
    }
}
</code>```

Help would be appreciated! Regards

Body:
There's no direct way to do what you're describing. However, you have a few options which will hopefully achieve what you want:

Have an interface which contains only the accessors, and not the mutators, and make sure your return type is of the interface rather than the concrete class.

Have a way of cloning a class- this might be an external method, or a .clone() method on the class. This should return a new instance of the class, but the state representing the same information (e.g. the name would be the same). Then instead of returning the original class, return a copy. These will still be mutable, but changes to these instances won't affect the originals.

Have a second class which represents an immutable "view" on the first class. This is what ratchet freak describes in his answer. Again, you will need some method which can create an instance of the view from an instance of the original class.

Design your classes so that you don't need to do this.

Assuming these are classes you control, 4 is my overwhelming favorite option, and should definitely be your first aim until you have a good reason to rule it out. Some reasons:

1,2, and 3 all require annoying additions to your code (interfaces or methods). Especially with 2 and 3, if this is something that you do a lot throughout your code, you're creating significant maintenance work for yourself.

A class should be responsible for its own encapsulation. You're turning this idea on its head by making the class open, and having it depend on the kindness of strangers to find ways to pass it around which will give it some protection. Now instead of having this responsibility centralized in one place which will always take care of itself, every time you use this class in a different place, you as a developer have to remember these extra rules about how to use and pass it around.

One really useful aspect about encapsulation is that it allows a class to make assumptions about its state, as long as it also takes responsibility for keeping these assumptions true. An example might be a Fraction class. If this class manages its own encapsulated state and keeps itself in a reduced form, then its equals method can look like:

equals(Object obj) {
    return obj.numerator = numerator  && obj.denominator = denominator;
}

If numerator and denominator weren't encapsulated though, it couldn't be sure that it was in a reduced form any more and would have to use more complex logic to ensure that, for example 1/2 and 2/4 compared as equal. This is called a class invariant. Just hoping that every time you use your class you'll remember to protect its invariants is a sure route to bugs and probably to horribly coupled code. This is another facet of the previous bullet point- you're turning the responsibility of encapsulation inside out if you rely on every class which uses this one to remember to call .clone() or whatever.

If you do find yourself in a situation where you have to do this (or the costs of not doing it are too high), then all other things being equal I'd recommend option 1, as it's a relatively natural use of interfaces.


答:
Now that looked disturbingly familiar. Even the minimizing on the tokens, although not taken to the extremes. I rather use fname than filename for example, out for output, x for the data input, n for counts, l for lengths and so on. lx would be length of x, ly length of y,... you get the drift.

Plus, as I often manipulate large datasets in scientific applications, I use the index facilities in R a lot. When I write out all those indices, the code hurts my eyes. So index becomes id, or even just i.

Even more, the specific loop structures in R (the apply family) often demands of function declaration within the apply call. In those cases I always use x,y,z,... These functions are often one or two lines, so it's clear where it's coming from, and it doesn't clutter the screen.

It's not a bad thing, as long as you have some naming conventions that are coherent through the complete code, and you supply comments to explain the more obscure variable names. In the end, it makes code more readible to me than a long train of camels hobbling over the screen.


问:
Where should my team start with becoming "modern"?
I'm a relatively new developer, fresh from college. While in college and during subsequent job-seeking, I realized that there were a lot of "modern" software development methodologies that my education was lacking: unit testing, logging, database normalization, agile development (vs. generic agile concepts), coding style guides, refactoring, code reviews,  no standardized documentation methods (or even requirements), etc.

Overall, I didn't see this is a problem. I expected my first job to embrace all of these ideas and to teach them to me on the job. Then I got my first job (full stack web development) at a big corporation and I realized that we do none of these things. In fact I, the least experienced on the team, am the one who is spearheading attempts to bring my team up to speed with "modern" programming techniques - as I worry that not doing so is professional suicide down the road.

First I began with logging software (log4J), but then I quickly moved on to writing my own styleguide, then abandoning it for the Google styleguide - and then I realized that our Java web development used hand-written front controllers, so I pushed for our adoption of Spring - but then I realized we had no unit tests, either, but I was already learning Spring... and as you can see, it becomes overwhelming all too quickly, especially when paired with normal development work. Furthermore, it is difficult for me to become "expert" enough in these methodologies to teach anyone else in them without devoting too much time to a single one of them, let alone them all.

Of all these techniques, which I see as "expected" in today's software development world, how do I integrate them into a team as a new player without overwhelming both myself and the team?

How can I influence my team to become more agile? is related, but I'm not an Agile developer like the asker here, and I'm looking at a much broader set of methodologies than Agile.

答:
Find a flaw. Fix a flaw. Show the fix.

Let's take normalisation* first. And indeed, I'd suggest you take it first, because lack of normalisation is likely to result in actual buggy data that couldn't exist otherwise, whereas the rest are cases where best-practice could likely help but it's harder to say "Bug A was caused by not following policy X". If you have a database that isn't normalised, then you have a place where data can be inconsistent.

It's a good bet that you will be able to find an actual case of inconsistent data. You have now found two things:

A bug in your data.

A bug in your database schemata.

You actually knew about the second bug first, but the first one is more easily demonstrable and also something that is causing a real problem, not something that theoretically could.

Unfortunately one of the real reasons for resisting normalising denormalised database is that the question of what to do with such buggy data is not always easy, but you will have found an actual bug.

(Do be aware though that there are reasons why one might sometimes denormalise some data on purpose. Don't mistake knowledgeable breaking of the rule for ignorance of the rule; if you normalise a table that is deliberately denormalised for speed of lookup, you won't win any kudos. Even here though, denormalising being fraught is something that should be done procedurally, so if the denormalised table isn't created automatically based on the contents of normalised tables there is still progress to make).

For the rest, introduce them when they help in the short-term, to later build on them in the long term. E.g. if you are given a small piece of code to build, write a unit test for it. Better still, if you are given a bug to fix, write a unit test that fails because of the bug and then when you have fixed the bug mention the fact that it passes when you close off the bugs (or send an email saying it's fixed, or whatever).

*Incidentally, not very modern. The reason it is called normalization and not normalizing or something else, is that at the time it was a topical joke to stick -ization on the end of things to make fun of the name of Richard Nixon's Vietnamization policy.


问:
How to separate sensitive data in database(MySql)
I need to design a database that will contains information about personal disease of users.

What can be the approach in order to implement the columns of the DB's tables: encrypt the information, separate data within two differents DB, one for sensitive data and another for not sensitive data, or both or another approach?

答:
Ominus' answer addresses your first question. The answer to the second question may require more details about your application.

Another approach with even greater security if the patients must access the database could be to have a separate database for each user. In this approach you might use a framework that provides multi-tenant, multi-database functionality. The problem however is that if you have separate application users and separate database users, synchronizing these users will be incredibly difficult.
I would guess that patients don't need to access your database though. If they do need to, it might be most secure to have a key per user.

In addition to legal or contractual requirements, some other reasons I can think of to have separate databases are: customer's perception of increased security making sales easier, worries about encryption being broken, and worries about (the) key(s) being compromised.

Regarding the part of Briddmus' answer where he states "that you need to encrypt more than just the medical information": this only holds if everyone in the database has a medical condition. (I would guess this is the case).

Note: parts of this answer would be better suited as comments but I don't yet have sufficient rep to post comments here.


答:
Let's say you were using a C-style language with no && and needed to do the equivalent code as in your question.

Your code would be:

if(smartphone != null)
{
  if(smartphone.GetSignal() > 50)
  {
    // Do stuff
  }
}
```

<p>This pattern would turn up a lot.</p>

<p>Now imagine version 2.0 of our hypothetical language introduces <code>&&</code>. Think how cool you'd think it was!</p>

<p><code>&&</code> is the recognised, idiomatic means of doing what my example above does. It's not bad practice to use it, indeed it's bad practice not to use it in cases like the above: An experienced coder in such a language would be wondering where the <code>else</code> was or other reason for not doing things in the normal fashion.</p>

<blockquote>
  <p>The language is clever because it knows that if the the first statement if false then there is no point even evaluating the second statement and so a null reference exception is never thrown.</p>
</blockquote>

<p>No, <strong>you</strong> are clever, because you knew that if the first statement was false then there is no point even evaluating the second statement. The language is dumb as a box of rocks and did what you told it to do. (John McCarthy was even more clever, and realised that short-circuit evaluation would be a useful thing for languages to have).</p>

<p>The difference between you being clever and the language being clever is important, because good and bad practice often come down to you being as clever as necessary, but no more clever.</p>

<p>Consider:</p>

<pre class="lang-cs prettyprint-override"><code>if(smartphone != null && smartphone.GetSignal() > ((range = (range != null ? range : GetRange()) != null && range.Valid ? range.MinSignal : 50)
</code>```

This extends your code to check a range. If the range is null then it tries to set it by a call to GetRange() though that might fail so range might still be null. If range is not null after this, and it is Valid then its MinSignal property is used, otherwise a default of 50 is used.

This depends upon && too, but putting it in one line is probably too clever (I'm not 100% sure I have it right, and I'm not going to double-check because that fact demonstrates my point).

It's not && that is the problem here though, but the ability to use it to put a lot in one expression (a good thing) increases our ability to write hard-to-understand expressions unnecessarily (a bad thing).

Also:

if(smartphone != null && (smartphone.GetSignal() == 2 || smartphone.GetSignal() == 5 || smartphone.GetSignal() == 8 || smartPhone.GetSignal() == 34))
{
  // do something
}
```

<p>Here I'm combining the use of <code>&&</code> with a check for certain values. This isn't realistic in the case of phone signals, but does come up in other cases. Here, it's an example of my not being clever enough. If I'd done the following:</p>

<pre class="lang-cs prettyprint-override"><code>if(smartphone != null)
{
  switch (smartphone.GetSignal())
  {
    case 2: case 5: case 8: case 34:
      // Do something
      break;
  }
}
</code>```

I'd have gained in both readability and also likely in performance (the multiple calls to GetSignal() would likely not have been optimised away).

Here again the problem isn't so much && as taking that particular hammer and seeing everything else as a nail; not using it let me do something better than using it does.

A final case that moves away from best practice is:

if(a && b)
{
  //do something
}
```

<p>Compared to:</p>

<pre class="lang-cs prettyprint-override"><code>if(a & b)
{
  //do something
}
</code>```

The classic argument as to why we might favour the latter is that there is some side-effect in assessing b that we want whether a is true or not. I disagree on that: If that side-effect is so important, then make it happen in a separate line of code.

However, in terms of efficiency either of the two are likely to be better. The first will obviously execute less code (not assessing b at all in one code path) which can save us whatever amount of time it takes to assess b.

The first though also has one more branch. Consider if we re-write it in our hypothetical C-style language with no &&:

if(a)
{
  if(b)
  {
    // Do something
  }
}
```

That extra if is hidden in our use of &&, but it is still there. And as such it's a case where there is branch prediction happening and potentially therefore branch mis-prediction.

For that reason the if(a & b) code can be more efficient in some cases.

Here I'd say that if(a && b) is still the best practice approach to start with: More common, the only one viable in some cases (where b will error if a is false) and faster more often than not. It's worth noting that if(a & b) is often a useful optimisation on it in certain cases though.

Body:
Let's say you were using a C-style language with no && and needed to do the equivalent code as in your question.

Your code would be:

if(smartphone != null)
{
  if(smartphone.GetSignal() > 50)
  {
    // Do stuff
  }
}

This pattern would turn up a lot.

Now imagine version 2.0 of our hypothetical language introduces &&. Think how cool you'd think it was!

&& is the recognised, idiomatic means of doing what my example above does. It's not bad practice to use it, indeed it's bad practice not to use it in cases like the above: An experienced coder in such a language would be wondering where the else was or other reason for not doing things in the normal fashion.

The language is clever because it knows that if the the first statement if false then there is no point even evaluating the second statement and so a null reference exception is never thrown.

No, you are clever, because you knew that if the first statement was false then there is no point even evaluating the second statement. The language is dumb as a box of rocks and did what you told it to do. (John McCarthy was even more clever, and realised that short-circuit evaluation would be a useful thing for languages to have).

The difference between you being clever and the language being clever is important, because good and bad practice often come down to you being as clever as necessary, but no more clever.

Consider:

if(smartphone != null && smartphone.GetSignal() > ((range = (range != null ? range : GetRange()) != null && range.Valid ? range.MinSignal : 50)

This extends your code to check a range. If the range is null then it tries to set it by a call to GetRange() though that might fail so range might still be null. If range is not null after this, and it is Valid then its MinSignal property is used, otherwise a default of 50 is used.

This depends upon && too, but putting it in one line is probably too clever (I'm not 100% sure I have it right, and I'm not going to double-check because that fact demonstrates my point).

It's not && that is the problem here though, but the ability to use it to put a lot in one expression (a good thing) increases our ability to write hard-to-understand expressions unnecessarily (a bad thing).

Also:

if(smartphone != null && (smartphone.GetSignal() == 2 || smartphone.GetSignal() == 5 || smartphone.GetSignal() == 8 || smartPhone.GetSignal() == 34))
{
  // do something
}

Here I'm combining the use of && with a check for certain values. This isn't realistic in the case of phone signals, but does come up in other cases. Here, it's an example of my not being clever enough. If I'd done the following:

if(smartphone != null)
{
  switch (smartphone.GetSignal())
  {
    case 2: case 5: case 8: case 34:
      // Do something
      break;
  }
}

I'd have gained in both readability and also likely in performance (the multiple calls to GetSignal() would likely not have been optimised away).

Here again the problem isn't so much && as taking that particular hammer and seeing everything else as a nail; not using it let me do something better than using it does.

A final case that moves away from best practice is:

if(a && b)
{
  //do something
}

Compared to:

if(a & b)
{
  //do something
}

The classic argument as to why we might favour the latter is that there is some side-effect in assessing b that we want whether a is true or not. I disagree on that: If that side-effect is so important, then make it happen in a separate line of code.

However, in terms of efficiency either of the two are likely to be better. The first will obviously execute less code (not assessing b at all in one code path) which can save us whatever amount of time it takes to assess b.

The first though also has one more branch. Consider if we re-write it in our hypothetical C-style language with no &&:

if(a)
{
  if(b)
  {
    // Do something
  }
}

That extra if is hidden in our use of &&, but it is still there. And as such it's a case where there is branch prediction happening and potentially therefore branch mis-prediction.

For that reason the if(a & b) code can be more efficient in some cases.

Here I'd say that if(a && b) is still the best practice approach to start with: More common, the only one viable in some cases (where b will error if a is false) and faster more often than not. It's worth noting that if(a & b) is often a useful optimisation on it in certain cases though.


答:
I'm going to be unpopular and say Yes, it is bad practice. IF the functionality of your code is relying on it to implement conditional logic.

ie

 if(quickLogicA && slowLogicB) {doSomething();}
```

<p>is good, but</p>

<pre class="lang-cs prettyprint-override"><code>if(logicA && doSomething()) {andAlsoDoSomethingElse();}
</code>```

is bad, and surely no-one would agree with?!

if(doSomething() || somethingElseIfItFailed() && anotherThingIfEitherWorked() & andAlwaysThisThing())
{/* do nothing */}
```

<p>Reasoning : </p>

<p>Your code errors if both sides are evaluated rather than simply not performing the logic. It has been argued that this is not a problem, the 'and' operator is defined in c# so the meaning is clear. However, I contend that this is not true.</p>

<p><strong>Reason 1. Historical</strong></p>

<p>Essentially you are relying on (what was originally intended as) a compiler optimization to provide functionality in your code. </p>

<p>Although in c# the language specification guarantees the boolean 'and' operator does short circuiting. This is not true of all languages and compilers.</p>

<p>wikipeda lists various languages and their take on short circuiting http://en.wikipedia.org/wiki/Short-circuit_evaluation as you can there are many approaches. And a couple of extra problems I don't go into here.</p>

<p>In particular, FORTRAN, Pascal and Delphi have compiler flags which toggle this behavior.</p>

<p>Therefore : You may find you code works when compiled for release, but not for debug or with an alternate compiler etc. </p>

<p><strong>Reason 2. Language differences</strong></p>

<p>As you can see from wikipedia, not all languages take the same approach to short circuiting, even when they specify how the boolean operators should handle it.</p>

<p>In particular VB.Net's 'and' operator does not short circuit and TSQL has some peculiarities. </p>

<p>Given that a modern 'solution' is likely to include a number of languages, such as javascript, regex, xpath etc you should take this into account when making your code functionality clear.</p>

<p><strong>Reason 3. Differences within a language</strong></p>

<p>For example VB's inline if behaves differently from its if. Again in modern applications  your code may move between, for example code behind and an inline webform, you have to be aware of the differences in meaning.</p>

<p><strong>Reason 4. Your specific example of null checking the parameter of a function</strong></p>

<p>This is a <strong>very</strong> good example. In that it is something everyone does, but is actually bad practice when you think about it.</p>

<p>Its a very common to see this kind of check as it reduces your lines of code considerably. I doubt anyone would bring it up in a code review. (and obviously from the comments and rating you can see it's popular!)</p>

<p>However, it fails best practice for more than one reason!</p>

<ol>
<li><p>Its <strong>very</strong> clear from numerous sources, that best practice is to check your parameters for validity before you use them and to throw an exception if they are invalid. Your code snippet dosn't show the surrounding code, but you should probably be doing something like:</p>

<pre class="lang-cs prettyprint-override"><code>if (smartphone == null)
{
    //throw an exception
}
// perform functionality
</code>```

You are calling a function from within the conditional statement. Although your function's name implies that it simply calculates a value, it can hide side effects. eg

Smartphone.GetSignal() { this.signal++; return this.signal; }

else if (smartphone.GetSignal() < 1)
{
    // Do stuff
}
else if (smartphone.GetSignal() < 2)
{
    // Do stuff
}
```

<p>best practice would suggest:</p>

<pre class="lang-cs prettyprint-override"><code>var s = smartphone.GetSignal();
if(s < 50)
{
    //do something
}
</code>```

If you apply these best practices to your code you can see that your opportunity to achieve shorter code through the use of the hidden conditional disappears. Best practice is to do something, to handle the case where smartphone is null.

I think you will find that this is also the case for other common usages. You have to remember we also have :

inline conditionals

var s = smartphone!=null ? smartphone.GetSignal() : 0;
```

<p>and null coalescence</p>

<pre class="lang-cs prettyprint-override"><code>var s = smartphoneConnectionStatus ?? "No Connection";
</code>```

which provide similar short code length functionality with more clarity

numerous links to support all my points:

https://stackoverflow.com/questions/1158614/what-is-the-best-practice-in-case-one-argument-is-null

Constructor parameter validation in C# - Best practices

Should one check for null if he does not expect null?

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

https://stackoverflow.com/questions/1445867/why-would-a-language-not-use-short-circuit-evaluation

http://orcharddojo.net/orchard-resources/Library/DevelopmentGuidelines/BestPractices/CSharp

examples of compiler flags that affect short circuiting:

Fortran : "sce | nosce By default, the compiler performs short circuit evaluation in selected logical expressions using XL Fortran rules. Specifying sce allows the compiler to use non-XL Fortran rules. The compiler will perform short circuit evaluation if the current rules allow it. The default is nosce."

Pascal : "B - A flag directive that controls short-circuit evaluation. See Order of evaluation of operands of dyadic operators for more information about short-circuit evaluation. See also the -sc compiler option for the command-line compiler for more information (documented in the User's Manual)."

Delphi : "Delphi supports short circuit evaluation by default. It can be turned off using the {$BOOLEVAL OFF} compiler directive."

Body:
I'm going to be unpopular and say Yes, it is bad practice. IF the functionality of your code is relying on it to implement conditional logic.

ie

 if(quickLogicA && slowLogicB) {doSomething();}

is good, but

if(logicA && doSomething()) {andAlsoDoSomethingElse();}

is bad, and surely no-one would agree with?!

if(doSomething() || somethingElseIfItFailed() && anotherThingIfEitherWorked() & andAlwaysThisThing())
{/* do nothing */}

Reasoning :

Your code errors if both sides are evaluated rather than simply not performing the logic. It has been argued that this is not a problem, the 'and' operator is defined in c# so the meaning is clear. However, I contend that this is not true.

Reason 1. Historical

Essentially you are relying on (what was originally intended as) a compiler optimization to provide functionality in your code.

Although in c# the language specification guarantees the boolean 'and' operator does short circuiting. This is not true of all languages and compilers.

wikipeda lists various languages and their take on short circuiting http://en.wikipedia.org/wiki/Short-circuit_evaluation as you can there are many approaches. And a couple of extra problems I don't go into here.

In particular, FORTRAN, Pascal and Delphi have compiler flags which toggle this behavior.

Therefore : You may find you code works when compiled for release, but not for debug or with an alternate compiler etc.

Reason 2. Language differences

As you can see from wikipedia, not all languages take the same approach to short circuiting, even when they specify how the boolean operators should handle it.

In particular VB.Net's 'and' operator does not short circuit and TSQL has some peculiarities.

Given that a modern 'solution' is likely to include a number of languages, such as javascript, regex, xpath etc you should take this into account when making your code functionality clear.

Reason 3. Differences within a language

For example VB's inline if behaves differently from its if. Again in modern applications  your code may move between, for example code behind and an inline webform, you have to be aware of the differences in meaning.

Reason 4. Your specific example of null checking the parameter of a function

This is a very good example. In that it is something everyone does, but is actually bad practice when you think about it.

Its a very common to see this kind of check as it reduces your lines of code considerably. I doubt anyone would bring it up in a code review. (and obviously from the comments and rating you can see it's popular!)

However, it fails best practice for more than one reason!

Its very clear from numerous sources, that best practice is to check your parameters for validity before you use them and to throw an exception if they are invalid. Your code snippet dosn't show the surrounding code, but you should probably be doing something like:

if (smartphone == null)
{
    //throw an exception
}
// perform functionality

You are calling a function from within the conditional statement. Although your function's name implies that it simply calculates a value, it can hide side effects. eg

Smartphone.GetSignal() { this.signal++; return this.signal; }

else if (smartphone.GetSignal() < 1)
{
    // Do stuff
}
else if (smartphone.GetSignal() < 2)
{
    // Do stuff
}

best practice would suggest:

var s = smartphone.GetSignal();
if(s < 50)
{
    //do something
}

If you apply these best practices to your code you can see that your opportunity to achieve shorter code through the use of the hidden conditional disappears. Best practice is to do something, to handle the case where smartphone is null.

I think you will find that this is also the case for other common usages. You have to remember we also have :

inline conditionals

var s = smartphone!=null ? smartphone.GetSignal() : 0;

and null coalescence

var s = smartphoneConnectionStatus ?? "No Connection";

which provide similar short code length functionality with more clarity

numerous links to support all my points:

https://stackoverflow.com/questions/1158614/what-is-the-best-practice-in-case-one-argument-is-null

Constructor parameter validation in C# - Best practices

Should one check for null if he does not expect null?

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

https://stackoverflow.com/questions/1445867/why-would-a-language-not-use-short-circuit-evaluation

http://orcharddojo.net/orchard-resources/Library/DevelopmentGuidelines/BestPractices/CSharp

examples of compiler flags that affect short circuiting:

Fortran : "sce | nosce By default, the compiler performs short circuit evaluation in selected logical expressions using XL Fortran rules. Specifying sce allows the compiler to use non-XL Fortran rules. The compiler will perform short circuit evaluation if the current rules allow it. The default is nosce."

Pascal : "B - A flag directive that controls short-circuit evaluation. See Order of evaluation of operands of dyadic operators for more information about short-circuit evaluation. See also the -sc compiler option for the command-line compiler for more information (documented in the User's Manual)."

Delphi : "Delphi supports short circuit evaluation by default. It can be turned off using the {$BOOLEVAL OFF} compiler directive."


问:
Concurrency: How do you approach the design and debug the implementation?
I've been developing concurrent systems for several years now, and I have a pretty good grasp on the subject despite my lack of formal training (i.e. no degree).  There's a few new languages that have become popular to at least talk about lately that are designed to make concurrency easier such as Erlang and Go.  It appears that their approach to concurrency echoes my own experience as to how to make systems scalable and take advantage of multiple cores/processors/machines.

However, I find that there are very few tools to help visualize what you intend to do, and verify that you are at least close to your original vision.  Debugging concurrent code can be a nightmare with languages that are not designed for concurrency (like C/C++, C#, Java, etc.).  In particular, it can be near impossible to recreate conditions that happen readily on one system in your development environment.

So, what are your approaches to designing a system to deal with concurrency and parallel processing?  Examples:

How do you figure out what can be made concurrent vs. what has to be sequential?

How do you reproduce error conditions and view what is happening as the application executes?

How do you visualize the interactions between the different concurrent parts of the application?

I have my own answers for some of these, but I'd also like to learn a bit more.

Edit

So far we have a lot of good input.  Many of the articles linked to are very good, and I've already read some of them.

My personal experience with concurrent programming leads me to believe you need a different mindset than you do with sequential programming.  The mental divide is probably as wide as the difference between object oriented programming and procedural programming.  I'd like this set of questions to focus more on the thought processes necessary (i.e. theory) to systematically approach the answers.  When providing more concrete answers, it helps to provide an example--something you went through personally.

Goal for the Bounty

Don't tell me what I should do.  I already have that under control.  Tell me what you do.  Tell me how you solve these problems.

答:
I'll be blunt.  I adore tools.  I use lots of tools.
My first step is to lay out the intended paths for flow of state.  My next step is to try and figure out if it's worth it, or if the required flow of information will render the code serial too often.  Then, I'll try and draft some simple models.  These can range from a stack of crude toothpick sculptures to some simple similar examples in python.  Next, I look through a couple of my favorite books, like the little book of semaphores, and see if someone's already come up with a better solution to my problem.

Then I start coding.

Just kidding.  A bit more research first.  I like to sit down with a fellow hacker, and walk through an expected execution of the program at a high level.  If questions come up, we step to a lower level.  It's important to find out if someone else can understand your solution well enough to maintain it.

Finally, I start coding.  I try to keep it very simple first.  Just the code path, nothing fancy.  Move as little state as possible.  Avoid writes.  Avoid reads that may conflict with writes.  Avoid, above all else, writes that may conflict with writes.  It's very easy to find that you have a positively toxic number of these, and that your beautiful solution is suddenly little more than a cache-thrashing serial approach.

A good rule is to use frameworks where-ever you can.  If you're writing basic threading components yourself, like good synchronized data structures, or god-forbid, actual synchro-primitives, you are almost certainly going to blow your whole leg off.

Finally, tools.  Debugging is very hard.  I use valgrind\callgrind on linux in conjunction with PIN, and parallel studios on windows.  Do not try and debug this stuff by hand.  You probably can.  But you'll probably wish you hadn't.  Ten hours mastering some powerful tools, and some good models will save you hundreds of hours later.

Above all else, work incrementally.  Work carefully.  Do not write concurrent code when tired.  Do not write it while hungry.  In fact, if you can avoid it, simply do not write it.  Concurrency is hard, and I have found that many apps that list it as a feature often ship with it as their only feature.

In summary:

Begin:

Think

Talk

Test

Write simply

Read

Test

Write

Debug

GOTO Begin


答:
You can take this further, and in some languages it's the idiomatic way to do things: you can use short circuit evualuation outside of conditional statements too, and they become a form of conditional statement themselves. E.g. in Perl, it is idiomatic for functions to return something falsy on failure (and something truthy on success), and something like

open($handle, "<", "filename.txt") or die "Couldn't open file!";
```

is idiomatic. open returns something nonzero on success (so that the die part after or never happens), but undefined on failure, and then the call to die does happen (that is Perl's way to raise an exception).

That is fine in languages where everybody does it.

Body:
You can take this further, and in some languages it's the idiomatic way to do things: you can use short circuit evualuation outside of conditional statements too, and they become a form of conditional statement themselves. E.g. in Perl, it is idiomatic for functions to return something falsy on failure (and something truthy on success), and something like

open($handle, "<", "filename.txt") or die "Couldn't open file!";

is idiomatic. open returns something nonzero on success (so that the die part after or never happens), but undefined on failure, and then the call to die does happen (that is Perl's way to raise an exception).

That is fine in languages where everybody does it.


问:
Example of writing unit test for a method
I am writing unit tests for an iOS application. I clearly understand the benefits of writing unit tests & TDD, but I am confused about what kind of tests you can write for methods like this;

```<code>-(void)setCurrentView:(NSString *)view data:(NSString *)data
{
    if (!isEmpty(view)) {
        [Crashlytics setObjectValue:view forKey:kCurrentView];
        if (!isEmpty(data)) {
            [Crashlytics setObjectValue:data forKey:kCurrentViewData];
        }
    }
}
</code>```

It is written in objective C & Crashlytics is a third part API.

We can pass NULL & nil values & test that it doesn't throw any exception

Other than this we can test that the values are set properly (isEqual)

Any other test cases we can use here..

Update
The above method doesn't work as excepted. Calling class method "setObjectValue" is not sending anything to Crashlytics dashboard. I have to call the the instance method in Crashlytics to make it work..

```<code>[[Crashlytics sharedInstance] setObjectValue:view forKey:kCurrentView];
</code>```

答:
The point of unit testing is testing your code's functionality in isolation.  To the extent that your code is simply a wrapper around an external library, it doesn't really have any functionality to unit test.

It may be useful to unit test the NULL and nil values, as you suggest.

However, unit testing the call to the library doesn't seem worthwhile.  Suppose you set up a dummy replacement for the Crashlytics object (I don't know objective C, so I don't know exactly how you would do that).  What would it prove?

That you successfully called the library

That you passed in the data received by the method.

These are fairly trivial, and in any case will be more than adequately covered by integration testing.


答: I'm going to go against the grain and say: find a new job after spending some time at this one to build your resume a little. Aim for a year or so. Although many things are "buzzwords," issues like a complete lack of unit testing are intractable for a single developer, and chances are that if the programmers working there have no desire for testing, you'll never get purchase and may even jeopardize your position at the company by making people think of you as a blowhard. You need to be in a place where you can get mentoring, not trying to push the culture towards basic competence.

Title: Where should my team start with becoming "modern"?

Body:
I'm a relatively new developer, fresh from college. While in college and during subsequent job-seeking, I realized that there were a lot of "modern" software development methodologies that my education was lacking: unit testing, logging, database normalization, agile development (vs. generic agile concepts), coding style guides, refactoring, code reviews,  no standardized documentation methods (or even requirements), etc.

Overall, I didn't see this is a problem. I expected my first job to embrace all of these ideas and to teach them to me on the job. Then I got my first job (full stack web development) at a big corporation and I realized that we do none of these things. In fact I, the least experienced on the team, am the one who is spearheading attempts to bring my team up to speed with "modern" programming techniques - as I worry that not doing so is professional suicide down the road.

First I began with logging software (log4J), but then I quickly moved on to writing my own styleguide, then abandoning it for the Google styleguide - and then I realized that our Java web development used hand-written front controllers, so I pushed for our adoption of Spring - but then I realized we had no unit tests, either, but I was already learning Spring... and as you can see, it becomes overwhelming all too quickly, especially when paired with normal development work. Furthermore, it is difficult for me to become "expert" enough in these methodologies to teach anyone else in them without devoting too much time to a single one of them, let alone them all.

Of all these techniques, which I see as "expected" in today's software development world, how do I integrate them into a team as a new player without overwhelming both myself and the team?

How can I influence my team to become more agile? is related, but I'm not an Agile developer like the asker here, and I'm looking at a much broader set of methodologies than Agile.


问:
REST API design: POST (implicit userId) vs PUT (explicit userId)
For some routes on an API, like GET /news, one would asume the user only wants news that pertains to them, so the userId is implicitly taken from authentication info.

However, some of the routes on an API i'm designing modify the "users" resource - i.e. changing some account info. For example, the user might want to change their name on the account. I could do

POST /users/name

or

PUT /users/:userId/name

1) Is this dichotomy generally correct (correct meaning most REST APIs would be designed in this fashion)? The idea that PUT would use an explicit userId where POST would take it from authentication info

2) If yes to the above, which style makes more sense for "modifying-account-info" type routes? If no, what do you suggest?

答:
Your GET /news essentially hides with what resources are you working with behind authentication info (which is usually transferred to the server using sessionId). This isn't RESTful, as you should explicitly define what resources are you working with in the URL.

Correct version is:

```<code>GET /news?userId=:userId
</code>```

Even in this case you use the authentication info to validate/authorize the request, but this is OK from the REST point of view.

The only exception to this rule is the POST when you're creating a new entity while the key is generated on the server - in this case you omit the ID because you don't know it yet. It has some disadvantages (non-idempotent), using PUT with client-generated key is better.

Body:
Your GET /news essentially hides with what resources are you working with behind authentication info (which is usually transferred to the server using sessionId). This isn't RESTful, as you should explicitly define what resources are you working with in the URL.

Correct version is:

GET /news?userId=:userId

Even in this case you use the authentication info to validate/authorize the request, but this is OK from the REST point of view.

The only exception to this rule is the POST when you're creating a new entity while the key is generated on the server - in this case you omit the ID because you don't know it yet. It has some disadvantages (non-idempotent), using PUT with client-generated key is better.


答:
First of all, be aware that ESB and Microservices can mean different things depending on context. Also, it seems that people usually consider Microservices within a pull-architecture: there are Restful APIs and each service calls other service's APIs to get data as needed. ESB, on the other hand is usually associated with a push-architecture: systems put data in queues where other systems get that data delivered later.

The default use of APIs is to provide an application's functionality to other systems and services and to hide that application's backend data representation from all those other services. So if you'd build your product data app according to those principles than you would build an API inside that app and thus use the same data access functionality (SQL, ORM, etc.) as the rest of the app. If the mobile app needs just the basic product management features which your app provides, it would directly use this API and you'd not have any further separation and not not sync any data.

If, on the other hand, your mobile app needs the data in a more refined for or with some additional functionality, or with higher performance than the original app can deliver (and you can't fix this with a simple caching reverse-proxy) or your old app is old technology and hard to extend, only then you'll get a benefit for putting your new API in a separate application. And only then you need to find a way to sync data between both.

Now, assuming the latter is the case, your means of syncing depend on many things:

Does data only go one way or both ways?

If both ways, does the existing application need a way to validate and reject invalid data?

How often does data change? and how quick do changes need to be reflected?

What ways of exporting and importing data does the existing application provide? this is of special importance when that app is hard to extend!

How likely is the data format of the old app to change? In a new
Microservice-based architecture you add APIs to encapsulate app data
whose format changes often. In an old legacy app, maybe nothing will
change any more until the app dies some day. (Also, beware that we
often expect this to happen, but as the proverb says: "The condemned
live longer.")

In any case, the first question you should answer is: does your new API just provide a new form of access to existing data and functionality or does it provide you functionality and needs a different form to store the data? Use this and other criteria to decide if the API should be part of the existing app or a new application.

Title: Using ESB for database synchronisation / replication

Body:
We're starting to look at implementing an ESB / Microservices architecture. I (think) I know about the concepts, but there's one thing I don't seem to be able to get a good idea about: data replication / synchronisation.

Creating an event for each and every table (maybe even multiple (create,update,delete)) seems like overkill to me, if it's just to synchronize data. Wouldn't an ETL / SQL Replication solution be much easier, in cases where no business logic will be exectute, as it's just to update the local cache/db of the server?

What strategies would you advise?

Simple example, we have an application that manages all product data, we want to build an API (Web Service) that is going to serve a Mobile App that will display that data.

There are several options:

API directly accesses the database

API has a local database that's being kept up to date using ESB messages

API has a local database that's being kept up to date using some replication tool

API has a local database that's updated once a day using a batch operation.

In my opinion the reason to use messages would be to further uncouple the systems as the database structure behind it can be changed without affecting the system in that scenario. For all other means and purposes 3/4 seem much let complex, which in my opionion meets the KISS principle.

What would you advice? Where can I get some sort of flowchart/decision tree example on what alternative to use when?


答:
I've seen good APIs designed both ways. On the one hand, providing the userId in authentication and the URL seems redundant.

On the other hand, it could be more consistent to have an explicit Id in the URL if there are also ways for one user to look at public data of another user or you are using the same or a similar API in clients that need to get data for many users. That way, you always provide a userId in the URL, no matter if it's redundant or not.

As an aside, I have also seen APIs where you could use the word "me" in the URL to refer to the authenticated user.

Title: REST API design: POST (implicit userId) vs PUT (explicit userId)

Body:
For some routes on an API, like GET /news, one would asume the user only wants news that pertains to them, so the userId is implicitly taken from authentication info.

However, some of the routes on an API i'm designing modify the "users" resource - i.e. changing some account info. For example, the user might want to change their name on the account. I could do

POST /users/name

or

PUT /users/:userId/name

1) Is this dichotomy generally correct (correct meaning most REST APIs would be designed in this fashion)? The idea that PUT would use an explicit userId where POST would take it from authentication info

2) If yes to the above, which style makes more sense for "modifying-account-info" type routes? If no, what do you suggest?


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

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

答:
Write an algorithm for the following problem: Given a number n, output the total number of (unique) binary trees that have n nodes.

Thus, for n=0 and n=1, the answer is 1. For n=2, you have 2: the root node, and then the second node either to the left or the right.

You can gain insight into design techniques and to see if they think of recursion or memoization or the dynamic programming solution.

[See also this StackOverflow discussion for the related, but different, case of binary-search trees.]


问:
Modifying GPL code to link closely with another program
If program B is licensed under GPL, can a programmer modify it to interact with his own proprietary program, A, such that both programs are separate processes, and then only release the modified source code only for program B?

I was thinking of program B being turned into a "black box" for program A, but instead of it being a function it's a completely separate program.

I'm not seeking legal advice, I'm trying to understand more about free software and its complications without being too technical. Unfortunately, the GPL faq talks about linked libraries and other things I haven't covered yet in school, so it is difficult for me to wrap my mind around the "general" case here.

答:
You take GPL-licensed program B, modify it, and release the result under GPL. That's just what you should do. No matter what A does with B as long as A is in independent program.

The tricky question is what happens if your proprietary program doesn't do anything useful unless there is also B running and you write and distribute a wrapper (say, W) which makes it easier for the user to run A and B together. Than the entire A+B+W package could be considered a derived work and legal difficulties can arise. Possibly, the safest way would be to tell the user that they have to get B themselves and start it the right way so that A can run. If that's not practical it could (depending on the situation) indeed be necessary that A (or at least W) is also open-sourced or you find an alternative to B which does not have the license restriction.


答:
Source control.

You did not mention it, hopefully because it's already in place, but, in case it's not, start there.

Source control has the biggest bang-for-buck, except in rare circunstances pathologically in need of something else.

And you can start alone if no one initially buys in.


答:
There are basically two different questions in one. Let me simplify and rephrase them:

1. If you have userId once as authentication info and once as a part of a data object which one should win?

None of them should win. These are two different userIds one is user performing the action another is the data object user as a subject of the action. Think of admin renaming another user. in case of a normal user you should compare this two id-s and return some error status code if they differ.

2. How to design an API call to the resource location which modifies the location itself? Example: PUT to /users/{name} would potentially alter the name.

That's why you have userId. I assume userId do not change. So use this location to PUT to to update the user. As a convenience you can provide response redirect on the location /users/{name} to corresponding permanent location of the resource.


答:
First, it does not matter if you change B afterwards as long as you publish your modifications under GPL again. B could have been written (and published) that way by the original author, before you already started to create A.

So your situation is probably one of the two scenarios described in the GPL FAQ under

"writing a [GPL] plug-in for a non-free program"

or

"non-free program that's designed to load a GPL-covered plug-in"

(pick your choice which one fits better to your case).

When you read the two sections, you see the critical point in both cases is if the communication between the free and the non-free program is done just by "fork and exec" (or whatever equivalent the OS you are using provides). If, however, the two pieces of software "make function calls to each other and share data structures", you are violating the GPL (that is actually how I would interpret the FAQ, but IANAL).

Title: Modifying GPL code to link closely with another program

Body:
If program B is licensed under GPL, can a programmer modify it to interact with his own proprietary program, A, such that both programs are separate processes, and then only release the modified source code only for program B?

I was thinking of program B being turned into a "black box" for program A, but instead of it being a function it's a completely separate program.

I'm not seeking legal advice, I'm trying to understand more about free software and its complications without being too technical. Unfortunately, the GPL faq talks about linked libraries and other things I haven't covered yet in school, so it is difficult for me to wrap my mind around the "general" case here.


问:
Encapsulating mutable objects with special structure in Python
I am writing a library for working with special types of trees, called Foo trees. A Foo tree has very special structure. There some operations, called bar and baz, which only make sense on Foo trees. So I'm designing a FooTree class to represent Foo trees.

To construct a FooTree instance, one might pass some object representing a tree. This object will be checked for special structure and stored internally:

```<code>class FooTree(object):

    def __init__(self, tree):
        ... # check that tree is a valid Foo tree
        self._tree = tree

    def bar(self):
        # operation that only makes sense on a foo tree
</code>```

The problem is: what if I construct a FooTree from a mutable object? For example, say Tree is a type whose instances are mutable:

```<code>tree = Tree()
... # build a valid Foo tree
foo_tree = FooTree(tree)
tree.remove_node(0) # tree is no longer a Foo tree
</code>```

Since tree is no longer a valid Foo tree, and foo_tree wraps a reference to tree, foo_tree is no longer valid.

Instead I might copy the tree when creating a FooTree:

```<code>class FooTree(object):

    def __init__(self, tree):
        ... # check that tree is a valid Foo tree
        self._tree = tree.copy()

    def bar(self):
        # operation that only makes sense on a foo tree
</code>```

This solves the problem, but creates a new one: Foo trees are typically very large, so copying them is expensive.

What patterns exist for creating FooTree objects from Tree objects, without copying and without the mutability problem?

For example, I might have FooTree accept a callable which produces a Tree:

```<code>class FooTreeBuilder(object):
    def __init__(self, data):
        self.data = data

    def __call__(self):
        tree = Tree()
        ... # build tree from self.data
        return tree

class FooTree(object):

    def __init__(self, builder):
        self._tree = builder()

builder = FooTreeBuilder(data)
foo_tree = FooTree(builder)
</code>```

Are there any better approaches? I'm specifically looking for approaches that lend well to Python implementations.

答:
some options are:

using immutable trees as basic data structure

using a builder or mutation operations to construct a FooTree without needing a Tree

copying the input tree (which is good practice unless you have really big data and performance issues)

Note that by builder I mean the builder pattern as described by Joshua Bloch. (Long article, but the design issue is relevant for Python just as it is for Java.) Your Builder callable does not really mitigate the problem, because if a user of FooTree already has a Tree, they will just call FooTree(lambda: myTree) and thus you'll have the mutability problem again.

The builder pattern (or making making FooTree mutable), on the other hand, allow your users to create FooTrees directly without needing a Tree first.

and the best choice depends on:

whether Tree is a class that you can design (and make immutable) as opposed to using something that is given.

in your application domain: do trees change often or is immutability actually a good abstraction?

how much separation you want between your own FooTrees and the other Trees. Maybe copying the tree has good side benefits like using a specialized data structure for your own trees.

do you actually need trees anyways? are they your given input material? or would a solution without the Tree class make any sense?

All of this is independent of the language who are using and making it Pythonic is a matter of implementing the chosen design.


答:
I disagree with your statement that C is not designed for concurrency. C is designed for general systems programming and enjoys a tenacity for pointing out critical decisions to be made, and will continue to do so for years to come. This is true even when the best decision might be not to use C. Additionally, concurrency in C is only as difficult as your design is complex.

I try, to the best of my ability, to implement locks with the idea that eventually, truly practical lock free programming might become a reality for me. By locking, I don't mean mutual exclusion, I simply mean a process that implements safe concurrency without the need for arbitration. By practical, I mean something that is easier to port than it was to implement. I have very little formal CS training as well, but I suppose that I'm permitted to wish :)

Following that, most bugs that I encounter become relatively shallow, or so completely mind boggling that I retreat to a pub. The pub becomes an attractive option only when profiling a program slows it down sufficiently to expose additional races that aren't related to what I'm trying to find.

As others have pointed out, the problem that you describe is extremely domain specific. I just try, with the best of my ability to avoid any case that might require arbitration (outside of my process) whenever possible. If that looks like it might be a regal pain, I re-evaluate the option of giving multiple threads or processes concurrent and unserialized access to something.

Then again, throw 'distributed' in there and arbitration becomes a must. Do you have a specific example?

Title: Concurrency: How do you approach the design and debug the implementation?

Body:
I've been developing concurrent systems for several years now, and I have a pretty good grasp on the subject despite my lack of formal training (i.e. no degree).  There's a few new languages that have become popular to at least talk about lately that are designed to make concurrency easier such as Erlang and Go.  It appears that their approach to concurrency echoes my own experience as to how to make systems scalable and take advantage of multiple cores/processors/machines.

However, I find that there are very few tools to help visualize what you intend to do, and verify that you are at least close to your original vision.  Debugging concurrent code can be a nightmare with languages that are not designed for concurrency (like C/C++, C#, Java, etc.).  In particular, it can be near impossible to recreate conditions that happen readily on one system in your development environment.

So, what are your approaches to designing a system to deal with concurrency and parallel processing?  Examples:

How do you figure out what can be made concurrent vs. what has to be sequential?

How do you reproduce error conditions and view what is happening as the application executes?

How do you visualize the interactions between the different concurrent parts of the application?

I have my own answers for some of these, but I'd also like to learn a bit more.

Edit

So far we have a lot of good input.  Many of the articles linked to are very good, and I've already read some of them.

My personal experience with concurrent programming leads me to believe you need a different mindset than you do with sequential programming.  The mental divide is probably as wide as the difference between object oriented programming and procedural programming.  I'd like this set of questions to focus more on the thought processes necessary (i.e. theory) to systematically approach the answers.  When providing more concrete answers, it helps to provide an example--something you went through personally.

Goal for the Bounty

Don't tell me what I should do.  I already have that under control.  Tell me what you do.  Tell me how you solve these problems.