问:
How is encapsulation used for safety?
I am learning OOP. I have studied much about encapsulation but the more I read the more I became confused.

I understand we hide (by making private) data and expose it to user of class (other developers) as properties or methods. I also understand by encapsulation we hide details.

In an article (http://www.csharp-station.com/Tutorial/CSharp/lesson19) I read:

Abstract from article

When designing an object, you must think about how others could use it. In a best-case scenario any program using the object would be well designed and the code would never change. However, the reality is that programs do change often and in a team environment many people touch the same code at one time or another. Therefore, it is beneficial to consider what could go wrong as well as the pristine image of how the object should be used.

In the case of the BankAccount object, examine the situation where code outside of your object could access a decimal Amount field or a string CustomerName field. At the point of time that the code is written, everything would work well. However, later in the development cycle, you realize that the BankAccount object should keep track of an int CustomerID rather than string CustomerName because you don't want to duplicate relationships between information (or some other valid reason to alter the definition of internal state). Such changes cause a rippling effect in your code because it was built to use the BankAccount class, as originally designed (with CustomerName being a string), and you must now change code that accesses that state throughout your entire application.

The object-oriented principle of Encapsulation helps avoid such problems, allowing you to hide internal state and abstract access to it though type members such as methods, properties, and indexers. Encapsulation helps you reduce coupling between objects and increases the maintainability of your code.

Question
How will encapsulation help when making changes in code and from its rippling effects.
For a data member, if I change its type from int to float, (even if I am exposing this using property) I will need to change variable type where I am using already using this code.

Kindly guide me how encapsulation will help with such changes.

Thanks for this help and guidance.

答:
The main way that encapsulation helps reduce rippling effects of change is by keeping as many of the implementation details private to the class. By limiting the interface only to those members needed to use the class, many changes can be made to the implementation without affecting any code that uses the class.

That seems to be the point being made by the text you quoted, although I also found it a little confusing on my first read.

OwnerDisplayName: haansi

Title: How is encapsulation used for safety?

OwnerDisplayName: Jonathan Wood


问:
Can any GPLv2 licensed library be used in a company's internal intranet application?
I am creating an internal application for the company I am contracted to. We wish to use a GPLv2 licensed library in this application. Some points

The application is to be used within the confines of the company and
never be available for public use. It is for internal company use
only.

It will never be sold, ever!!. So no money will be made directly from selling the code. It's not a product.

There are two forms of usage of the application

Its native form which is console based exe (which uses the GPL library); and

Usage via a web interface which calls the executable.

The source code will remain closed source (company use only), and be propriety

I have gone through numerous questions on SO about this (one closed as off-topic and another unmarked from Programmers ), but I have had a hard time in understanding whether my interpretation of the licence is correct.

Based on my understanding thus far, I am permitted to use this library without any concern. I am not modifying the source code nor am I distributing the application or making the application publicly available. The application will not be sold nor will it be distributed to anyone outside the company (It will however be available at our company's offsite DR facility). I am very likely to use the released versions binaries and not re-compile from source.

The following question from the GNU FAQ seems to support my thoughts.

Does the GPL require that source code of modified versions be posted to the public?

The GPL does not require you to release your modified version, or any
  part of it. You are free to make modifications and use them privately,
  without ever releasing them. This applies to organizations (including
  companies), too; an organization can make a modified version and use
  it internally without ever releasing it outside the organization.

But if you release the modified version to the public in some way, the
  GPL requires you to make the modified source code available to the
  program's users, under the GPL.

Thus, the GPL gives permission to release the modified program in
  certain ways, and not in other ways; but the decision of whether to
  release it is up to you.

Can any GPLv2 licensed library be used in a company's internal intranet application?

答:
The LGPL version 2 allows you to redistribute the source and binary.

You can even sell it.

The only real restriction is as follows:

If you modify the library and distribute it, then you must release the changes you have made to the library publicly. Read point 2 of the LGPL.

If you don't modify it you don't really have a problem.

ContentLicense: CC BY-SA 3.0


问:
Why is naming a table's Primary Key column "Id" considered bad practice?
My t-sql teacher told us that naming our PK column "Id" is considered bad practice without any further explanations.

Why is naming a table PK column "Id" is considered bad practice?

答:
Another thing to consider is that if the primary key name is different from the foreign key name, then it is not possible to use certain third party tools.

For example, you would be unable to load your schema into a tool like Visio and have it produce accurate ERD's.


问:
Fuzzy search for a sub-string without tokens
Let's say I have the following lines:

```<code>Lorem ipsum dolor sit amet, (tag) consectetur adipiscing elit.
Phasellus congue nisi vel lorem dignissim tristique. (tag)
Etiam vulputate lacus nec velit lobortis ut adipiscing mauris condimentum. (tag )
Vestibulum quis nulla id nisi ultricies placerat. (teg)
In tempus vulputate ante, quis suscipit nunc euismod in. (teg )
Phasellus iaculis diam in felis pellentesque tristique. (ta g)
(tag Praesent vestibulum sollicitudin velit, non mollis lacus scelerisque in.
Nunc ac erat enim, at lobortis libero. (interesting)
</code>```

There's supposed to be a tag in each line enclosed in parenthesis.  But as you can see the data is very dirty and there's extra spaces inside tags, missing parents, misspelled tags, etc.

How would I identify the lines containing "(tag)" or something similar?  The output I would expect in the example is to retrieve all lines, except for the last.

I need to compare a long string to a shorter sub-string, so something like Levenshtein distance wont work (or will it?).  Tokenized techniques seem to rigid, because although I might tokenize everything in parenthesis, what happens when a parenthesis is missing?

答:
I will answer my own question with these links:

http://codehost.wordpress.com/2011/09/13/fuzzy-substring-matching/

http://ginstrom.com/scribbles/2007/12/01/fuzzy-substring-matching-with-levenshtein-distance-in-python/

The second link contains the following function:

```<code>def fuzzy_substring(needle, haystack):
    """Calculates the fuzzy match of needle in haystack,
    using a modified version of the Levenshtein distance
    algorithm.
    The function is modified from the levenshtein function
    in the bktree module by Adam Hupp"""

    m, n = len(needle), len(haystack)

    # base cases
    if m == 1:
        return not needle in haystack
    if not n:
        return m

    row1 = [0] * (n+1)
    for i in range(0,m):
        row2 = [i+1]
        for j in range(0,n):
            cost = ( needle[i] != haystack[j] )

            row2.append( min(row1[j+1]+1, # deletion
                               row2[j]+1, #insertion
                               row1[j]+cost) #substitution
                           )
        row1 = row2
    return min(row1)

lines = """Lorem ipsum dolor sit amet, (tag) consectetur adipiscing elit.
Phasellus congue nisi vel lorem dignissim tristique. (tag)
Etiam vulputate lacus nec velit lobortis ut adipiscing mauris condimentum. (tag )
Vestibulum quis nulla id nisi ultricies placerat. (teg)
In tempus vulputate ante, quis suscipit nunc euismod in. (teg )
Phasellus iaculis diam in felis pellentesque tristique. (ta g)
(tag Praesent vestibulum sollicitudin velit, non mollis lacus scelerisque in.
Nunc ac erat enim, at lobortis libero. (interesting)""".split('\n')

for line in lines:
    print fuzzy_substring('(tag)', line), line
</code>```

The output is:

```<code>0 Lorem ipsum dolor sit amet, (tag) consectetur adipiscing elit.
0 Phasellus congue nisi vel lorem dignissim tristique. (tag)
1 Etiam vulputate lacus nec velit lobortis ut adipiscing mauris condimentum. (tag )
1 Vestibulum quis nulla id nisi ultricies placerat. (teg)
2 In tempus vulputate ante, quis suscipit nunc euismod in. (teg )
1 Phasellus iaculis diam in felis pellentesque tristique. (ta g)
1 (tag Praesent vestibulum sollicitudin velit, non mollis lacus scelerisque in.
3 Nunc ac erat enim, at lobortis libero. (interesting)
</code>```

Body:
I will answer my own question with these links:

http://codehost.wordpress.com/2011/09/13/fuzzy-substring-matching/

http://ginstrom.com/scribbles/2007/12/01/fuzzy-substring-matching-with-levenshtein-distance-in-python/

The second link contains the following function:

def fuzzy_substring(needle, haystack):
    """Calculates the fuzzy match of needle in haystack,
    using a modified version of the Levenshtein distance
    algorithm.
    The function is modified from the levenshtein function
    in the bktree module by Adam Hupp"""

    m, n = len(needle), len(haystack)

    # base cases
    if m == 1:
        return not needle in haystack
    if not n:
        return m

    row1 = [0] * (n+1)
    for i in range(0,m):
        row2 = [i+1]
        for j in range(0,n):
            cost = ( needle[i] != haystack[j] )

            row2.append( min(row1[j+1]+1, # deletion
                               row2[j]+1, #insertion
                               row1[j]+cost) #substitution
                           )
        row1 = row2
    return min(row1)

lines = """Lorem ipsum dolor sit amet, (tag) consectetur adipiscing elit.
Phasellus congue nisi vel lorem dignissim tristique. (tag)
Etiam vulputate lacus nec velit lobortis ut adipiscing mauris condimentum. (tag )
Vestibulum quis nulla id nisi ultricies placerat. (teg)
In tempus vulputate ante, quis suscipit nunc euismod in. (teg )
Phasellus iaculis diam in felis pellentesque tristique. (ta g)
(tag Praesent vestibulum sollicitudin velit, non mollis lacus scelerisque in.
Nunc ac erat enim, at lobortis libero. (interesting)""".split('\n')

for line in lines:
    print fuzzy_substring('(tag)', line), line

The output is:

0 Lorem ipsum dolor sit amet, (tag) consectetur adipiscing elit.
0 Phasellus congue nisi vel lorem dignissim tristique. (tag)
1 Etiam vulputate lacus nec velit lobortis ut adipiscing mauris condimentum. (tag )
1 Vestibulum quis nulla id nisi ultricies placerat. (teg)
2 In tempus vulputate ante, quis suscipit nunc euismod in. (teg )
1 Phasellus iaculis diam in felis pellentesque tristique. (ta g)
1 (tag Praesent vestibulum sollicitudin velit, non mollis lacus scelerisque in.
3 Nunc ac erat enim, at lobortis libero. (interesting)


问:
Testing for object equality by comparing the toString() representations of objects
Following on from this question - how do you explain to someone that this is just crazy!:

```<code>boolean someMethod(Map<String, Object> context) {
    Object object = context.get("someProperty")
    Object another = context.get("anotherProperty")

    return object.toString().equals(another.toString());
}
</code>```

Apparently the reason for why Object.equals(...) is not used is that "what's contained in the Map is not concretely known, but is definitely known to be one of the primitive wrappers i.e. String, Double, Boolean, etc... and that Boolean.TRUE is required to be equal(...) to the String "TRUE"".

答:
If you are keenly interested to know about Object Equality then use can use the method of
class Object.

int hashCode() gives the integer value called  hashCode which pertain to an object.

```<code>definitely the hashcode differs object to object.
     it's a easiest way to identify object equality.
</code>```

Body:
If you are keenly interested to know about Object Equality then use can use the method of
class Object.

int hashCode() gives the integer value called  hashCode which pertain to an object.

definitely the hashcode differs object to object.
     it's a easiest way to identify object equality.


问:
Why is the folder name "bin" used in some frameworks and languages?
I have been learning Java. And still after a prolonged time I don't know why the name of the folder is "bin" where one find all the tools for java?

Is there is any logical reason behind that?

I have also noticed the same in .Net framework also.

答: bin is a standard directory name in typical UNIX/UNIX-like systems.  It goes back to the early days of UNIX. /bin, /usr/bin or /usr/local/bin are directories where executable binaries are stored on most UNIX or UNIX-like systems.  Java simply used this conventional name to designate where executables are stored within the Java home directory.


问:
Why aren't there other programming languages that compile to Python bytecode?
In Java, there are multiple languages that compile to Java bytecode and can run on the JVM -- Clojure, Groovy, and Scala being the main ones I can remember off the top of my head.

However, Python also turns into bytecode (.pyc files) before being run by the Python interpreter.  I might just be ignorant, but why aren't there any other programming languages that compile to python bytecode?

Is it just because nobody bothered to, or is there some kind of inherent restriction or barrier in place that makes doing so difficult?

答:
There are multiple JVM languages because there were talented people who wanted to write code that would work with existing Java code, but they didn't want to write Java.

Apparently there are no programmers who want to work with existing Python code, but hate Python enough to port another language to the Python bytecode interpreter.

You can look at this in two ways: there are alternative languages for the JVM because Java is so widespread, or there are no alternative languages for the Python bytecode interpreter because Python doesn't suck.


答:
I think it allows you to change the functionality of your class without, although not always, introducing BC breaks (Binary or Behavioural Compatibility). That is, you can change how your class does 'something' without having to change how the end user tells it to do that 'something'.

The example you gave of changing the return type is a BC break, because anyone who previously used your class will not be able to use the new version without recompiling. This is something that should be done only as a last resort, and in a professional setting can only be done with clearance from architects and after paperwork has been filed, customers notified, etc.

It also gives you complete control over the state of your object.

Title: How is encapsulation used for safety?

Body:
I am learning OOP. I have studied much about encapsulation but the more I read the more I became confused.

I understand we hide (by making private) data and expose it to user of class (other developers) as properties or methods. I also understand by encapsulation we hide details.

In an article (http://www.csharp-station.com/Tutorial/CSharp/lesson19) I read:

Abstract from article

When designing an object, you must think about how others could use it. In a best-case scenario any program using the object would be well designed and the code would never change. However, the reality is that programs do change often and in a team environment many people touch the same code at one time or another. Therefore, it is beneficial to consider what could go wrong as well as the pristine image of how the object should be used.

In the case of the BankAccount object, examine the situation where code outside of your object could access a decimal Amount field or a string CustomerName field. At the point of time that the code is written, everything would work well. However, later in the development cycle, you realize that the BankAccount object should keep track of an int CustomerID rather than string CustomerName because you don't want to duplicate relationships between information (or some other valid reason to alter the definition of internal state). Such changes cause a rippling effect in your code because it was built to use the BankAccount class, as originally designed (with CustomerName being a string), and you must now change code that accesses that state throughout your entire application.

The object-oriented principle of Encapsulation helps avoid such problems, allowing you to hide internal state and abstract access to it though type members such as methods, properties, and indexers. Encapsulation helps you reduce coupling between objects and increases the maintainability of your code.

Question
How will encapsulation help when making changes in code and from its rippling effects.
For a data member, if I change its type from int to float, (even if I am exposing this using property) I will need to change variable type where I am using already using this code.

Kindly guide me how encapsulation will help with such changes.

Thanks for this help and guidance.


问:
Looking for a good approach and data structure to solve this
C# WinForms:

A Combobox with some items in in.

A spread sheet with some items in it. Each row also has a check-box so users can select them.

User picks an items in the combobox and clicks a Save button. It means associate that Combobox item to those selected items in the spreadsheet.

Q1: What's a good structure I can use to keep track of which combobox item is associated with which items from the spreadsheet?

NOTE: User can also Move up or Mode Down the items in the spreadsheet. So it gets a little tricky here, they might have associated some items, then they change the order or those items but we still need to know what items are selected for each combobox item

Q2: What's a good approach to keep track of that?

答:
I think both questions can be answered at once.  A Dictionary for sure.  You can keep track of which item (key) is associated with item(s) (value(s)) on the spreadsheet. It's important to associate the key and its value(s) before order changes so the correct associations have been made. If you want spaghetti to be matched with meatballs and parmesean cheese, you don't want to sort in which sphagetti is matched with peanut butter.

NOTE: A tuple is two items paired together. A dictionary is a pair that associates a key with its value(s).


答:
There are technical deficiencies such as the GIL in CPython, but few perceived language deficiencies, so the runtime isn't the selling point of the Python community. Exactly the opposite, there are more backend runtime options because of the dissatisfaction with the GIL/CPython implementation.

The Java Language is much more maligned than the JVM ( even in the Java community ).

The JVM is pretty well regarded in most circles; thus the desire for different/better language front ends with the benefits of the highly optimized back end JVM.

Title: Why aren't there other programming languages that compile to Python bytecode?

Body:
In Java, there are multiple languages that compile to Java bytecode and can run on the JVM -- Clojure, Groovy, and Scala being the main ones I can remember off the top of my head.

However, Python also turns into bytecode (.pyc files) before being run by the Python interpreter.  I might just be ignorant, but why aren't there any other programming languages that compile to python bytecode?

Is it just because nobody bothered to, or is there some kind of inherent restriction or barrier in place that makes doing so difficult?


问:
Why do trees grow downward?
Why do trees grow downward in computer science?

I have a feeling it goes back to a printer, and that a program traversing a tree first prints the root, and uses the notion of a bottomless stack of paper to express the indefinite levels of recursion that might be encountered.

References:

Trees grow downward, having their roots at the top of the page and their leaves down below

From ON HOLY WARS AND A PLEA FOR PEACE.

by convention, trees are drawn growing downwards

From the Wikipedia article on tree data structures.

Real trees grow from their root upwards to the sky, but computer-science trees grow from the root downwards

From David Schmidt's lecture notes.

答:
Drawing from the top > down and left > right are popular in computer science because those are the starting directions in written English. Considering that most computer science papers are written in English regardless of the native language of the writer this would be the most prevalent way to draw diagrams.

It is most natural for an English language reader to read a graph from top > down or left > right than either of the other alternatives.

Do a search of images.google.com for directed tree graph and review the results. The only tree diagrams I could find that went up were UML Class Diagrams, and only because that is the convention that UML chose for Class Diagrams. All other UML Diagrams go left > right or up > down.

I would consider reading directed tree graphs from down > up as un-natural as reading top posted email threads; which to say is completely un-natural.

Title: Why do trees grow downward?


答:
In my experience, encapsulation makes doing the "wrong" thing much more difficult. You can group together functionality which semantically go together and isolate them from functionality which can lead to bad or unpredictable behavior. It can also help hide the details from the end user which may help increase safety and reliability.

Consider this post by John D Cook. Consider that you have a Bread object. One natural thing to slice this bread. So you write a slice() function, so you can do

slice(loaf)

with a new loaf object you've created. This makes sense. But if you're not careful, you might accidentally call

slice(finger)

with a finger object somewhere in your project. This could lead to very bad things. Instead, encapsulate this function/method into a Bread class so you can do this

loaf.slice()

This definitely  helps avoid calling finger.slice() accidentally, since finger probably doesn't have a slice() method associated with it.

This is a bit of a contrived example but I've found it helpful. Encapsulation is can sometimes be an underrated aspect of OOP, but it's a good one.

Title: How is encapsulation used for safety?


问:
Should I change the name of the WTFPL?
I'm using the WTFPL in my personal projects that I have published on GitHub.

Currently I'm using the license verbatim, but I have a suspicion that I shouldn't be leaving the third line:

```<code>Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
</code>```

in there, and instead should use my name instead of Sam's.

But the license is very confusing about this.

Half of the WTFPL site is about the WTFPL itself, so I thought that copyright statement might refer to a copyright on the license text itself, and not on the project that is using the license.

However, the site also says:

Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed.

So would I have to change the name from "WTFPL" to something like "WTFPL-Domenic"?

答:
Whether or not you should change the name of the license depends upon what you've changed and what you're applying the license against.

Short answer: If you are just applying the license to your program, then no you do not need to change the name of the WTFPL.  If you are changing the terms or language of the WTFPL then you need to change the name of the WTFPL as well.

Applying the license

To apply the license to your program(s), the WTFPL FAQ lays things out pretty clearly for you.

Step 1. Download or copy/paste the full text of the WTFPL and distribute it with your work. A common file name for the license file is COPYING. If the work features multiple licenses, it is usual to call the file COPYING.WTFPL.

Step 2. Add the following wording to your copyright statements:

```<code>    Copyright © 2000 Your Name <your@address>
    This work is free. You can redistribute it and/or modify it under the
    terms of the Do What The Fuck You Want To Public License, Version 2,
    as published by Sam Hocevar. See the COPYING file for more details.
</code>```

And as part of Step 2, you need to change:

```<code>Copyright © 2000 Your Name <your@address>
</code>```

to:

```<code>Copyright © 2014 Domenic < domenic@your.email.addr >
</code>```

note: Use your name or github alias in there and provide a valid email address

If you don't want to change anything about the license itself, you're done.

That said, the WTFPL is essentially saying "this is completely free, do whatever you want" which negates any actual claim to copyright.  So you could skip Step 2 and just insert the WTFPL text verbatim as per Step 1.

Modifying the license

You don't have to modify the license terms, but you might have your reasons for wanting to do so.  For example, perhaps you're a huge Battlestar Galactica fan and you want to change the F to frak in order to make it a bit less vulgar.

In that case, by the terms of that copyright, you must change the name of the license and the copyright it's held under.  This is also addressed in the FAQ.

Can’t you change the wording? It’s inappropriate / childish / not corporate-compliant.

The WTFPL lets you relicense the work under any other license.

To be a bit more clear about how you would change the WTFPL itself, let's look at the WTFPL:

In sections 1 and 3, you'll need to perform the equivalent of this sed command:

```<code>s/FUCK/FRAK/g
</code>```

Note that this changes the name of the license to DO WHAT THE FRAK YOU WANT TO PUBLIC LICENSE

Technically speaking, you ought to change the version and date in section 1 but you don't necessarily have to since they're kind of meaningless in this context.

And in section 2, you'll need to change:

Copyright (C) 2004 Sam Hocevar

into something like this:

Copyright (C) 2014 Domenic < domenic@your.email.addr >

You may feel free to add something in your version acknowledging Sam Hocevar's contribution, but you are not required to do so.

It's questionable if you can also refer to your license as the "WTFPL" since the actual name is now "What The Frak Public License" and "WTFPL" is just an abbreviation of the name of the license.  Given the spirit that the original WTFPL has been released under, I certainly wouldn't worry about it.  Use whatever the frak abbreviation you'd like.

Title: Should I change the name of the WTFPL?

Body:
Whether or not you should change the name of the license depends upon what you've changed and what you're applying the license against.

Short answer: If you are just applying the license to your program, then no you do not need to change the name of the WTFPL.  If you are changing the terms or language of the WTFPL then you need to change the name of the WTFPL as well.

Applying the license

To apply the license to your program(s), the WTFPL FAQ lays things out pretty clearly for you.

Step 1. Download or copy/paste the full text of the WTFPL and distribute it with your work. A common file name for the license file is COPYING. If the work features multiple licenses, it is usual to call the file COPYING.WTFPL.

Step 2. Add the following wording to your copyright statements:

    Copyright © 2000 Your Name <your@address>
    This work is free. You can redistribute it and/or modify it under the
    terms of the Do What The Fuck You Want To Public License, Version 2,
    as published by Sam Hocevar. See the COPYING file for more details.

And as part of Step 2, you need to change:

Copyright © 2000 Your Name <your@address>

to:

Copyright © 2014 Domenic < domenic@your.email.addr >

note: Use your name or github alias in there and provide a valid email address

If you don't want to change anything about the license itself, you're done.

That said, the WTFPL is essentially saying "this is completely free, do whatever you want" which negates any actual claim to copyright.  So you could skip Step 2 and just insert the WTFPL text verbatim as per Step 1.

Modifying the license

You don't have to modify the license terms, but you might have your reasons for wanting to do so.  For example, perhaps you're a huge Battlestar Galactica fan and you want to change the F to frak in order to make it a bit less vulgar.

In that case, by the terms of that copyright, you must change the name of the license and the copyright it's held under.  This is also addressed in the FAQ.

Can’t you change the wording? It’s inappropriate / childish / not corporate-compliant.

The WTFPL lets you relicense the work under any other license.

To be a bit more clear about how you would change the WTFPL itself, let's look at the WTFPL:

In sections 1 and 3, you'll need to perform the equivalent of this sed command:

s/FUCK/FRAK/g

Note that this changes the name of the license to DO WHAT THE FRAK YOU WANT TO PUBLIC LICENSE

Technically speaking, you ought to change the version and date in section 1 but you don't necessarily have to since they're kind of meaningless in this context.

And in section 2, you'll need to change:

Copyright (C) 2004 Sam Hocevar

into something like this:

Copyright (C) 2014 Domenic < domenic@your.email.addr >

You may feel free to add something in your version acknowledging Sam Hocevar's contribution, but you are not required to do so.

It's questionable if you can also refer to your license as the "WTFPL" since the actual name is now "What The Frak Public License" and "WTFPL" is just an abbreviation of the name of the license.  Given the spirit that the original WTFPL has been released under, I certainly wouldn't worry about it.  Use whatever the frak abbreviation you'd like.


答:
Encapsulation helps large groups of developers coordinate their work more efficiently.  Each group of developers works on different modules, and those modules are encapsulated -- separate the code into a small number of widely available operators whose use they can't control tightly, and a large number of internal operators that the can control tightly.  What this means is that each group of developers can define invariants that are important for their module to maintain, and make sure those invariants hold regardless of what other modules' developers do.

Since encapsulation allows for invariant-preservation, it is often used to maintain security/safety invariants, e.g.

that a datastore is never accessed without proper credentials

that a bank account never has more money added than was removed from another

that certain operations are always logged

The Object capability model is a methodology for writing security sensitive code that is encapsulation on steroids.

The security model relies on not being able to forge references; see Synthesizing addresses of actors.

Objects can interact only by sending messages on references.
A reference can be obtained by:

initial conditions: In the initial state of the computational world being described, object A may already have a reference to object B.
parenthood: If A creates B, at that moment A obtains the only reference to the newly created B.

endowment: If A creates B, B is born with that subset of A's references with which A chose to endow it.

introduction: If A has references to both B and C, A can send to B a message containing a reference to C. B can retain that reference for subsequent use.

In the Object-capability model, all computation is performed following the above rules.

Advantages that motivate object-oriented programming, such as encapsulation or information hiding, modularity, and separation of concerns, correspond to security goals such as least privilege and privilege separation in capability-based programming.

Title: How is encapsulation used for safety?


问:
Is this an example of a pattern or an algorithm?
I feel like I have a reusable "something" here and I'm not sure whether to think of it as a pattern or an algorithm (or neither).

It's characterized by having an unknown amount of work to accomplish a task because the subtasks can encounter various conditions which cause them to add "Issues" to a global queue.

Then, the command is run repeatedly coupled with a round of "Issue Fixing" until either there are no issues left or the number of issues does not change.

I'm just putting enough code here to show what I'm talking about - there's a bit more to it (let me know if I should post more).

```<code>        public void FindNewCampaigns()
        {
            var findNewCampaigns = Locator.Get<ICommand<IEnumerable<Campaign>>>("FindNewCampaigns");
            var campaigns = findNewCampaigns.Execute();
            var issues = Locator.Get<ICollection<Issue>>("CommandIssues");
            while (issues.Count > 0)
            {
                int before = issues.Count;
                FixIssues(issues);
                issues.Clear();
                campaigns = findNewCampaigns.Execute();
                int after = issues.Count;
                if (before == after)
                {
                    System.Console.WriteLine("No issues got fixed, quitting ({0}/{1}).", before, after);
                    break;
                }
            }
            if (issues.Count == 0)
            {
                CreateCampaigns(campaigns);
            }
        }

        private void FixIssues(ICollection<Issues.Issue> issues)
        {
            foreach (var issue in issues)
            {
                System.Console.WriteLine("ISSUE: " + issue.GetType().Name + " - " + issue.ToString());

                if (issue is AdvertiserDoesNotExist)
                {
                    var specificIssue = (AdvertiserDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.Advertiser>>("CreateAdvertiser");
                    command.Execute(specificIssue.AdvertiserName);
                }
                else if (issue is AccountManagerDoesNotExist)
                {
                    var specificIssue = (AccountManagerDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.AccountManager>>("CreateAccountManager");
                    command.Execute(specificIssue.AccountManagerName);
                }
                else if (issue is AdManagerDoesNotExist)
                {
                    var specificIssue = (AdManagerDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.AdManager>>("CreateAdManager");
                    command.Execute(specificIssue.AdManagerName);
                }
                else if (issue is MediaBuyerDoesNotExist)
                {
                    var specificIssue = (MediaBuyerDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.MediaBuyer>>("CreateMediaBuyer");
                    command.Execute(specificIssue.MediaBuyerName);
                }
            }
        }
</code>```

Here's the code for FindNewCampaigns.  It adds issues as it finds them.  An Issue is supposed to be something that needs to happen before a new campaign is able to actually get created in a target store.

```<code>    public class FindNewCampaigns : Command<IEnumerable<Campaign>>
    {
        private IFactory<CakeEntities> cakeEntities;
        private IFactory<DADatabase> eomDatabase;

        public FindNewCampaigns(IFactory<CakeEntities> cakeEntities, IFactory<DADatabase> eomDatabase)
        {
            this.cakeEntities = cakeEntities;
            this.eomDatabase = eomDatabase;
        }

        public override IEnumerable<Campaign> Execute()
        {
            using (var eom = eomDatabase.Create())
            using (var cake = cakeEntities.Create())
            {
                // Get EOM campaigns
                var campaigns = eom.Campaigns.Select(c => c.pid).ToList();
                // Get Cake offers
                var offers = cake.CakeOffers.Select(c => c.Offer_Id).ToList();
                // Get Cake offers that don't match to EOM campaigns
                var newOffers = offers.Except(campaigns).ToList();
                // Get default values
                int accountManagerID = DefaultAccountManagerId(eom);
                int adManagerID = DefaultAdManagerId(eom);
                int advertiserID = DefaultAdvertiserID(eom);
                int campaignStatusID = DefaultCampaignStatus(eom);
                // Create new campaigns in memory
                var newCampaigns = (from offer in cake.CakeOffers
                                    where newOffers.Contains(offer.Offer_Id)
                                    select new
                                    {
                                        Offer = offer,
                                        Campaign = new Campaign {
                                            pid = offer.Offer_Id,
                                            campaign_name = offer.OfferName,
                                            campaign_status_id = campaignStatusID,
                                            account_manager_id = accountManagerID,
                                            ad_manager_id = adManagerID,
                                            advertiser_id = advertiserID,
                                        }
                                    }).ToList();
                // Set campaign status
                var campaignStatus = eom.CampaignStatus.ToDictionary(c => c.name, c => c.id);
                campaignStatus.Add("Private", campaignStatus["Active"]);
                campaignStatus.Add("Apply To Run", campaignStatus["Active"]);
                campaignStatus.Add("Inactive", campaignStatus["default"]);
                foreach (var item in newCampaigns)
                {
                    string statusName = item.Offer.StatusName;
                    if (campaignStatus.ContainsKey(statusName))
                    {
                        item.Campaign.campaign_status_id = campaignStatus[statusName];
                    }
                    else
                    {
                        AddIssue(new CampaignStatusDoesNotExist(statusName));
                    }
                }
                // Set advertiser
                var cakeAdvertisers = cake.CakeAdvertisers.ToDictionary(c => c.Advertiser_Id);
                foreach (var item in newCampaigns)
                {
                    int offerAdvertiserID = int.Parse(item.Offer.Advertiser_Id);
                    var offerAdvertiser = cake.CakeAdvertisers.FirstOrDefault(c => c.Advertiser_Id == offerAdvertiserID);
                    string offerAdvertiserName = offerAdvertiser.AdvertiserName;
                    var eomAdvertiser = eom.Advertisers.FirstOrDefault(c => c.name == offerAdvertiserName);
                    if (eomAdvertiser != null)
                    {
                        item.Campaign.advertiser_id = eomAdvertiser.id;
                    }
                    else
                    {
                        AddIssue(new AdvertiserDoesNotExist(offerAdvertiserName));
                    }
                }
                // Set account manager
                foreach (var item in newCampaigns)
                {
                    int offerAdvertiserID = int.Parse(item.Offer.Advertiser_Id);
                    var offerAdvertiser = cake.CakeAdvertisers.FirstOrDefault(c => c.Advertiser_Id == offerAdvertiserID);
                    string offerAccountManager = offerAdvertiser.AccountManagerName;
                    if (offerAccountManager != null)
                    {
                        AccountManager am = eom.AccountManagers.ToList().SingleOrDefault(c => c.NameIsEquivalentTo(offerAccountManager));
                        if (am != null)
                        {
                            item.Campaign.account_manager_id = am.id;
                        }
                        else
                        {
                            AddIssue(new AccountManagerDoesNotExist(offerAccountManager));
                        }
                    }
                    else
                    {
                        AddIssue(new OfferHasNoAccountManager(item.Offer.OfferName));
                    }
                }
                // Set ad manager
                foreach (var item in newCampaigns)
                {
                    int offerAdvertiserID = int.Parse(item.Offer.Advertiser_Id);
                    var offerAdvertiser = cake.CakeAdvertisers.FirstOrDefault(c => c.Advertiser_Id == offerAdvertiserID);
                    string offerAdManager = offerAdvertiser.AdManagerName;
                    if (offerAdManager != null)
                    {
                        AdManager ad = eom.AdManagers.ToList().SingleOrDefault(c => c.NameIsEquivalentTo(offerAdManager));
                        if (ad != null)
                        {
                            item.Campaign.ad_manager_id = ad.id;
                        }
                        else
                        {
                            AddIssue(new AdManagerDoesNotExist(offerAdManager));
                        }
                    }
                    else
                    {
                        AddIssue(new OfferHasNoAdManager(item.Offer.OfferName));
                    }
                }
                return newCampaigns.Select(c => c.Campaign).ToList();
            }
        }
</code>```

答:
```
Is this an example of a pattern or an algorithm?
```

It's an algorithm.

A pattern is a generalized / portable approach to solving a problem.
An algorithm is a specific approach to solving a problem.

See this SO question: https://stackoverflow.com/questions/558657/whats-the-difference-between-an-algorithm-and-a-design-pattern

Body:
Is this an example of a pattern or an algorithm?

It's an algorithm.

A pattern is a generalized / portable approach to solving a problem.
An algorithm is a specific approach to solving a problem.

See this SO question: https://stackoverflow.com/questions/558657/whats-the-difference-between-an-algorithm-and-a-design-pattern


问:
"continue" and "break" for static analysis
I know there have been a number of discussions of whether break and continue should be considered harmful generally (with the bottom line being - more or less - that it depends; in some cases they enhance clarity and readability, but in other cases they do not).

Suppose a new project is starting development, with plans for nightly builds including a run through a static analyzer. Should it be part of the coding guidelines for the project to avoid (or strongly discourage) the use of continue and break, even if it can sacrifice a little readability and require excessive indentation? I'm most interested in how this applies to C code.

Essentially, can the use of these control operators significantly complicate the static analysis of the code possibly resulting in additional false negatives, that would otherwise register a potential fault if break or continue were not used?

(Of course a complete static analysis proving the correctness of an aribtrary program is an undecidable proposition, so please keep responses about any hands-on experience with this you have, and not on theoretical impossibilities)

Thanks in advance!

答:
I've used Coverity on a number of fairly large code-bases and not found the occasional use of break or continue to cause false positives.  However in most code-bases I've worked with break and continue have only been used lightly and generally only in fairly simple ways.

My concern with the use of break and continue would be code readability.  In general I suspect that static analysis tools cope better than people at dealing with their use.  I would discourage them for that reason, not for static analysis.

In practise I've found that code requiring either use of break and continue or excessive indention can probably be written in a better way anyway, although there are cases where it can significantly aid readability.


问:
Interpretation of DRY principle
Right now I'm struggling with this concept of DRY (Don't Repeat Yourself) in my coding. I'm creating this function in which I'm fearing it's becoming too complex but I'm trying to follow the DRY principle.

```<code>createTrajectoryFromPoint(A a,B b,C c,boolean doesSomething,boolean doesSomething2)
</code>```

This function I have say takes 3 input parameters, and then the function will do something slightly different given the boolean combinations doesSomething and doesSomething2. However the problem I'm having is that this function is growing in complexity greatly with every new boolean parameter that's added.

So my question is, is it better to have a bunch of different functions that share a lot of the same logic (therefore violating the DRY principle) or one function that behaves slightly differently given a number of parameters but making it much more complex (but preserving DRY)?

答:
boolean arguments to trigger different code paths in a single function/method is a terrible code smell.

What you are doing violates Loose Coupling and High Cohesion and Single Responsibility principles, which are much more important than DRY in precedence.

That means that things should depend on other things only when they have to ( Coupling ) and that they should do one thing and only one thing ( very well ) ( Cohesion ).

By your own omission, this is too tightly coupled ( all the boolean flags are a type of state dependency, which is one of the worst! ) and has too many individual responsibilities intermingled ( overly complex ).

What you are doing is not in the spirit of DRY anyway. DRY is more about repetition ( the R stands for REPEAT ). Avoiding copy and pasting is its most basic form. What you are doing isn't related to repetition.

Your problem is your decomposition of your code isn't at the correct level. If you think you will have duplicate code, then that should be its own function/method that is parameterized appropriate, not copy and pasted, and the others should be named descriptively and delegate to the core function/method.

Title: Interpretation of DRY principle


答:
You can have a list of ComboBox item and each ComboBox item have a list of associated spreadsheet items.

```<code>public class AssociatedComboItem
{
    public ComboItemType ComboItem{get;set;}
    public List<SSItem> Items{get;set;} // SpreadSheet items
}
</code>```

and then somewhere in your context, keep a list of AssociatedComboItem's to have all ComboBox items and their associated SpreadSheet items.

```<code>public List<AssociatedComboItem> Items{get;set;}
...
Items.Where(c=>c.ComboItem == someComboItem).FirstOrDefault(); // To get some comboItem reference

Items.Where(c=>c.Items.Contains(ss=>ss == someSpreadSheetItem)).FirstOrDefault(); // To find a ComboBox item which contains a specific SpreadSheet item
</code>```

Title: Looking for a good approach and data structure to solve this

Body:
C# WinForms:

A Combobox with some items in in.

A spread sheet with some items in it. Each row also has a check-box so users can select them.

User picks an items in the combobox and clicks a Save button. It means associate that Combobox item to those selected items in the spreadsheet.

Q1: What's a good structure I can use to keep track of which combobox item is associated with which items from the spreadsheet?

NOTE: User can also Move up or Mode Down the items in the spreadsheet. So it gets a little tricky here, they might have associated some items, then they change the order or those items but we still need to know what items are selected for each combobox item

Q2: What's a good approach to keep track of that?

Body:
You can have a list of ComboBox item and each ComboBox item have a list of associated spreadsheet items.

public class AssociatedComboItem
{
    public ComboItemType ComboItem{get;set;}
    public List<SSItem> Items{get;set;} // SpreadSheet items
}

and then somewhere in your context, keep a list of AssociatedComboItem's to have all ComboBox items and their associated SpreadSheet items.

public List<AssociatedComboItem> Items{get;set;}
...
Items.Where(c=>c.ComboItem == someComboItem).FirstOrDefault(); // To get some comboItem reference

Items.Where(c=>c.Items.Contains(ss=>ss == someSpreadSheetItem)).FirstOrDefault(); // To find a ComboBox item which contains a specific SpreadSheet item


答:
How will encapsulation help when making changes in code and from its rippling effects.

Let me give you a typical and simplistic example.
First, suppose you are not using encapsulation:
You have a set of data and use an array to store that data, and there is another part of your program that uses that array. Now, if at some point you decide that a linked list is a better choice for storing your data. If you replace array with linked list, what is going to happen? Your program will break, unless you make changes all over the place to replace the array-processing logic with linked-list-processing logic.

But, if you use OO/Encapsulation, then you probably partition your program into classes, one that store the data, and other, that uses the data. In the first class, you hide your implementation (encapsulation), and expose your services through methods like

```<code>size()
remove(int index)
add(int index, Object o)
get(int index)

...
</code>```

In this second case, if you change the implementation of the storing class from array to linked list, or to any other thing, it will not affect your clients. No ripple effect.

Title: How is encapsulation used for safety?

Body:
How will encapsulation help when making changes in code and from its rippling effects.

Let me give you a typical and simplistic example.
First, suppose you are not using encapsulation:
You have a set of data and use an array to store that data, and there is another part of your program that uses that array. Now, if at some point you decide that a linked list is a better choice for storing your data. If you replace array with linked list, what is going to happen? Your program will break, unless you make changes all over the place to replace the array-processing logic with linked-list-processing logic.

But, if you use OO/Encapsulation, then you probably partition your program into classes, one that store the data, and other, that uses the data. In the first class, you hide your implementation (encapsulation), and expose your services through methods like

size()
remove(int index)
add(int index, Object o)
get(int index)

...

In this second case, if you change the implementation of the storing class from array to linked list, or to any other thing, it will not affect your clients. No ripple effect.


答: DRY can be taken too far, its best to use the single responsibility principle (SRP) in conjunction with DRY. Adding bool flags to a function to make it do slightly different versions of the same code can be a sign you are doing too much with one function. In this case I would suggest creating a separate function for each case that your flags represent, then when you have each function written out it should be fairly apparent if there is a common section that can be moved to a private function without passing all the flags, if there isn't an apparent section of code, then you really aren't repeating yourself, you have several different but similar cases.</p>

Title: Interpretation of DRY principle

Body:
Right now I'm struggling with this concept of DRY (Don't Repeat Yourself) in my coding. I'm creating this function in which I'm fearing it's becoming too complex but I'm trying to follow the DRY principle.

```<code>createTrajectoryFromPoint(A a,B b,C c,boolean doesSomething,boolean doesSomething2)
</code>```

This function I have say takes 3 input parameters, and then the function will do something slightly different given the boolean combinations doesSomething and doesSomething2. However the problem I'm having is that this function is growing in complexity greatly with every new boolean parameter that's added.

So my question is, is it better to have a bunch of different functions that share a lot of the same logic (therefore violating the DRY principle) or one function that behaves slightly differently given a number of parameters but making it much more complex (but preserving DRY)?


答:
Why won't you create another function containing all the logic in your function before you decide to do something or something2 and then have three functions like :

```<code>createTrajectoryFromPoint(A a,B b,C c){...}

dosomething(A a, B b, C c){...}

dosomething2(A a, B b, C c){...}
</code>```

And now by passing three same parameter types to three different functions, you will be again repeating yourself, so you should define a struct or class containing A,B,C.

Alternatively you can create a class containing parameters A, B, C and a list of operations to be done. Add which operations(something, something2) you want to happen with these parameters (A,B,C) by registering operations with the object. Then have a method to call all registered operations on your object.

```<code>public class MyComplexType
{
    public A a{get;set;}
    public B b{get;set;}
    public C c{get;set;}

    public delegate void Operation(A a, B b, C c);
    public List<Operation> Operations{get;set;}

    public MyComplexType(A a, B b, C c)
    {
        this.a = a;
        this.b = b;
        this.c = c
        Operations = new List<Operation>();
    }

    public CallMyOperations()
    {
        foreach(var operation in Operations)
        {
            operation(a,b,c);
        }
    }
}
</code>```

Title: Interpretation of DRY principle

Body:
Why won't you create another function containing all the logic in your function before you decide to do something or something2 and then have three functions like :

createTrajectoryFromPoint(A a,B b,C c){...}

dosomething(A a, B b, C c){...}

dosomething2(A a, B b, C c){...}

And now by passing three same parameter types to three different functions, you will be again repeating yourself, so you should define a struct or class containing A,B,C.

Alternatively you can create a class containing parameters A, B, C and a list of operations to be done. Add which operations(something, something2) you want to happen with these parameters (A,B,C) by registering operations with the object. Then have a method to call all registered operations on your object.

public class MyComplexType
{
    public A a{get;set;}
    public B b{get;set;}
    public C c{get;set;}

    public delegate void Operation(A a, B b, C c);
    public List<Operation> Operations{get;set;}

    public MyComplexType(A a, B b, C c)
    {
        this.a = a;
        this.b = b;
        this.c = c
        Operations = new List<Operation>();
    }

    public CallMyOperations()
    {
        foreach(var operation in Operations)
        {
            operation(a,b,c);
        }
    }
}


答:
The fact that you are passing in booleans to make the function do different things is a violation of the Single Responsibility Principle.  A function should do one thing.  It should do one thing only, and it should do it well.

It smells like you need to split it into several smaller functions with descriptive names, separating the code paths corresponding to the values of those booleans.

Once you do that you should look for common code in the resulting functions, and factor it out into its own function(s).  Depending on how complex this thing is, you may even be able to factor out a class or two.

Of course, this assumes that you are using a version control system, and that you have a good test suite, so that you can refactor without fear of breaking something.

Title: Interpretation of DRY principle


答:
How will encapsulation help when making changes in code and from its
  rippling effects. For a data member, if I change its type from int to
  float, (even if I am exposing this using property) I will need to
  change variable type where I am using already using this code.

The benefit of encapsulation is that it lets you change the internal implementation without breaking client code. It doesn't protect you if you decide that you need to change the interface to your code, but that's a different matter.

Example: Say you have a value representing the price per unit of some commodity. The price is expressed in cents, and because you don't deal in fractional cents you decided to make the property an integer (I'll use C here because I'm not very familiar with C#):

```<code>int _price

int pricePerUnit(void) {
    return _price;
}

int priceForUnits(int units) {
    return units * _price;
}
</code>```

That all works out fine until one day when somebody notices that your firm is losing a lot of money due to rounding errors. Many of the commodities that you track are bought and sold in lots of many thousands of units, so you need to start tracking the price to an accuracy of at least 0.001 cent. Because you were smart enough to encapsulate the price instead of letting clients access it directly, you can make that change pretty quickly:

```<code>double _dprice

int pricePerUnit(void) {
    return (int)_dprice;
}

int priceForUnits(int units) {
    return (int)(units * _dprice);
}
</code>```

The interface that clients use to obtain prices stays the same, but the data they get back is now more accurate. If the price per unit is $1.001, priceForUnits(1000000) will now return a price that's $1000 greater than before. That happens even though you haven't changed the interface to your system at all, and you therefore haven't broken any client code.

Now, that may not always be all that you need to do. Sometimes you'll need to change or augment your interface so that you can report the price more accurately to clients, too:

```<code>double pricePerUnit() {
    return _dprice;
}
</code>```

A change like that will break client code, so you might instead keep the old interface and provide a newer, better routine:

```<code>int pricePerUnit() {
    return (int)_dprice;
}

double accuratePricePerUnit() {
    return _dprice;
}
</code>```

You and the rest of your team can then embark on the process of converting all the clients of your system to use the newer, better accuratePricePerUnit(). The client code will get more accurate as you make progress on that task, but even the old stuff should continue to work as well as it did in the past.

Anyway, the point is that encapsulation lets you change the way the internals work while presenting a consistent interface, and that helps you make useful changes without breaking other code. It doesn't always protect you from having to update other code, but it can at least help you do that in a controlled manner.

Title: How is encapsulation used for safety?

Body:
How will encapsulation help when making changes in code and from its
  rippling effects. For a data member, if I change its type from int to
  float, (even if I am exposing this using property) I will need to
  change variable type where I am using already using this code.

The benefit of encapsulation is that it lets you change the internal implementation without breaking client code. It doesn't protect you if you decide that you need to change the interface to your code, but that's a different matter.

Example: Say you have a value representing the price per unit of some commodity. The price is expressed in cents, and because you don't deal in fractional cents you decided to make the property an integer (I'll use C here because I'm not very familiar with C#):

int _price

int pricePerUnit(void) {
    return _price;
}

int priceForUnits(int units) {
    return units * _price;
}

That all works out fine until one day when somebody notices that your firm is losing a lot of money due to rounding errors. Many of the commodities that you track are bought and sold in lots of many thousands of units, so you need to start tracking the price to an accuracy of at least 0.001 cent. Because you were smart enough to encapsulate the price instead of letting clients access it directly, you can make that change pretty quickly:

double _dprice

int pricePerUnit(void) {
    return (int)_dprice;
}

int priceForUnits(int units) {
    return (int)(units * _dprice);
}

The interface that clients use to obtain prices stays the same, but the data they get back is now more accurate. If the price per unit is $1.001, priceForUnits(1000000) will now return a price that's $1000 greater than before. That happens even though you haven't changed the interface to your system at all, and you therefore haven't broken any client code.

Now, that may not always be all that you need to do. Sometimes you'll need to change or augment your interface so that you can report the price more accurately to clients, too:

double pricePerUnit() {
    return _dprice;
}

A change like that will break client code, so you might instead keep the old interface and provide a newer, better routine:

int pricePerUnit() {
    return (int)_dprice;
}

double accuratePricePerUnit() {
    return _dprice;
}

You and the rest of your team can then embark on the process of converting all the clients of your system to use the newer, better accuratePricePerUnit(). The client code will get more accurate as you make progress on that task, but even the old stuff should continue to work as well as it did in the past.

Anyway, the point is that encapsulation lets you change the way the internals work while presenting a consistent interface, and that helps you make useful changes without breaking other code. It doesn't always protect you from having to update other code, but it can at least help you do that in a controlled manner.


问:
How to avoid context switching while developing full stack web apps?
To give some context, I've been a Ruby & Rails developer for the past few years, and just recently started doing quite a lot of JavaScript to add more responsiveness to the apps.

When programming backend, it is quite easy (at least for me), to do most of the stuff test driven and just keep hammering out a bunch of code that works, while being able to focus.

But I found that as I'm moving more towards the frontend, I am constantly context switching. Some JavaScript is easy to test (models), but the parts that are directly connected to the GUI seem just impossible to reasonably test automatically.

This isn't as much of a deal when I first start with the GUI part with dummy data, but once it all gets connected, and the GUI is created based on data from a an external API and my machine is running two apps at the same time and I'm basically debugging both, it just seems like I'm constantly context switching, not really being able to focus on one thing.

An example here might be a Node.js chat server that connects to another Rails application via some API. Now if the API was already done and set in stone, I could easily just focus on the Node.js part ... but trying to do the whole thing in some agile fashion, I just built the API as I build the Node.js app, which has a side effect on working on both Rails and Node (both backed up by different databases etc, ...).

If I compare this to working on one small library or just some deep backend stuff, I find that my productivity basically non-existent, because I constantly switch around and find bugs in 50 different places, instead of just focusing on one.

Is there something that I'm fundamentaly doing wrong?

答:
If you don't want to context switch you should hand GUI development to someone else.

The problem you are having is pretty common if the front-end and back-end of a system is developed by the same person.

Also if you had all the requirement specifications, it would be easier to develop both parts separately, but of course you are talking about agile development.


问:
If you were the manager of a team of 25 developers, how would you motivate them?
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.

答:
Avoid the temptation to hire all 25
at once.

Try to attract known top developers
at the beginning.

Once you have a small team of very
talented people, who know what they
are doing and have established a
high-level of expectation.

Keep adding more people. They need to know that they are surrounded by good people who are willing to help them, but they have to keep up.

The less-talented (I'm not saying they suck, but these things are relative.) people will be able to achieve if put in the right environment (good people), are trained well, and supervised.

It's much easier to manage people when you get the right people and build culture and attitudes instead of trying to establish a bunch of rules.

ContentLicense: CC BY-SA 2.5


答:
An alternative approach is to replace the boolean parameters with interface parameters, with code to handle the different boolean values refactored into the interface implementations. So you would have

```<code>createTrajectoryFromPoint(A a,B b,C c,IX x,IY y)
</code>```

where you have implementations of IX and IY that represent the different values for the booleans. In the body of the function, wherever you have

```<code>if (doesSomething)
{
     ...
}
else
{
     ...
}
</code>```

you replace it with a call to a method defined on IX, with the implementations containing the omitted code blocks.

Title: Interpretation of DRY principle

Body:
An alternative approach is to replace the boolean parameters with interface parameters, with code to handle the different boolean values refactored into the interface implementations. So you would have

createTrajectoryFromPoint(A a,B b,C c,IX x,IY y)

where you have implementations of IX and IY that represent the different values for the booleans. In the body of the function, wherever you have

if (doesSomething)
{
     ...
}
else
{
     ...
}

you replace it with a call to a method defined on IX, with the implementations containing the omitted code blocks.


问:
Why do .NET modules separate module file names from namespaces?
In implementations of the Scheme programming language (R6RS standard) I can import a module as follows:

```<code>(import (abc def xyz))
</code>```

The system will try to look for a file $DIR/abc/def/xyz.sls where $DIR is some directory where you keep your Scheme modules. xyz.sls is the source code for the module and it is compiled on the fly if necessary.

The Ruby, Python, and Perl module systems are similar in this respect.

C# on the other hand is a little more involved.

First, you have dll files that you must reference on a per project basis. You must reference each one explicitly. This is more involved than say, dropping dll files in a directory and having C# pick them up by name.

Second, There isn't a one-to-one naming correspondence between the dll filename, and the namespaces offered by the dll. I can appreciate this flexibility, but it can also get out of hand (and has).

To make this concrete, it would be nice if, when I say this using abc.def.xyz;, C# would try to find a file abc/def/xyz.dll, in some directory that C# knows to look in (configurable on a per project basis).

I find the Ruby, Python, Perl, Scheme way of handling modules more elegant. It seems that emerging languages tend to go with the simpler design.

Why does the .NET/C# world does things in this way, with an extra level of indirection?

答:
It adds flexibility and allows to load the libraries (what you call modules in your question) on demand.

One namespace, multiple libraries:

One of the advantages is that I can easily replace one library by another. Let's say I have a namespace MyCompany.MyApplication.DAL, and a library DAL.MicrosoftSQL.dll, which contains all the SQL queries and other stuff which may be specific to the database. If I want the application to be compatible with Oracle, I just add DAL.Oracle.dll, keeping the same namespace. From now, I can deliver the application with one library for customers who need the compatibility with Microsoft SQL Server, and with the other library for customers who use Oracle.

Changing the namespace at this level would lead to either duplicate code, or the necessity to go and change all the usings inside the source code for each database.

One library, multiple namespaces:

Having several namespaces in one library is also advantageous in terms of readability. If, in a class, I use only one of the namespaces, I put just this one at the top of the file.

Having all the namespaces of a large library would be rather confusing both for the person who read the source code and for the writer herself, with Intellisense having too many things to suggest in a given context.

Having smaller libraries, one library per file would have a performance impact: each library must be loaded on demand in memory and processed by the virtual machine when running the application; less files to load means slightly better performance.


问:
What sorting algorithm does STL use?
I recently started using <vector.h> library and I was wondering, since all the operations are already implemented, IF the method of the sorting algorithm is the most efficient one. Everything runs perfect, there is no doubt, but should I worry about its performance?

If I want to sort up to 6-7 million numbers, should I implement my own sorting method using quick sort?

答:
It's hard to be definitive without knowing your use-case in detail, but as a general rule of thumb;

Don't optimise early

Implement the simplest, most readable and maintainable solution first, and then benchmark it.  Often it will be plenty fast enough.  You should only start worrying about optimisation when there is a problem, and when you have done enough benchmarking to know where the problem lies.

Title: What sorting algorithm does STL use?


答: It is unlikely you will be able to create a sort faster than std::sort in most cases. its even faster than the C qsort() in many cases.</p>

Title: What sorting algorithm does STL use?

Body:
I recently started using <vector.h> library and I was wondering, since all the operations are already implemented, IF the method of the sorting algorithm is the most efficient one. Everything runs perfect, there is no doubt, but should I worry about its performance?

If I want to sort up to 6-7 million numbers, should I implement my own sorting method using quick sort?


问:
Do DVCSes discourage continuous integration?
Say there is a team of ten agile developers. Every day they each pick a task from the board, commits several changes against it, until (by the end of the day) they have completed the task. All developers check in directly against trunk (Google-style, every commit is a release candidate, using feature toggles etc).

If they were using a centralized CVS like SVN, every time one of them commits, the build server will integrate and test their changes against the other nine developers' work. The build server will be pretty much running continuously all day.

But if they were using a DCVS like git, the developer may wait until they complete the task before pushing all their local commits together up to the central repository. Their changes will not be integrated until the end of the day.

In this scenario, the SVN team is continuously-integrating more frequently, and discovering integration problems much faster than the git team.

Does this mean DVCSs are less suitable for continuous teams than older centralized tools? How do you guys get around this deferred-push issue?

答: When my team switched to Git, we explicitly laid out our process such that a push was to be treated exactly like a commit in the older VCS, and local commits could be done as frequently/infrequently as each individual chose.  With that, there is no difference to the CI system whether we are using a DVCS or a centralized VCS.</p>


答:
In most libraries, std::sort is implemented as an introsort, so unless you want to hurt worst-case performance (a lot), you almost certainly do not want to use Quicksort instead. My experience indicates that a home-rolled Quicksort will rarely improve performance noticeably anyway.

The main reason to switch to something else would be to get something like stability (in which case you want std::stable_sort instead) or ability to work with data that won't fit in RAM (in which case you might want to look into STXXL), not for simple performance.

Title: What sorting algorithm does STL use?


答:
Sorting algorithms performs different based on your data collection's certain properties.

You say you just started using , so you won't likely to write faster sorting algorithms than people who created C++ and its libraries. Use standard libraries.

Title: What sorting algorithm does STL use?


问:
What do I need to do to NOT steal "Hello World" code with a GPL license?
In the project, I found a file, math.c, with a big GPL header and ...

```<code>//------------------------------------------------------------------------------
/// Returns the minimum value between two integers.
/// \param a  First integer to compare.
/// \param b  Second integer to compare.
//------------------------------------------------------------------------------
unsigned int min(unsigned int a, unsigned int b)
{
    if (a < b) {
        return a;
    }
    else {
        return b;
    }
}
</code>```

OK, cool so I need to get min value and ... this file!? So I need to open the whole project because of it? Or do I need to reinvent mathematics?

I don't believe it's just insane, so the question is: when we can just remove the GPL header?

Must I be a weirdo and do it?:

```<code>unsigned int min(             unsigned int
JEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE,
unsigned int hyrthrtRERG            ) {  if
(JEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE
< hyrthrtRERG            ) {  return JEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE;  }
else {return hyrthrtRERG            ;    } }
</code>```

Seriously, do they want me to write code like the above?

答:
If the code is really is trivial as the "min" example then there is a very high probability that someone else has already implemented the same functionality under a different open source license.

Depending on the license you may verywell be allowed to include the code in your closed source appliantion.


答:
It looks like you're choosing to overload the terminology of both "namespace" and "module." It shouldn't be any surprise that you see things as "indirect" when they don't fit your definitions.

In most languages that support namespaces, including C#, a namespace is not a module. A namespace is a way of scoping names. Modules are a way of scoping behavior.

In general, while the .Net runtime supports the idea of a module (with a slightly different definition than the one you are using implicitly), it's rather rarely used; I've only seen it used in projects built in SharpDevelop, mostly so that you could build a single DLL from modules built in different languages. Instead, we build libraries using a dynamically linked library.

In C#, namespaces resolve without any "layer of indirection" as long as they are all in the same binary; any indirection required is a responsibility of the compiler and linker that you don't have to give much thought to. Once you start building a project with multiple dependencies, you then reference external libraries. Once your project has made a reference to an external library (DLL), the compiler finds it for you.

In Scheme, if you need to load an external library, you have to do something like (#%require (lib "mylib.ss")) first, or use the foreign function interface directly, as I recall. If you're using external binaries, you have the same amount of work to resolve external binaries. Chances are you have mostly used libraries so commonly used that there's a Scheme-based shim that abstracts that from you, but if you ever have to write your own integration with a 3rd party library, you'll essentially have do some work to "load" the library.

In Ruby, Modules, Namespaces, and File Names are actually far less connected than you seem to assume; the LOAD_PATH makes things a bit complicated, and Module declarations can be anywhere. Python is probably closer to doing things the way you think you are seeing in Scheme, except that 3rd party libraries in C still add a (small) wrinkle.

Additionally, dynamically typed languages like Ruby, Python and Lisp typically don't have the same approach to "contracts" as statically typed languages. In dynamically typed languages, you usually only establish a sort of "Gentleman's agreement" that code will respond to certain methods, and if your classes appear to be speaking the same language, all is good. Statically typed languages have additional mechanisms to enforce these rules at compile time. In C#, using such a contract allows you to provide at least moderately useful guarantees of adherence to these interfaces, which allows you to bundle plugins and substitutions with some degree of guarantee of commonality because you all compile against the same contract. In Ruby or Scheme, you verify these agreements by writing tests that work at runtime. There are costs and benefits to either solution, but conflating the idea of a namespace, a module and a library won't help.

There is a measurable performance benefit from these compile time guarantees, as a method invocation requires no double dispatch. In order to get these benefits in something like Lisp, Ruby, JavaScript, or elsewhere, what are now still slightly exotic mechanisms of just-in-time statically compiling classes in specialized VMs is required.

One thing that the C# ecosystem still has relatively immature support for is the management of these binary dependencies; Java has had Maven for several years to deal with making sure you have all your requisite dependencies, whereas C# still has a fairly primitive MAKE-like approach that involves strategically placing files in the right place ahead of time.

Title: Why do .NET modules separate module file names from namespaces?

Body:
In implementations of the Scheme programming language (R6RS standard) I can import a module as follows:

```<code>(import (abc def xyz))
</code>```

The system will try to look for a file $DIR/abc/def/xyz.sls where $DIR is some directory where you keep your Scheme modules. xyz.sls is the source code for the module and it is compiled on the fly if necessary.

The Ruby, Python, and Perl module systems are similar in this respect.

C# on the other hand is a little more involved.

First, you have dll files that you must reference on a per project basis. You must reference each one explicitly. This is more involved than say, dropping dll files in a directory and having C# pick them up by name.

Second, There isn't a one-to-one naming correspondence between the dll filename, and the namespaces offered by the dll. I can appreciate this flexibility, but it can also get out of hand (and has).

To make this concrete, it would be nice if, when I say this using abc.def.xyz;, C# would try to find a file abc/def/xyz.dll, in some directory that C# knows to look in (configurable on a per project basis).

I find the Ruby, Python, Perl, Scheme way of handling modules more elegant. It seems that emerging languages tend to go with the simpler design.

Why does the .NET/C# world does things in this way, with an extra level of indirection?


问:
What do you do to make sure you take proper/enough breaks, while avoiding unwanted side-effects of break taking?
preamble>

It seems to me that computer programmers are one of a select few groups of people who actually take pleasure from sitting in front of computers for long periods of time. Most people in other professions actively dislike their time at computers, and do their best to avoid it (so, I assume, they don't have problems taking breaks). At least for me, having external cues for taking breaks, and clear instructions on what to do with each break (stretch, go for a walk, close my eyes, look into a distance of preferably a few km and focus on faraway objects, etc...), is a must.

So far, I've just been making up the breaks and tools to get them as I go along, based on what looks to be low-specificity information found on the net (generic stuff ala ergonomics advice for office staff). This has led to all sorts of side effects - loss of attention as I get distracted if I walk around, breaks in flow with alarm clocks interrupting my thoughts, and people around me assuming I'm low on work due to the frequency of my walking around compared to everyone else.

/preamble>

tl;dr

Taking breaks is important

My internal break taking system doesn't work, and ad-hoc ones have unwanted side effects

What do you do to make sure you take proper breaks?

How do you avoid unwanted side-effects, such as getting distracted or interrupting flow or giving your co-workers the impression you're spending a lot of time goofing off?

答:
Because the amount of time you can work productively for varies day-to-day, I take breaks on the following conditions:

"strong" hunger or thirst (though you should never really feel thirsty if you are hydrating / sipping water throughout the day)

need to use washroom

A "long" break (30 minutes to an hour) I usually use for physical exercise, and I take such breaks when:

1) I just finished fixing a bug, fleshing out a feature that I am proud of. I take the break as a reward

2) I am completely stumped and need to clear my head

I use the gym for #2 a lot.


问:
Why is Global State so Evil?
Before we start this, let me say I'm well aware of the concepts of Abstraction and Dependency Injection. I don't need my eyes opened here.

Well, most of us say, (too) many times without really understanding, "Don't use global variables", or "Singletons are evil because they are global". But what really is so bad about the ominous global state?

Let's say I need a global configuration for my application, for instance system folder paths, or application-wide database credentials.

In that case, I don't see any good solution other than providing these settings in some sort of global space, which will be commonly available to the entire application.

I know it's bad to abuse it, but is the global space really THAT evil? And if it is, what good alternatives are there?

答:
Languages that are designed for secure & robust systems design often get rid of global mutable state altogether.  (Arguably this means no globals, since immutable objects are in a sense not really stateful since they never have a state transition.)

Joe-E is one example, and David Wagner explains the decision thus:

Analysis of who has access to an object and the principle
  of least privilege are both subverted when capabilities are
  stored in global variables and thus are potentially readable
  by any part of the program. Once an object is globally available, it is no longer possible to limit the scope of analysis:
  access to the object is a privilege that cannot be withheld
  from any code in the program. Joe-E avoids these problems
  by verifying that the global scope contains no capabilities,
  only immutable data.

So one way to think about it is

Programming is a distributed reasoning problem.  Programmers on large projects need to divide up the program into pieces which can be reasoned about by individuals.

The smaller the scope, the easier it is to reason about.  This is true both of individuals and static analysis tools that try to prove properties of a system, and of tests that need to test properties of a system.

Significant sources of authority that are globally available make properties of the system hard to reason about.

Therefore, globally mutable state makes it harder to

design robust systems,

harder to prove properties of a system, and

harder to be sure that your tests are testing in a scope similar to your production environment.

Global mutable state is similar to DLL hell.  Over time, different pieces of a large system will require subtly different behavior from shared pieces of mutable state.  Solving DLL hell and shared mutable state inconsistencies requires large-scale coordination between disparate teams.  These problems would not occur had the global state been properly scoped to begin with.

Title: Why is Global State so Evil?


答:
I usually go through several steps with this problem, stopping when can't figure out how to go further.

First, do what you have done.  Go hard with DRY.  If you do not end up with a big hairy mess, you're done.  If, as in your case, you have no duplicate code but each boolean has its value checked in 20 different places, go to the next step.

Second, split the code into blocks.  The booleans are each referenced only once (well, maybe twice sometimes) to direct execution to the right block.  With two booleans, you end up with four blocks.  Each block is almost identical.  DRY is gone.  Do not make each block a separate method.  That would be more elegant, but putting all the code in one method makes it easier, or even possible, for anyone doing maintenance to see that they have to make each change in four places.  With well organized code and a tall monitor, the differences and mistakes will be almost obvious.  You now have maintainable code and it will run faster than the original tangled mess.

Third, try to grab duplicate lines of code from each of your blocks and make them into nice, simple methods.  Sometimes you can't do anything.  Sometimes you can't do much.  But every little bit you do moves you back towards DRY and makes the code just a bit easier to follow and safer to maintain.  Ideally, your original method might end up with no duplicate code.  At that point, you may want to split it into several methods without the boolean parameters or you may not.  The convenience of the calling code is now the main concern.

I added my answer to the large number already here because of the second step.  I hate duplicate code, but if it's the only intelligable way to solve a problem, do it in such a way that anyone will know at a glance what you are doing.  Use multiple blocks and only one method.  Make the blocks as identical as possible in names, spacing, alignments, ...everything.  The differences should then jump out at the reader.  It might make it obvious how to rewrite it in a DRY manner, and if not, maintaining it will be reasonably straightforward.

Title: Interpretation of DRY principle


问:
Design patterns: moving object references around an application
I'm new to Programmers and I am looking to increase my knowledge of programming. Recently, a user on Stack Overflow told me using singletons is a bad idea, that they encourage tight coupling and that they make testing harder.

What prompted this discussion was that every class I've ever written accessed any kind of data through a singleton. For example, a class that handles state data for a game. If any other class wanted to access this data, all they would have to do is get the singletons instance and there it would be. Specifically, instantiating a class on the AppDelegate, then accessing it via: [[[[UIApplication sharedApplication] delegate] gameObject] getScore].

The SO user told me that I should instantiate the 'gameObject' wherever I first need it, then pass that object to every other class that needs it via either a method as an argument, or via a property.

I was discussing these points when someone else pointed out that this information is completely wrong, that singletons are unrelated to coupling and that they do not affect testing at all.

I'm now completely confused as to which person is correct. Could someone please clarify which technique is best for an object to persist for the lifetime of the app, and be accessible to other classes, and also maintain loose coupling. To me, the object passing by method or property to each class seems the most logical, but I do not know!

Thanks in advance for any help!

答:
You won't ever know. Program design is about tradeoffs, and analyzing particular scenarios to produce a solution that is good (not best) given what you know about them. In this particular scenario, the singleton proponent is decidedly incorrect but you're missing the point.

In scenarios where the answer is less clear cut, you're going to need to be able to think things through yourself to judge what is a good or bad approach for the problem at hand. If you know what coupling is, and what a singleton is then you shouldn't really need to ask us. It's important to develop this skill for those many times when the particulars of the scenario mean we can't get you an answer.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I'm from Italy but I'm not sure what you're asking.

If you're talking about naming objects, yes, we do that in English. Usually students name their objects in Italian for learning purposes. But personally I find it difficult and prefer to use English, since some technical terms are extremely awful in Italian.


答:
The following annotation in the Framework Design Guidelines Section 3.3. Names of Assemblies and Dlls offers insight into why namespaces and assemblies are separate.

BRAD ABRAMS Early in the design of the CLR we decided to seperate the
  developer view of the platform (namespaces) from the packaging and
  deployment view of the platform (assemblies). This separation allows
  each to be optimized independently based on its own criteria. For
  example, we are free to factor namespaces to group types that are
  functionally related (e.g., all the I/O stuff in System.IO) while the
  assemblies can be factored for performance (load time), deployment,
  servicing, or versioning reasons.


答:
At the end of the day, you have to do what makes the most sense you you.  Singletons are fine.  If they've worked for you, use them.

The problem with them is that you may need more than one of them someday.  Your game program may want to juggle two or more games at the same time.  Then you have track down every reference to your GameObject and replace it with something more elaborate.  The cost of allowing multiple gameObjects from the start is a lot less than retro-fitting the capability later and only slightly more than sticking with a singleton GameObject for the whole life of the program.

If you are certain you will never have multiple games, it's cheaper to go with the singleton.  (Although avoiding them might help improve your programming skills--it might be good practice for times when you can't use singletons.)  Personally, I've spent enough time getting rid of singletons in my code that I'll avoid them now at all costs.

In your case, singletons are not related to coupling and do not affect testing at all (other than the complete retesting you have to do after removing them).

However, if your code responded to web HTTP requests, and hence might run in hundreds of threads simultaneously, accessing singletons (and, for that matter, any data visible to more than one thread) becomes very tricky.  If you don't understand multi-threading programming real well, you are going to cause a major train wreck.  The values in the singleton will change at any time.  Bugs will be unrepeatable, because they depend on the precise timing of several threads.  Reliable testing becomes impossible.

There are a lot of people doing this kind of programming.  They don't understand multi-threading.  And the people who have to clean up after them feel very strongly that they should not use singletons.  This is what the user on SO is talking about.  (I think he was advising you to create a new gameObject for each individual HTTP request.) I doubt this is relevant to you, but it helps to know what everyone is talking about.

Title: Design patterns: moving object references around an application

Body:
I'm new to Programmers and I am looking to increase my knowledge of programming. Recently, a user on Stack Overflow told me using singletons is a bad idea, that they encourage tight coupling and that they make testing harder.

What prompted this discussion was that every class I've ever written accessed any kind of data through a singleton. For example, a class that handles state data for a game. If any other class wanted to access this data, all they would have to do is get the singletons instance and there it would be. Specifically, instantiating a class on the AppDelegate, then accessing it via: [[[[UIApplication sharedApplication] delegate] gameObject] getScore].

The SO user told me that I should instantiate the 'gameObject' wherever I first need it, then pass that object to every other class that needs it via either a method as an argument, or via a property.

I was discussing these points when someone else pointed out that this information is completely wrong, that singletons are unrelated to coupling and that they do not affect testing at all.

I'm now completely confused as to which person is correct. Could someone please clarify which technique is best for an object to persist for the lifetime of the app, and be accessible to other classes, and also maintain loose coupling. To me, the object passing by method or property to each class seems the most logical, but I do not know!

Thanks in advance for any help!


答:
The part that creates coupling isn't the fact that the variable lives in a singleton, but that your client object goes and fetches it from there itself.  This means that you could never change the way your object is stored without introducing all kinds of hassle for yourself (assuming, as you say, that many objects behave this way).

Consider what would happen, for example, if you decided you wanted your program to be MDI (multi-document interface) so the user could play more than one game at once.  Since your entire program accesses this singleton, you've pretty much screwed yourself.

On the other hand, you can store the game in the singleton and then inject it into objects that need to access it.  Look up Dependency Injection.  I don't know why you'd have a singleton at that point but maybe it wouldn't be completely pointless.

Basically, they're both right.


问:
Why is 80 characters the 'standard' limit for code width?
Why is 80 characters the "standard" limit for code width? Why 80 and not 79, 81 or 100? What is the origin of this particular value? </p>

答: A related question is "why has 80 column persisted". Even the responses on this page are approximately that width. I agree with the historical reasons for 80 columns, but the question is why the standard has persisted. I would claim readability - for prose and code. Our minds can only absorb so much information in one piece. I still use the 80 column marker in my code editor to remind me when a statement is getting too long and obscure. It also leaves me plenty of screen real-estate for the browser, and the supporting IDE windows. Long live 80 column - as a guide not a rule.</p>


问:
Patterns for integrating with a slow external service
Was hoping someone could provide some patterns/techniques/ideas to increase performance for the following scenario.

Am integrating with an external ordering system via SOAP. The external system can be slow and unfortunately nothing can be changed at that end.

All products are retrieved from this external source and an order is only placed with the external system when they've paid so cart functionality will be implemented locally.

When a item is added to the cart, it will check the external source if there's enough stock and then add the item to the cart locally, and the user will stay on the same page (eg. wont' redirect to a cart summary screen). It will also check the rest of the items in their cart to ensure there is enough stock, so depending on how many items they have there could be a lot of calls to the external source.

I guess, could only check the stock levels for other items in their cart when they get to the checkout summary screen and subsequent checkout screens but i feel that isn't the best user experience.

For reference, local site will be using ASP.NET MVC3

Any suggestions?

Thanks

答:
If you're going to be making a lot of calls to check the stock levels every time an item is added, that would imply the stock levels would change very quickly - it's worth looking at some statistics to see if this is actually necessary.

If it's not, you could create a simpler solution with a local store of the stock levels that gets updated by another process every 10 minutes (for example) - even better if you can get the external party to publish the stock list and you can just subscribe, but it doesn't sound like you've got much control over them.

You could then do a check against the external service to ensure stock is there before taking payment, process the payment and submit the order.