问:
How do browsers do CSS caching and why only .alert or .danger but not .alert.danger?
I read about BEM & OBCSS here and somewhere the author mentioned this:

Decoupling selector will not only increase maintainability and scalability: it will speed up the rendering. Most web browsers are caching first-level selectors. .alert and .danger will be cached but not .alert.danger!

How in particular are browsers caching these rules and why only rules with lower specificity?

I'm curious because I didn't know browsers actually cache CSS rules.
Can someone give a reasonable explanation about CSS caching?

Is the speed notable for huge amounts of CSS?

答:
I think he's referring to the browser implementation's tendency to cache the look-up of elements with a specific class. That is they keep a list of all the elements for each class. You'll often see comments about caching selectors for performance reason for long selectors. (Usually just telling the programmer not to query for the same thing multiple times in JQuery if it's expensive). It's really not something one has to think about in regards to styling though. When you insert a new node into the DOM the look-ups are fairly quick.

Depending on the page though it actually can be noticeable with Javascript queries. I've written documentation generation like software that used a lot of repetitive classes and querying complex selectors. I accidentally duplicated the same selector inside of a for loop and the program chugged until I pulled it outside of the loop. Have to use some common sense and understand that a selector look-up might be doing some work behind the scenes to match all the elements.

I'd imagine, if it's true that CSS selectors aren't memoized past the first class, that it's done for memory reasons. Storing lists of all the elements that match specific CSS rules and keeping track of them when elements are added and removed could potentially eat up a lot of memory and needless CPU on small devices. (Potentially for very little gain if the queries are infrequent).

Also every browser can implement things anyway it wants under the hood. MDN has this article: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS on some best practices. It's possible other browsers have their own guides.


问:
@Qualifier and Dependency Inversion Principle
I recently discovered SOLID principles and i'm trying to learn how to properly apply them. I have an application that had a huge interface:

```<code>public interface NotificationService {
  public void sendNewProjectRequestNotificationToDesigners(String projectId);
  public void sendNewProjectAcceptedNotificationToCustomer(String projectId);
  public void sendNewProjectRejectedNotificationToCustomer(String projectId);
  ...
  // and aboud 30 more methods like that
  // specifying the type of notification and who is going to be sent to
}
</code>```

This clearly violates:

SRP: so many different kind of notifications

OCP: Every new notification i just modified the class

ISP: In every single class that injects a NotificationService, will only want 1 of all the methods.

DIP: The clients of this class need to be aware of the exact method to use.

so i began my refactoring and came up with:

```<code>public interface NotificationSender {
  public void sendNotification(String projectId);
}

public class NewProjectRequestNotificationSender implements NotificationSender {
  public void sendNotification(String projectId) {
    ...
  }
}

// and many other classes, one for each method in the original interface
</code>```

Now to apply Dependency Injection, i declared each class that implements NotificationSender as a @Bean with a qualifier name.

And the classes that require a specific notification sender, the dependency is injected with @Qualifier.

Question 1: By having to use @Qualifier in the clases that require a specific NotificationSender, hence these clases are still forced to know details like the qualifier name of the given NotificationSender, am i still violating Dependency Inversion Principle?

Question 2: Is there a better approach?

答:
No, the qualifiers are just a hint to your dependency injection system. They're more configuration than code. You are still accessing the beans only though the NotificationSender interface, so your code doesn't know any more about the implementation details of the different instances.

Imagine you were unit testing a bean that used a qualified NotificationSender injection. You could pass it any NotificationSender you liked (a mock, perhaps). Outside the DI framework, your code couldn't care less what implementation you give it!

ContentLicense: CC BY-SA 3.0


问:
Making a security on webapi for browser usage
I have a webapi project working in production for few months now.

The entire webapi is server to server.

There is a need now to have the same functionality in a browser, meaning the customers can invoke via ajax functions directly on the webapi server.

Since the webapi is stateless and session usage is not really recommended, what are my options here?

Today (server to server), every request reaching the server has user and pass, and on every request there is a login check (not that efficient, I know).

What happens when the same rest webapi needs to go to the browser and have security?

答: One option is to add authentication to your webapi server. Another option is you may already have a web server with authentication that is related to this webapi server. If so, you can use this server as a proxy to the webapi server, possibly using a facade pattern to simplify the interaction (https://en.wikipedia.org/wiki/Facade_pattern).</p>


问:
Designing around shallow constness with inheritance

Background

I'm writing an image handling class. For this question two requirements of the class are of interest:

Must have "deep" const correctness.

Must allow sub-image aliases, a.k.a. sections or slicing without performing deep copies of image data.

By deep constness I mean the following. Consider this example class:

```<code>class Image{
public:
    ...
    Image(const Image&);

    Image alias(int x0, int y0, int x1, int y1) const;
private:
    Buffer image_data;
};
</code>```

And assume you have a function that is passed a const reference to a image, like so:

```<code>void foo(const Image& im){
    Image alias = im.alias(0,0, 10, 10);
    // Hold on, the mutable alias can modify the data in the const argument!
}
</code>```

The above alias function call defeats the constness of the argument because the contents of the argument image can be modified through the non-const alias. I can't return a const Image from alias because well that makes no sense really and the copy constructor of Image will happily construct a mutable instance anyway.

My solution (and I've seen it used often so I don't claim originality here) is to introduce two classes (interfaces really, but for the simplicity they are classes in this example and return by value is okay, in reality alias(...) returns a shared_ptr to interface):

```<code>class ConstImage{
public:
    ConstImage alias(...) const;
};

class Image{
public:
    Image alias(...);
};
</code>```

Now the following code:

```<code>void foo(const Image& im){
    // compile error, cannot convert ConstImage to Image, perfect!
    Image alias = im.alias(...);
}
</code>```

And of course you would change the signature to void foo(const ConstImage& im) so that you can accept invocations like foo(const_im.alias(...)) or other ConstImage objects.

Now of course we want foo(const ConstImage& im) to be callable (1) with a mutable Image too and here is where the question comes in.

Question

Using inheritance: class Image : public ConstImage will make all Image types usable through ConstImage references and pointers. It will also facilitate code-reuse between the const and non-const implementations which by necessity are very similar.

This solves the above mentioned problem (1). However if you look at the inheritance relation as an "is a" statement then "a mutable image IS AN immutable image" makes no sense. Which speaks against using inheritance here.

My question is, is this kind of (ab)use of inheritance widely acceptable? Is there some other better solution that I have overlooked? Note that the Image class is more of an interface so naive value conversion from Image to ConstImage isn't possible. Although one could probably come up with something crazy to allow it.

答:
If you accept that Const just means "won't be manipulated from here", as most of your question seems to imply, a const_image isn't immutable.

Seems like your class is a smart-pointer with extra accessors and (if non-const) manipulators.

You might benefit from basing it on std::shared_ptr.

Next, to emulate deep-const, your Image-class needs to do the following:

Ensure a const instance lacks manipulators.

That's easily done, just make sure no manipulator-method is const-qualified, and all inspector-methods are.

```<code>int getX() const; // inspector
void setX(int);   // manipulator
</code>```

Ensure a const instance does not expose any non-deep-const internal state.

Any inspector-method only returns const-qualified references or equivalent pointers, and only for state which itself emulates deep-const, or does not have any linked state.

Naturally deep-copies may always be returned. (Deep-copies and Shallow copies are trivially equivalent for state without internal links.)

Ensure a non-const instance cannot be constructed from a const instance.

Now this last point looks like a back-breaker, as C++ unfortuately does not allow making a constructor const.

Fortunately, we can get around that with more code: Just declare a second class.

```<code>struct image;
struct const_image {
    // ctors, dtor, const inspectors
    // no manipulators, and only expose as const_image, other deep-const type or deep-copy
private:
    friend class image;
    // explicitly defaulted (move-)assignment-operators
    // Whatever members are neccessary to maintain the data.
    // Probably only a single shared_ptr and some indices
};

struct image : const_image {
    // delegating ctors for all but copy-construction and move-constructor
    // copy-ctor accepting a non-const image, probably defaulted
    // move-constructor, (move-)assignment-operators
    // additional non-const inspectors (where possible a thin mask over the const ones)
    // these all return Image or manipulatable internal state
    // manipulators
private:
    // if neccessary, optional additional state for supporting manipulation-operations
};
</code>```

Body:
If you accept that Const just means "won't be manipulated from here", as most of your question seems to imply, a const_image isn't immutable.

Seems like your class is a smart-pointer with extra accessors and (if non-const) manipulators.

You might benefit from basing it on std::shared_ptr.

Next, to emulate deep-const, your Image-class needs to do the following:

Ensure a const instance lacks manipulators.

That's easily done, just make sure no manipulator-method is const-qualified, and all inspector-methods are.

int getX() const; // inspector
void setX(int);   // manipulator

Ensure a const instance does not expose any non-deep-const internal state.

Any inspector-method only returns const-qualified references or equivalent pointers, and only for state which itself emulates deep-const, or does not have any linked state.

Naturally deep-copies may always be returned. (Deep-copies and Shallow copies are trivially equivalent for state without internal links.)

Ensure a non-const instance cannot be constructed from a const instance.

Now this last point looks like a back-breaker, as C++ unfortuately does not allow making a constructor const.

Fortunately, we can get around that with more code: Just declare a second class.

struct image;
struct const_image {
    // ctors, dtor, const inspectors
    // no manipulators, and only expose as const_image, other deep-const type or deep-copy
private:
    friend class image;
    // explicitly defaulted (move-)assignment-operators
    // Whatever members are neccessary to maintain the data.
    // Probably only a single shared_ptr and some indices
};

struct image : const_image {
    // delegating ctors for all but copy-construction and move-constructor
    // copy-ctor accepting a non-const image, probably defaulted
    // move-constructor, (move-)assignment-operators
    // additional non-const inspectors (where possible a thin mask over the const ones)
    // these all return Image or manipulatable internal state
    // manipulators
private:
    // if neccessary, optional additional state for supporting manipulation-operations
};

ContentLicense: CC BY-SA 4.0


问:
Asp.net MVC web application and iOS mobile app
I am currently writing a web application in ASP.NET MVC, so far it is mostly a simple CRUD web app. The database is hosted on the cloud and I am using Entity Framework to interact with it.

I know that further in the development cycle we will have to make a mobile application (iOS with swift) which will interact with the same database, so I want to have a good framework that will be able to handle both without too much duplication of code or DAL, while still being secure.

Those are the options I have so far:

Write my MVC web application and further down the line, make http requests to my controllers action from my app. Possible problems: Security and authentications of those calls?

Write my MVC web application and a MVC Web API. Both my controllers of my web app and the iOS app will interact with this API. Possible problems: Will this setup work with the asp.net MVC web app?

Write additional web methods in my MVC controllers specifically for the REST api call of my iOS app. Possible problems: Is it possible at all?

答: The best way for iOS to communicate with your database is with REST (or JSON).  So your third option is the best.  Your .NET web application can easily also include web service commands that allow the JSON iOS app Set and Get the data.</p>


问:
Is this avoiding inheritance correctly?
I want to add capabilities for an abstract Model class to send events whenever it updates. To be able to send events, it needs to have access to an EventManager. So, the intent were first, to be able to handle events (e.g. save operation) and second to send Events to the system event handler.

My approach is to implement a new interface EventManagerAware in ExistingModel class, which needs this behaviour, like this:

interface EventManagerAware {

    public function handleEvent(EventManager em);
}

class ExistingModel extends Model implements EventManagerAware {

    public function handleEvent(EventManager em) {
        em.sendEvent(Event::SAVE);
    }
}

abstract class Model() {

    public function save() {

        if (this instanceOf EventManagerAware) {
            this.handleEvent(this.getServiceManager().getEventManager());
        }
}
```

<p>After review, someone argued that it's better to just extend the <code>Model</code> class, override the <code>save()</code> method and change <code>ExistingModel</code> from extending <code>Model</code> to <code>EventPublisherModel</code> class, like so:</p>

<pre class="lang-java prettyprint-override"><code>class EventPublisherModel extends Model {

    public function save() {
        this.getServiceManager().getEventManager().sendEvent(Event::SAVE);
    }
}

class ExistingModel extends EventPublisherModel {

}
</code>```

FYI, the existing Model class looks like this:

abstract class Model {
    protected ServiceManager serviceManager;

    public function __construct(ServiceManager sm) {
        this.serviceManager = sm;
    }

    public function getServiceManager() {
        return this.serviceManager;
    }

    public function save() {

    }
}
```

One of the arguments put for having EventPublisherModel class was because doing in the first approach, all Model objects would check for EventManagerService when doing save() operation, and that's unnecessary.

I've never really thought about why the first approach would be better, but did think that it I have Segregated the Interface and didn't think inheritance is needed because sending events is in different domain from the Model class.

Which is the best way of doing this and why?

答:
Which way is best depends on your needs.  With the first way, each class will have identical, or nearly identical, code for handling events.  This causes code duplication.  Each class can easily handle the events in its own way.  It is possible to add event manager awareness further along the inheritance chain.  Another negative is the type check for every Model based class in save.

In the second way the code for handling events is in one place.  You don't need to add it to every class.  Types that don't need event handling are unaffected by it.  Models that need custom event handling can create their own implementation of save.  Event manager awareness will need to be added to classes at the point they derive from Model.  Overall the code will be simpler and easier to maintain.

In summary, the second (EventPublisher) way is usually the way to go.

Title: Is this avoiding inheritance correctly?


问:
What to do when properties of a HashMap and ArrrayList are neccessary?
I have a data structure that stores various permission groups for a multiplayer game server. There is an instance of a "Rank" class for each permission group. Each rank also has a name. I need to be able to access all of the ranks both in a Iterable fashion and with a key.

There are three main ways I can think of doing this. I don't know which one is best as they all have pros and cons. The first method could have a significant performance impact as the getRank(String) method will be called quite often with anywhere from about 2-50 ranks. The second method could also be problematic as there are several instances, although not nearly as common, where it is useful to have such a method with high performance. The third method could be problematic if the list and map ever get out of sync, especially since it needs to be thread-safe.

I would like to know which method is best and why. My primary concern is that it is both reliable and performant.

Method #1

```<code>public synchronized Rank getRank(String name) throws IllegalArgumentException{
    for(Rank rank : ranks){
        if(rank.getName().equalsIgnoreCase(name)){
            return rank;
        }
    }

    throw new IllegalArgumentException("Rank: " + name + " does not exist!");
}
</code>```

Method #2:

```<code>public synchronized List<Ranks> getRanks(){
    ArrayList<Ranks> ranksList = new ArrayList<Ranks();

    for(String rankName : ranksMap.keySet()){
        ranksList.add(ranksMap.get(rankName));
    }

    return Collections.unmodifiableList(ranksList); //unmodifiableList to prevent someone from trying to add or remove ranks by editing this list
}
</code>```

Method #3:

```<code>public class RankList{
    private ArrayList<Rank> list = new ArrayList<>();
    private Map<String, Rank> map = new HashMap<>();

    public void add(Rank rank){
        list.add(rank);
        map.put(rank.getName().toLowerCase(), rank);
    }

    public List<Rank> getRanks(){
        return Collections.unmodifiableList(list);
    }

    public Rank get(String name){
        return map.get(name.toLowerCase());
    }

}
</code>```

答:
If you order elements by insertion order, you can use Java's LinkedHashMap

You will not be able to view it as a list, but you can easily siphon data into a temporary list and return that list. From there you can sort it if necessary.

You can also use a SortedMap (TreeMap is its standard implementation) if you want to have the map in a specific order. You can return a list view the same way, copying data into a list via iterator.

Member variable declaration would be one of the following:

```<code>// Need insertion order
private Map<String, Rank> map = new LinkedHashMap<>();
// Need key order or some other order (can pass in comparator)
private Map<String, Rank> map = new TreeMap<>();
// Do not care about order.
private Map<String, Rank> map = new HashMap<>();
</code>```

You would return the list one of these ways:

```<code>// Using map order or do not care about order.
public List<Rank> getRanks() {
  return new ArrayList<Rank>(map.values());
}

// Using some other order.
public List<Rank> getRanks() {
  List<Rank> values = new ArrayList<Rank>(map.values());
  Collections.sort(values); // can pass in comparator
  return values;
}
</code>```

NB: I know you said order does not matter, but I am covering all the bases for other readers who might find this information useful.

See also:

Ordered List Map implementation in Java

How to convert a Map to List in Java?

Body:
If you order elements by insertion order, you can use Java's LinkedHashMap

You will not be able to view it as a list, but you can easily siphon data into a temporary list and return that list. From there you can sort it if necessary.

You can also use a SortedMap (TreeMap is its standard implementation) if you want to have the map in a specific order. You can return a list view the same way, copying data into a list via iterator.

Member variable declaration would be one of the following:

// Need insertion order
private Map<String, Rank> map = new LinkedHashMap<>();
// Need key order or some other order (can pass in comparator)
private Map<String, Rank> map = new TreeMap<>();
// Do not care about order.
private Map<String, Rank> map = new HashMap<>();

You would return the list one of these ways:

// Using map order or do not care about order.
public List<Rank> getRanks() {
  return new ArrayList<Rank>(map.values());
}

// Using some other order.
public List<Rank> getRanks() {
  List<Rank> values = new ArrayList<Rank>(map.values());
  Collections.sort(values); // can pass in comparator
  return values;
}

NB: I know you said order does not matter, but I am covering all the bases for other readers who might find this information useful.

See also:

Ordered List Map implementation in Java

How to convert a Map to List in Java?


答:
Have you considered refactoring your interface to something like:</p>

```<code>public interface NotificationSender {
  public void sendNotification(NotificationEvent event);
}

public final class NotificationEvent {
    private final NotificationKind type;
    private final String projectId;

    ...
}

public enum NotificationKind {
    REQUESTED, ACCEPTED, REJECTED, ...;
}
</code>```

Title: @Qualifier and Dependency Inversion Principle

Body:
I recently discovered SOLID principles and i'm trying to learn how to properly apply them. I have an application that had a huge interface:

```<code>public interface NotificationService {
  public void sendNewProjectRequestNotificationToDesigners(String projectId);
  public void sendNewProjectAcceptedNotificationToCustomer(String projectId);
  public void sendNewProjectRejectedNotificationToCustomer(String projectId);
  ...
  // and aboud 30 more methods like that
  // specifying the type of notification and who is going to be sent to
}
</code>```

This clearly violates:

SRP: so many different kind of notifications

OCP: Every new notification i just modified the class

ISP: In every single class that injects a NotificationService, will only want 1 of all the methods.

DIP: The clients of this class need to be aware of the exact method to use.

so i began my refactoring and came up with:

```<code>public interface NotificationSender {
  public void sendNotification(String projectId);
}

public class NewProjectRequestNotificationSender implements NotificationSender {
  public void sendNotification(String projectId) {
    ...
  }
}

// and many other classes, one for each method in the original interface
</code>```

Now to apply Dependency Injection, i declared each class that implements NotificationSender as a @Bean with a qualifier name.

And the classes that require a specific notification sender, the dependency is injected with @Qualifier.

Question 1: By having to use @Qualifier in the clases that require a specific NotificationSender, hence these clases are still forced to know details like the qualifier name of the given NotificationSender, am i still violating Dependency Inversion Principle?

Question 2: Is there a better approach?

Body:
Have you considered refactoring your interface to something like:

public interface NotificationSender {
  public void sendNotification(NotificationEvent event);
}

public final class NotificationEvent {
    private final NotificationKind type;
    private final String projectId;

    ...
}

public enum NotificationKind {
    REQUESTED, ACCEPTED, REJECTED, ...;
}


问:
Copying/cloning MongoDB database from production to development
I am struggling to find a good way to copy over our production MongoDB database to overwrite our development database on demand. db.copyDatabase doesn't work from the command line using mongo-cli. Is there a better way to clone a database and overwrite a current one with Mongo?</p>

答:
You could use a shell script to do that using the mongodump and mongorestore tools.

What I do for this same scenario is to use the --eval option from the mongo-cli to drop the database, take a dump of the production database and then restore to the development database.

ssh user@host 'mongodump --host dbhost --port dbport --db dbproduction; cd dump ; zip dump.zip dbproduction/* ;'

scp user@host:dump/dump.zip /desiredPath/dump.zip ;

mongo --eval 'new Mongo().getDB("dbdevelopment"); db.dropDatabase();'

unzip dump.zip -d dump ; cd dump/ ;

mongorestore --db dbdevelopment dbproduction;

This will need to run from the development database's server with access to the production databases's server and it will do exactly what you need it to: dump and zip the production database, download it, drop the development database, unzip the downloaded file, and restore.


问:
Where to do post-processing of API call when used in MobileApp
Let's say I want to write an (iPhone) app, which tells you if you are in manhattan or not. This query involves additional computation after a google map API call (and is of course just an example).

My question is where would you do this additional computation?

On the App itself or on an application server?
And in latter case, how would you communicate with the server?

Would a REST api be appropriate for such a scenario? Here one could post latitude and longitude and receive a boolean indicating if one is inside or outside of manhattan.

答:
Of course this depends a lot on the actual job that needs to be done. But lets assume you need to find out if you are in Manhattan and you have queries google maps for the current location.

From google maps I believe it is possible to get the city name as well, but assuming we only have GPS coordinates, we would need to make an additional API call or implement some logic on the phone. In this case you want the phone to handle all API calls, this API call can be a call to your own REST implementation, in that case you handle the am I in  Manhattan? query at the server side. But if it is easy enough to handle this job at the phone, with this example that is the case, you should do it at the phone.

If you need to do work after receiving data from an API on the phone, it is best to perform this on a separate thread (that you have anyways during the internet request). After completely processing the data on the phone you can update the user interface accordingly.

Nowadays it is better to give as much work to the phone, and only use the server for communication and data synchronization. This keeps the server load at a minimum and distributes the work to all devices, which makes your setup extremely scalable.
If you query your server to do most of the job and you have a few million phone users, you will kill your bandwidth.

In short: As long as the job is douable whitin reasonable time on the device, do it on the device. If it is too complex, memory or time wise, create a REST api and perform it on the server.


问:
What uses does Smalltalk’s ‘become:’ have?
The become: message in Smalltalk causes one object to change into another, affecting all references to it.

What uses does this language feature have? Does it get used in real code? Is it just a curiosity? Is it considered a good/bad practice to use it?

答: It is not used a lot. In the Pharo 5 image I have open, there are 9 senders of #become:, 7 of which are in unit tests. It is used in the compiler in code generation and in the Fuel serialization library to replace proxies by their content.</p>


问:
What does the prefix "on" in a function (e.g."onButtonPressed") mean?
Sometimes I'll see some functions use "on" as a prefix, for example, on a button listener:

```<code>onButtonPressed();
</code>```

and there are other examples:

```<code>onStateChanged();
onNotified();
onResume();
</code>```

Does the prefix "on" have an implied semantic meaning behind it?

答:
Prefix "on" is most often used to indicate that method is intended to be used as a callback, i.e. not called directly, but set as a handler for some event.

For example, when you write method named onClick, you probably won't call it directly, but rather expect that GUI toolkit will call it once user clicks a button.


答:
It's just one of the many meanings of the English word word "on", used as a preposition.  It indicates when the action occurs.  So onButtonPressed() is called when the button is pressed.

The function could be re-named whenButtonPressed(), but that's longer and not idiomatic

Title: What does the prefix "on" in a function (e.g."onButtonPressed") mean?

Body:
Sometimes I'll see some functions use "on" as a prefix, for example, on a button listener:

```<code>onButtonPressed();
</code>```

and there are other examples:

```<code>onStateChanged();
onNotified();
onResume();
</code>```

Does the prefix "on" have an implied semantic meaning behind it?


问:
Meaning of using getters and setters and Uses of parameterized Constructor.
I am using getters and setters to for the purpose of encapsulation.

```<code>public class Student {

    private String studentID;
    private String studentName;
    private String address;

    public Student(){
        //default constructor
    }

    public Student(String studentID, String studentName, String address) {
        super();
        this.studentID = studentID;
        this.studentName = studentName;
        this.address = address;
    }

    public String getStudentID() {
        return studentID;
    }

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getAddress() {
        return address;
    }

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

the variables studentID, studentName and address are declared as private, with the intention of encapsulation.

but we could also do the same task by making the variable accessibility level from private to public, is it really helps to apply encapsulation by the use of setters and getters?

only I can understand the use of getter and setter is users of the class dows not need to have an idea about the names of the variables used in the class as setters and getters makes sense to the users of the class

ex- objectofStudentClass.setStudentID("S0001");

Is there any difference between main difference between making getters and setters instead if making the variable access level to public.

Question 2:
also here I have made parameterized constructor matching to the variables/fields in the class Student. is that  throw away the concept of encapsulation?

答:
Yes, there is a huge difference.

Having getters and setters allows you to change their implementation (for instance, to add range checking, audit logging, statistics updates etc.) in the future without having to change all client code. Having a public variable would make such maintenance a breaking change. Very often this is the difference between a change being feasible and being too invasive/risky to perform.


问:
Organizing action in MVC controller
I am developing an ASP.NET MVC application, that has a lot of client side interaction ie. a lot of ajax calls to controller actions.

Currently I have controllers containing actions (part of the same controller) returning both views and data (json/xml), I am considering is it a good practice to have actions returning data and views under one controller.

For example under

```<code>/Controllers/CarsController/
public ActionView Index()
public ActionView Car(int carID)
public ActionResult CarMakes()
public ActionResult CarModels(int makeID)

/Controllers/StoresController
public ActionView Index()
public ActionView Store(int storeID)
public ActionResult Cities()
public ActionResult Stores()
</code>```

This is one way of thinking, and the other would be

```<code>/Controllers/CarsController/
public ActionView Index()
public ActionView Car(int carID)

/Controllers/StoresController
public ActionView Index()
public ActionView Store(int storeID)

/Controllers/ServicesController
public ActionResult CarMakes()
public ActionResult CarModels(int makeID)
public ActionResult Cities()
public ActionResult Stores()
</code>```

The second way offers an easier way to find all the available actions that could be used for client side interaction. Actions avoids duplication, could also be reused and called from different controllers (they can be called and reused in either way)

So between these two I would just like to know what is general practice when designing MVC application?

答:
The first approach seems better. Keep all actions related to a certain object (usually a model) under a single controller. You will know for sure that if you need to change an existing action related to cars, it will be located under CarsController. This makes your code easier to maintain.

It's perfectly normal for a single controller to contain different types of actions.

Title: Organizing action in MVC controller


问:
How do you dive into large code bases?
What tools and techniques do you use for exploring and learning an unknown code base?

I am thinking of tools like grep, ctags, unit-tests, functional test, class-diagram generators, call graphs, code metrics like sloccount, and so on. I'd be interested in your experiences, the helpers you used or wrote yourself and the size of the code base with which you worked.

I realize that becoming acquainted with a code base is a process that happens over time, and familiarity can mean anything from "I'm able to summarize the code" to "I can refactor and shrink it to 30% of the size". But how to even begin?

答:
I'd encourage you to write unit tests before you change anything in the ball of mud.  And only change enough of the code at the time to make the tests pass.  As you refactor, add unit tests before hand so you know that the business functionality hasn't been busted by refactoring.

Is pair programming an option?  Having another person to bounce ideas off is a great idea to deal with that amount of nasty.

Title: How do you dive into large code bases?

ContentLicense: CC BY-SA 2.5


问:
What happened to VM based deployments?
Watched some MountainWest RubyConf 2014 talks and noticed an interesting theme. Many dynamic programming environments back in the old days used to be self-contained VM images, e.g. SmallTalk, GemStone/S.

One could checkpoint, modify, and ship these images wholesale and have it up and running with very little effort. Fast forward to now and I'm still using Make files to configure and install binaries. What happened?

答:
The number of people who had actually used one of these extreme productivity environments was pretty low. It started in workstation land, think $100.000/developer. Most developers couldn't afford the license and hardware needed. Then the price war broke out where Microsoft tried killing Borland and Sun gave away Java. Not enough developers had actually used smalltalk enough to stop management making long-term mistakes.
  So now the vms come back from the devops side, with docker  </p>

Title: What happened to VM based deployments?


问:
How to store (and find) updated values in a Distributed Hash Table?
Distributed Hash Tables are a great way to store immutable data in a resilient way.

However, I am wondering about how it would be possible to store new versions of old data in this system.

Because it is impossible in a distributed network to unconditionally trust the other party, a way is needed to ensure that another party does not manipulate stored data. The easiest way to do this is to store data values under keys that are generated from these values using a one-way hash function. This means that when someone wants to change data, they invalidate the key->value relation of that data, which is easy to check against.

Say, someone stores a document in the DHT, but later made some changes and wants to store that new version. How can other people connected to the DHT find out that there is a new version of this document?
The only information that I found about this said that an idea would be to store versioned data like this:

```<code>v1: hash(random_number) -> document1
v2: hash(key(v1)) -> document2
v3: hash(key(v2)) -> document3
...etc.
</code>```

Then, to check if there is a new version, all a client would need to do is to apply the hashing algorithm one more time to the hash of the current value.

Drawback: This approach does not have the relation between key and value, meaning that a value might be changed (by a malicious server or a man-in-the-middle) without invalidating the key.

How can these two approaches be combined? Or is there a different, better way to manage this?

答:
Once you decide that clients cannot be trusted, then it is a given fact that each value is immutable, and each key is immutable.  And immutability is forever.

This in turn means that this is not a problem of storing and finding values, it is a problem of identifying the key of the most updated version of a value, so it is a versioning problem.

When trying to solve the versioning problem, you first of all have to ask again if you can trust your sources.

If you can trust your sources, then all you need is a straightforward, almost trivial solution. This could involve:

Mapping keys to pairs of actual keys and version numbers, so that you can list them all to find the one with the highest version number.

Mapping keys to successor keys so that given a "current" key you can traverse the chain and find the key which corresponds to the latest version.

If you cannot trust your sources, then you have to employ some voting mechanism. This is a subject which has received plenty of research, under the broad title of "Consensus".  So, a good place to start would be the relevant wikipedia article: Wikipedia: Consensus (Computer science)


问:
data maintenance/migrations in image based sytems
Web applications usually have a database.
The code and the database work hand in hand together.
Therefore Frameworks like Ruby on Rails and Django create migration files

Sure there are also servers written in Self or Smalltalk or other image-based systems that face the same problem: Code is not written on the server but in a separate image of the programmer.

How do these systems deal with a changing schema, changing classes/prototypes.
Which way do the migrations go?

Example: What is the process of a new attribute going from programmer's idea to the server code and all objects?

I found the Gemstone/S manual chapter 8 but it does not really talk about the process of shipping code to the server.

答:
In Gemstone there are class versions and you can have objects of multiple class versions in the system. By default, adding a new attribute just adds it with a nil value. With a lazy accessor you can just set the value when needed. Or you can do an active migration and decide what needs to happen, either for all old objects when loading the new class definition or lazily, whenever one is used. </p>

<p>In Pharo we just have the default behaviour, adding an instance variable nils it. That means that loading a new version can potentially be slow, e.g. when needing to add an instVar to a million objects.  If we need more than just a new property, we add migration code that runs before or after loading the new version.  </p>

Body:
In Gemstone there are class versions and you can have objects of multiple class versions in the system. By default, adding a new attribute just adds it with a nil value. With a lazy accessor you can just set the value when needed. Or you can do an active migration and decide what needs to happen, either for all old objects when loading the new class definition or lazily, whenever one is used.

In Pharo we just have the default behaviour, adding an instance variable nils it. That means that loading a new version can potentially be slow, e.g. when needing to add an instVar to a million objects.  If we need more than just a new property, we add migration code that runs before or after loading the new version.


答:
Probably because of performance. I have used a VM image to develop with - on Microsoft platform I was exposed to a legacy product that worked on XP but not Windows 7, so was given a copy of a VM to run on my workstation that contained all the dev tools set up to go. Performance was not what I would have liked.

I think much of that was due to GUI performance, but that's the most important part for a developer. In the past, with mainframe environments partly the VM is better integrated, but also GUIs were less resource intensive.

Today, we tend to have developer environments that require as much power as is available, but there is a move to deploying applications in a single image - we've seen VMs for deployment, but these tended to be too heavyweight for a single application (ie you had to have a full OS running just to host a tiny server app), so we're moving towards application-level VMs in the form of frameworks like Docker or Windows Containers.

Title: What happened to VM based deployments?

Body:
Watched some MountainWest RubyConf 2014 talks and noticed an interesting theme. Many dynamic programming environments back in the old days used to be self-contained VM images, e.g. SmallTalk, GemStone/S.

One could checkpoint, modify, and ship these images wholesale and have it up and running with very little effort. Fast forward to now and I'm still using Make files to configure and install binaries. What happened?


问:
Object Communication Design
Multiple top-level systems that communicate with each other via messages(events/commands).

The Main class of the program wraps around all the systems and has a message dispacher component wich delivers messages from one system to another.
Each system contains a lot of objects that need to communicate with each other, however these messages do not necessarily concern other systems.

My current implementation is as follows: each registered listener has an object(hashmap) "subscribedEvents" with callbacks for the concerned events(messages), but to avoid having the inner objects of a system send their messages through the main dispacher they would have a personal dispacher. The problem I have with this approach is how to identify each dispatcher, since inner objects still need to be able to listen for top level messages and the "subscribedEvents" object would have to become

```<code> subscribedEvents[dispacherId].eventCallback
</code>```

What would be a proper way to add identifiers to the dispachers? A dispatcher is just a component of a class(system or inner object) and each dispatcher is not aware of the others. I can only think of a singleton eventDispatcher factory, but that doesn't look like a very elegant solution to me.

PS: I am open to a different whole new different approach for dealing with communication, this is just what I have come up with.

答:
You need a location service (an example of one is DNS) where each personal listener can register itself with a parent, possibly leading to those parents being children of another parent in turn until you get to a root. This allows you to broadcast messages that are received from a parent to all children that have registered to receive those messages.

If you know which dispatcher to send a message to you can send it directly, otherwise, you can ask the root to locate the one you want (I don't know your criteria for this). Alternatively you can send the message to the root and let it propagate the message to all its children, and their children. Use a location request message for this and it becomes easy to implement.

This kind of federated system works well - but be careful not to pass on all messages, you should be filtering them by allowing each dispatcher to say what kind of messages it cares about, and never send others to them. This helps make it scale. It also means you can add new services very easily, you just drop them into the system and each one starts processing messages as if by magic.

Title: Object Communication Design


答:
The first thing to note is that public getters and setters do not provide encapsulation:

[…] getters and setters do not achieve encapsulation or information hiding: they are a language-legitimized way to violate them.

James O. Coplien & Gertrud Bjørnvig. Lean Architecture. Wiley. 2010. p. 134.

So the answer to your question as to whether there's a difference between them and just having a public field is: there is no difference as far as encapsulation is concerned.

What they do provide though is support for the Open-closed principle. You can later change the behaviour of the getter and setter, to add a guard cause for example, without changing the API. This though leads down another potentially bad path, as any getter/setter that doesn't just get/set a field risks breaking the POLA principle.

You final question leads you to the "correct" way to use getters: use a constructor to set the fields and only provide getters. That provides true encapsulation and enables your fields to be invariant, which improves thread-safety.

Title: Meaning of using getters and setters and Uses of parameterized Constructor.

Body:
I am using getters and setters to for the purpose of encapsulation.

```<code>public class Student {

    private String studentID;
    private String studentName;
    private String address;

    public Student(){
        //default constructor
    }

    public Student(String studentID, String studentName, String address) {
        super();
        this.studentID = studentID;
        this.studentName = studentName;
        this.address = address;
    }

    public String getStudentID() {
        return studentID;
    }

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getAddress() {
        return address;
    }

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

the variables studentID, studentName and address are declared as private, with the intention of encapsulation.

but we could also do the same task by making the variable accessibility level from private to public, is it really helps to apply encapsulation by the use of setters and getters?

only I can understand the use of getter and setter is users of the class dows not need to have an idea about the names of the variables used in the class as setters and getters makes sense to the users of the class

ex- objectofStudentClass.setStudentID("S0001");

Is there any difference between main difference between making getters and setters instead if making the variable access level to public.

Question 2:
also here I have made parameterized constructor matching to the variables/fields in the class Student. is that  throw away the concept of encapsulation?


答:
This solves the above mentioned problem (1). However if you look at the inheritance relation as an "is a" statement then "a mutable image IS AN immutable image" makes no sense. Which speaks against using inheritance here.

Well ... a mutable image IS an imutable image, with extra capabilities (for mutation) - which makes a lot of sense (just like a surgeon is a doctor with extra capabilities). The fact that the extra capabilities are a distinction between mutable and immutable makes little difference (it's still an immutable image with mutable behavior added to it).

I imagine the confusion that created the question, is the fact that in spoken language, it doesn't make sense to say "a mutable X is an immutable X" (because in rational thinking, either A or non-A, but not both).

This OO "is-a" relationship though, is not really the same "is-a" relationship that you have in spoken English.

Title: Designing around shallow constness with inheritance

Body:
Background

I'm writing an image handling class. For this question two requirements of the class are of interest:

Must have "deep" const correctness.

Must allow sub-image aliases, a.k.a. sections or slicing without performing deep copies of image data.

By deep constness I mean the following. Consider this example class:

```<code>class Image{
public:
    ...
    Image(const Image&);

    Image alias(int x0, int y0, int x1, int y1) const;
private:
    Buffer image_data;
};
</code>```

And assume you have a function that is passed a const reference to a image, like so:

```<code>void foo(const Image& im){
    Image alias = im.alias(0,0, 10, 10);
    // Hold on, the mutable alias can modify the data in the const argument!
}
</code>```

The above alias function call defeats the constness of the argument because the contents of the argument image can be modified through the non-const alias. I can't return a const Image from alias because well that makes no sense really and the copy constructor of Image will happily construct a mutable instance anyway.

My solution (and I've seen it used often so I don't claim originality here) is to introduce two classes (interfaces really, but for the simplicity they are classes in this example and return by value is okay, in reality alias(...) returns a shared_ptr to interface):

```<code>class ConstImage{
public:
    ConstImage alias(...) const;
};

class Image{
public:
    Image alias(...);
};
</code>```

Now the following code:

```<code>void foo(const Image& im){
    // compile error, cannot convert ConstImage to Image, perfect!
    Image alias = im.alias(...);
}
</code>```

And of course you would change the signature to void foo(const ConstImage& im) so that you can accept invocations like foo(const_im.alias(...)) or other ConstImage objects.

Now of course we want foo(const ConstImage& im) to be callable (1) with a mutable Image too and here is where the question comes in.

Question

Using inheritance: class Image : public ConstImage will make all Image types usable through ConstImage references and pointers. It will also facilitate code-reuse between the const and non-const implementations which by necessity are very similar.

This solves the above mentioned problem (1). However if you look at the inheritance relation as an "is a" statement then "a mutable image IS AN immutable image" makes no sense. Which speaks against using inheritance here.

My question is, is this kind of (ab)use of inheritance widely acceptable? Is there some other better solution that I have overlooked? Note that the Image class is more of an interface so naive value conversion from Image to ConstImage isn't possible. Although one could probably come up with something crazy to allow it.


问:
Real world pitfalls of introducing F# into a large codebase and engineering team
I'm CTO of a software firm with a large existing codebase (all C#) and a sizable engineering team.  I can see how certain parts of the code would be far easier to write in F#, resulting in faster development time, fewer bugs, easier parallel implementations, etc., basically overall productivity gains for my team.  However, I can also see several productivity pitfalls of introducing F#, namely:

1) Everyone has to learn F#, and it's not as trivial as switching from, say, Java to C#.  Team members that have not learned F# will be unable to work on F# parts of the codebase.

2) The pool of hireable F# programmers, as of now (Dec 2010) is non-existent.  Search various software engineer resume databases for "F#", way less than 1% of resumes contain the keyword.

3) Community support as of now (Dec 2010) is less available.  You can google almost any problem in C# and find someone that has already dealt with it, not so with F#.  Third party tool support (NUnit, Resharper etc) is also sketchy.

I realize that this is a bit Catch-22, i.e. if people like me don't use F# then the community and tools will never materialize, etc.  But, I've got a company to run, and I can be cutting edge but not bleeding edge.

Any other pitfalls I'm not considering?  Or anyone care to rebut the pitfalls I've mentioned?  I think this is an important discussion and would love to hear your counter-arguments in this public forum that may do a lot to increase F# adoption by industry.

答: Search resumes for other functional languages such as Scheme, Lisp or Haskell.  A lot of people learn these in school and have them on their resumes; I'm sure many of them wouldn't mind learning F#.  I have Scheme in my resume even though I never used it after school and a job involving F# would probably get my attention too.</p>

OwnerDisplayName: nganju

OwnerDisplayName: MK


问:
Rendering partial View in MVC
i am not so familiar working with partial Views. The reason behind that is that I really do not have the basics of Jquery/JS/Ajax. But I recently found through some SO post that a partial view can be rendered using AJAX Unobtrusive. The method in the post seems to be really simple using the Ajax Helper methods.

But I came across many similar posts asking for help in rendering the Partial view. But most have suggested using scripts to render the same.

What is the reason why people never suggested Unobtrusive AJAX. (In my case I never got it right using Unobtrusive AJAX, but I strongly believe that it isn't the problem of Unobtrusive Ajax, but mine).

I am looking for suggestions in rendering a partial view. I have a project to be completed in a month. I would prefer someone suggests some easy methods to get my task done.

答:
There are two times when you want to render a partial view:

Synchronously, as part of rendering a larger view

e.g. the view that is called when rendering /Widgets/Details/ might have Razor code that looks like this

```
&ltdiv class="subwidget">
  @Html.Partial("_Subwidget", Model.Subwidget)
&lt/div>
```

This will then render the _Subwidget.cshtml and pass the Subwidget property of the current view's Widget. This helps in breaking down larger views to make them more manageable and lets you render the _Subwidget view in other views without duplicating code.

Asynchronously, when the partial view is the entire content you want returned from calling a controller method.

e.g. the page is already on the client device but contains this jQuery code

```
$.get('/Widgets/Subwidget/300')
```

Which sends a GET to the Widgets controller and calls Subwidget(300). The Subwiget action doesn't want to include any of the layout and other stuff, it only wants to return bare data (which could be an HTML fragment, JSON, or even just a string).

The Subwiget action might look something like this

```
public ActionResult Subwidget(int Id)
{
var subwidget = _widgetGateway.Subwidget(Id);
return PartialView("_Subwidget", subwidget);
}
```

It's up to the javascript code on the page to deal with it at that point.

It's important to keep in mind that a partial view is just the result that is sent to the browser. Your actions are still able to do all of the things that a standard controller action could do. If you want to accept data in the form of a POST, PUT, or DELETE you can also do work in your action:

```<code>[HttpPost]
public ActionResult SubmitSubwidget(Subwiget sub)
{
  _widgetGateway.Save(sub);
  return PartialView("_Subwidget", sub);
}
</code>```

In fact, you don't even have to return any content back to the browser at all. If you just want to know whether the call succeeded, you can just send the HTTP status code.

```<code>[HttpPost]
public ActionResult SubmitSubwidget(Subwiget sub)
{
  if(_widgetGateway.Save(sub))
    return new HttpStatusCodeResult(200, "Submitted");
  else
    return new HttpStatusCodeResult(500, "Submission failed");
}
</code>```

Title: Rendering partial View in MVC

Body:
There are two times when you want to render a partial view:

Synchronously, as part of rendering a larger view

e.g. the view that is called when rendering /Widgets/Details/ might have Razor code that looks like this

&ltdiv class="subwidget">
  @Html.Partial("_Subwidget", Model.Subwidget)
&lt/div>

This will then render the _Subwidget.cshtml and pass the Subwidget property of the current view's Widget. This helps in breaking down larger views to make them more manageable and lets you render the _Subwidget view in other views without duplicating code.

Asynchronously, when the partial view is the entire content you want returned from calling a controller method.

e.g. the page is already on the client device but contains this jQuery code

$.get('/Widgets/Subwidget/300')

Which sends a GET to the Widgets controller and calls Subwidget(300). The Subwiget action doesn't want to include any of the layout and other stuff, it only wants to return bare data (which could be an HTML fragment, JSON, or even just a string).

The Subwiget action might look something like this

public ActionResult Subwidget(int Id)
{
var subwidget = _widgetGateway.Subwidget(Id);
return PartialView("_Subwidget", subwidget);
}

It's up to the javascript code on the page to deal with it at that point.

It's important to keep in mind that a partial view is just the result that is sent to the browser. Your actions are still able to do all of the things that a standard controller action could do. If you want to accept data in the form of a POST, PUT, or DELETE you can also do work in your action:

[HttpPost]
public ActionResult SubmitSubwidget(Subwiget sub)
{
  _widgetGateway.Save(sub);
  return PartialView("_Subwidget", sub);
}

In fact, you don't even have to return any content back to the browser at all. If you just want to know whether the call succeeded, you can just send the HTTP status code.

[HttpPost]
public ActionResult SubmitSubwidget(Subwiget sub)
{
  if(_widgetGateway.Save(sub))
    return new HttpStatusCodeResult(200, "Submitted");
  else
    return new HttpStatusCodeResult(500, "Submission failed");
}


问:
Should it use counter, or flag inside objects, to indicate progress?
For example, I have a game, it has 5 enemies which attack once sequentially at each round:

```<code>class Enemy{
};

class Game{
public:
    Enemy enemys[5];
};
</code>```

I want something to indicate which enemy has attacked and which has not, now I have 2 solutions:

1.add a counter "enemyIndex" to indicate which enemy is attacking, after each enemy attacked, the "enemyIndex" counter automatically +1:

```<code>class Enemy{
};

class Game{
public:
    int enemyIndex;
    Enemy enemys[5];
};
</code>```

2.each Enemy object adds a flag "isAttacked", after the enemy attacked, its  "isAttacked" flag marked from false to true:

```<code>class Enemy{
public:
    bool isAttacked;
};

class Game{
public:
    Enemy enemys[5];
};
</code>```

which one is more reasonable in terms of design pattern?

答:
You could encapsulate the iteration logic in a Iterator.
Then you would call the iterator in the game class, or create a list of enemies that return this iterator.

Game::getAttackIterator() or EnemiesList::getAttackIterator()

This allows you to encapsulate the iteration logic for the attack, for example if you want enemies to be attacked twice sequentially instead of just once, you would simply change the implementation of the iterator.


问:
Is premature optimization really the root of all evil?
A colleague of mine today committed a class called ThreadLocalFormat, which basically moved instances of Java Format classes into a thread local, since they are not thread safe and "relatively expensive" to create. I wrote a quick test and calculated that I could create 200,000 instances a second, asked him was he creating that many, to which he answered "nowhere near that many". He's a great programmer and everyone on the team is highly skilled so we have no problem understanding the resulting code, but it was clearly a case of optimizing where there is no real need. He backed the code out at my request. What do you think? Is this a case of "premature optimization" and how bad is it really?

答:
Most of those who adhere to "PMO" (the partial quote, that is) say that optimizations must be based on measurements and measurements cannot be performed until at the very end.

It is also my experience from large systems development that performance testing is done at the very end, as development nears completion.

If we were to follow the "advice" of these people all systems would be excruciatingly slow. They would be expensive as well because their hardware needs are much greater than originally envisaged.

I have long advocated doing performance tests at regular intervals in the development process: it will indicate both the presence of new code (where previously there was none) and the state of existing code.

The performance of newly-implemented code may be compared with that
of existing, similar code. A "feel" for the new code's performance
will be established over time.

If existing code suddenly goes haywire you understand that something
has happened to it and you can investigate it immediately, not (much)
later when it affects the entire system.

Another pet idea is to instrument software at the function block level. As the system executes it gathers information on execution times for the function blocks. When a system upgrade is performed it can be determined what function blocks perform as they did in the earlier release and those that have deteriorated. On a software's screen the performance data could be accessed from the help menu.

Check out this excellent piece on what PMO might or might no mean.

OwnerDisplayName: Craig Day


答:
The main problem is always maintainability.

I would love to code in Scheme, but the next maintainer would probably want to hunt me down and torture me.

Title: Real world pitfalls of introducing F# into a large codebase and engineering team

Body:
I'm CTO of a software firm with a large existing codebase (all C#) and a sizable engineering team.  I can see how certain parts of the code would be far easier to write in F#, resulting in faster development time, fewer bugs, easier parallel implementations, etc., basically overall productivity gains for my team.  However, I can also see several productivity pitfalls of introducing F#, namely:

1) Everyone has to learn F#, and it's not as trivial as switching from, say, Java to C#.  Team members that have not learned F# will be unable to work on F# parts of the codebase.

2) The pool of hireable F# programmers, as of now (Dec 2010) is non-existent.  Search various software engineer resume databases for "F#", way less than 1% of resumes contain the keyword.

3) Community support as of now (Dec 2010) is less available.  You can google almost any problem in C# and find someone that has already dealt with it, not so with F#.  Third party tool support (NUnit, Resharper etc) is also sketchy.

I realize that this is a bit Catch-22, i.e. if people like me don't use F# then the community and tools will never materialize, etc.  But, I've got a company to run, and I can be cutting edge but not bleeding edge.

Any other pitfalls I'm not considering?  Or anyone care to rebut the pitfalls I've mentioned?  I think this is an important discussion and would love to hear your counter-arguments in this public forum that may do a lot to increase F# adoption by industry.

OwnerDisplayName: leppie


问:
In garbage collecting languages (JavaScript), can I securely overwrite data?
Realizing that garbage collection and memory management is implemented differently in different environments for sake of simplicity this question will focus on JavaScript (either V8 or Seamonkey).

I realize that garbage collection is a means to determine if a portion of memory needs to be deallocated or not. The simplest example I know of is setting a variable to null:

```<code>var x = 'foobar';
// x)-┐
//    V
//   ┌-┬-┬-┬-┬-┬-┐
//   |f|o|o|b|a|r|
//   └-┴-┴-┴-┴-┴-┘
x = null;
// x)--> null
//
//   ┌-┬-┬-┬-┬-┬-┐
//   |f|o|o|b|a|r| Eligible to be garbage collected
//   └-┴-┴-┴-┴-┴-┘
</code>```

So I was musing how can I securely change the value so that it isn't available to poking? I realize this is a purely contrived example. The reason I ask is to better understand how memory is allocated in JavaScript and if there are methods of data manipulation that would avoid reallocation of memory leaving some of it littering up the free memory space.

In other words can I change the memory values in JavaScript or is reassignment the only way leaving it in free memory?

To further illustrate my contrived example, let's say I want to store a password but then securely obfuscate it before I send it into garbage collector land. I believe Reassignment would look like this:

```<code>var x = 'foobar';
// x)-┐
//    V
//   ┌-┬-┬-┬-┬-┬-┐
//   |f|o|o|b|a|r|
//   └-┴-┴-┴-┴-┴-┘
x = '******';
// x)--------------┐
//                 V
//   ┌-┬-┬-┬-┬-┬-┐┌-┬-┬-┬-┬-┬-┐
//   |f|o|o|b|a|r||*|*|*|*|*|*|
//   └-┴-┴-┴-┴-┴-┘└-┴-┴-┴-┴-┴-┘
//    \_________/
//         |
//         Eligible for garbage collection
x = null;
// x)--> null
//
//   ┌-┬-┬-┬-┬-┬-┐┌-┬-┬-┬-┬-┬-┐
//   |f|o|o|b|a|r||*|*|*|*|*|*|
//   └-┴-┴-┴-┴-┴-┘└-┴-┴-┴-┴-┴-┘
//    \_________/  \_________/
//         |            |
//         Eligible for garbage collection
</code>```

So can I manipulate the first memory partition so that the values are not left in memory unreferenced but instead replaced so a memory scan would find the replacement instead of the old value?

答:
"So I was musing how can I securely change the value so that it isn't
  available to poking?"

you can't. You have no access to the actual memory location where the data is stored, so you can't determine where you're writing.

The attempt to overwrite the data is likely to write to another location entirely.


答:
Edited to qualify and expand my answer after the conversation in the comments with @MetaFight

In just about every language I've seen with events (JavaScript, ActionScript2/3) the on prefix is used to signify an event handler procedure and an emit, fire, or raise prefix is used on a method which elicits an event. (On might also be used in a property name to signify the attachment of a callback, such as in the onclick HTML attribute.)

C#, on the other hand, appears to break this this convention somewhat.

When the On prefix is used on a method in a base class, it will actually fire an event:

```<code>public class Base
{
    public delegate void OpeningEventHandler(Object sender, EventArgs e);
    public event OpeningEventHandler Opening = delegate {};

    protected virtual void OnOpening(EventArgs e)
    {
        Opening(this, e);
    }
}
</code>```

When this method is overridden in a derived class, the override is supposed to handle the event, also calling the base implementation:

```<code>public class Derived : Base
{
    protected override void OnOpening(EventArgs e)
    {
        // handle event here
        base.OnOpening(e);
    }
}
</code>```

This is presumably used to enable a deriving class to cancel propagation of the event (by not calling the base method).

From the MSDN documentation for the Form.Onload method:

Remarks

...

The OnLoad method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class.

Notes to Inheritors:

When overriding OnLoad in a derived class, be sure to call the base class's OnLoad method so that registered delegates receive the event.

There's a related question on SO.

Body:
Edited to qualify and expand my answer after the conversation in the comments with @MetaFight

In just about every language I've seen with events (JavaScript, ActionScript2/3) the on prefix is used to signify an event handler procedure and an emit, fire, or raise prefix is used on a method which elicits an event. (On might also be used in a property name to signify the attachment of a callback, such as in the onclick HTML attribute.)

C#, on the other hand, appears to break this this convention somewhat.

When the On prefix is used on a method in a base class, it will actually fire an event:

public class Base
{
    public delegate void OpeningEventHandler(Object sender, EventArgs e);
    public event OpeningEventHandler Opening = delegate {};

    protected virtual void OnOpening(EventArgs e)
    {
        Opening(this, e);
    }
}

When this method is overridden in a derived class, the override is supposed to handle the event, also calling the base implementation:

public class Derived : Base
{
    protected override void OnOpening(EventArgs e)
    {
        // handle event here
        base.OnOpening(e);
    }
}

This is presumably used to enable a deriving class to cancel propagation of the event (by not calling the base method).

From the MSDN documentation for the Form.Onload method:

Remarks

...

The OnLoad method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class.

Notes to Inheritors:

When overriding OnLoad in a derived class, be sure to call the base class's OnLoad method so that registered delegates receive the event.

There's a related question on SO.


问:
Is progressive HTTP download a viable alternative to HLS/DASH/RTMP for providing live video?
I'm working on a website that needs to stream live video to users, and as such I've had to get my head around the sorry state of current browser-based video-streaming technology. The most popular solutions for live streaming at present all have compatibility issues; RTMP requires Flash, HLS is only natively supported on Safari and Chrome for Android, DASH isn't natively supported anywhere, and using dash.js requires Media Source Extensions, which aren't yet widely supported.

This leads to a question that to me seems obvious: is it possible to use simple progressive download as an alternative to protocols like HLS, RTMP and DASH that either require browser support or plugins?

The idea of using progressive download to stream live media isn't unprecedented; people already do it for audio. Tools like liveCaster allow you to stream live MP3 audio through a single progressive HTTP response without needing a pre-recorded MP3 file, and libraries like AmplitudeJS have gone out of their way to add features related to this kind of live audio streaming.

I haven't seen any instances of this technique being used in the wild for video, though, and I can't tell why. It seems like it would remove a layer of messy and difficult browser-side compatibility problems for relatively little tradeoff. (And compatibility is still a huge problem for live streaming, even when the pros do it; if I try to watch live video on BBC's iPlayer in Firefox, it just gives me an error message telling me to install Flash.) Yet nobody is using this technique, and I've never seen anybody even mention the idea besides me.

Why?  Is there a fundamental limitation I'm not seeing that would make it impossible just stream a video file like an MP4 via progressive download as it is being generated, and play it in a <video> element as it downloads?

答:
Your question is valid and theoretically I think you can use Progressive Downloads for live video streaming. Actually A lot of Online Streaming Video like YouTube etc already use HTTP. I am assuming you are strictly talking about LIVE streaming and not just streaming.

You will have to implement the Live Streaming use cases though, yourself! Which otherwise the streaming protocols (RTMP etc.) do themselves. Here are some reasons to prefer these protocols and architecture:

1. Variable Bit Rate

Most Live streaming video is encoded in VBR and your video will have to quickly adapt to changing network congestion of your client. So your video can go switch multiple resolutions in a very short time depending on how fast or slow the client connection is.

According to Wikipedia

It works by detecting a user's bandwidth and CPU capacity in real time and adjusting the quality of a video stream accordingly

2. Live Content

The most important point is that Live streaming means live content. Unlike HTTP Progressive Download, you cannot buffer at any time. The user must see the latest frame intended for the whole world and cannot lag behind.

3. Disable Seeking

A minor issue, but the protocol should specifically not allow the user to seek backwards (and obviously forwards). This shouldn't just be controlled at the Video Player level but also at the network level.

4. Frequent disconnections / unreliable network

I am a bit unclear about this point but I do know that once an incoming HTTP download is disconnected, it can take some time to establish another handshake (even with keep-alive). Live protocols are much faster to connect and disconnect because of the next point ->

5. Latency

HTTP inherently runs over TCP which is gives guaranteed delivery of packets. Compare this with UDP used in a lot of protocols (especially live multiplayer gaming) where speed is prioritised over guarantees.

For more see here -> https://en.wikipedia.org/wiki/Streaming_media#Protocols

6. Content Copying

Most live stream servers will only respond to the current time's content. Though it is still possible to copy content of live streams, one has to resort to screen capture etc. Giving an HTTP progressive download makes the task of copying content quite trivial (Hence so many many YouTube downloaders out there).

Now, HTTP can be modelled to provide most of the above.

Apple's HTTP Live Streaming (HLS), you mentioned, comes closest to what you're trying to achieve.

And there is active research going on in this field as given here -> http://www.streamingmedia.com/Articles/ReadArticle.aspx?ArticleID=65749&PageNum=2

I'm on the lookout for more info and will update this answer.


问:
Passing Anonymous Type to a Bound Control
Generally speaking, I'm fairly opposed to the use of anonymous types in real-world code (except in LINQ and some other specific scenarios), but I'm looking right now at a situation where I need to bind an ASP GridView control with a collection of tuple values and they're looking pretty tempting.

Basically, I need to show a list of proprietary accounts that are associated with different computer names. I don't currently have a type that contains those two properties because I don't use them together like this anywhere else.

What I would normally do in a situation like this is just create a new class that has the properties, set the ItemType on the GridView to reference that type, then build objects of that type in my Select method (I use ObjectDataSource much of the time). But I'm thinking now that there's really no benefit to throwing in that extra class, since no matter what it's getting bound via reflection.

Is there any reason to shy away from using anonymous types in data-binding situations like this?

I'd accept anything: performance, readability, maintainability, principle, or whatever else you can throw at me. But the only disadvantage I can think of is if I wanted to use the Item property to use Intellisense for my data-binding, but in this particular case I have no use for anything more than BoundFields. Of course, this is all based on the assumption that it even works, admittedly I haven't tried it yet with anonymous types, so it might just not be supported for one reason or another.

答: I often bind a GridView to a System.Data.DataTable that was filled from a stored procedure. I make the fields in the stored procedure match the field names in the GridView. Another way, when using linq and entitiy framework with anonymous types is to bind the linq result directly to the DataSource property of the GridView the same way as if it were a DataTable. This question shows an example using linq and here's an example using a DataTable. I personally think using anonymous types is better than using a DataTable because the data in the DataTable is stored as an Object and the anonymous type is a strong data type. The decision to use DataTables vs Linq and Anonymous types often depends on how your supervisor feels about Linq and the Entity Framework.</p>

OwnerDisplayName: Matthew Haugen


答:
As you recognize in your first point, your programmers who don't know F# can't work on the F# part of your codebase.  However, you don't need to rewrite your whole codebase in F# to gain advantages from using it - just rewrite the parts where you would see the biggest benefit.  The fact that F# interoperates really well with C# should make it relatively easy to carve out certain parts and create F# assemblies out of them.

If you had your engineers working on a traditional 3-tier application, you probably wouldn't insist that they all needed to have a deep knowledge of SQL, HTML, Javascript, CSS, etc.  Instead, you'd naturally have some specialists working on different parts of the application.  Therefore, I don't think that adding a new language for one part of your application should be too big of a hurdle.  Furthermore, you can use coding standards and other practices to try to make sure that your F# code is readable even by engineers without a deep F# background.

OwnerDisplayName: kvb


问:
Create a globally visible method for an API
I'm trying to create a Java API that I will use in other projects.

I understand that if I create new classes I can make objects in the other projects that have those classes. But what I want right now is a way to just create a method that isn't part of an objects that I can call upon whenever I wish without having to create a new object.

So what I'm asking is, how would I create a method like this where I can pass in parameters from another project and the api project will do whatever I put in the method involving those perameters? Do I need to make the methods static or what?

When I try to just access the class with the class name and then import that class from the api, it doesn't allow me to use a public void method that I created.

答:
Don't use static method if it contains any global state. It's bad design.
But public static methods is good for "utility" classes/methods with no state between method calls. java.lang.Thread.currentThread() is not a good example. Collections.sort() is much better.
Disadvantages as were mentioned:

It's difficult to mock them in unit tests. But usually you don't. It contains some 'algorithm' and does not contain any state (no external dependencies).

You can't override static method by subclassing. This can be a case.
So consider these two options in your API. Don't avoid static methods just because Java is object-oriented language.


问:
Is Node.js a framework?
I keep seeing recruiters, developers, etc. refer to Node.js as a framework. In my opinion, this is out of ignorance for what Node.js really is.

Oftentimes, in job descriptions, Node.js is grouped in as a library among AngularJS, React, etc. Generally, I see it as being entered by someone that doesn't know the difference (HR, a recruiter, etc.).

In my opinion, Node.js is a platform, or a runtime environment; it switches out the DOM API (JavaScript in the browser) for various other APIs, like the file system (since it runs as a server, and not in the browser).

Why is it that people think Node.js is a framework; am I wrong? Is it actually a framework?

答:
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

source

Node is a runtime or environment. It is not a framework. People (I feel) often get this wrong because frameworks like express are ubiquitous with node.

more reading on runtimes vs frameworks if you are interested.

Title: Is Node.js a framework?


问:
How do I test a system where the objects are difficult to mock?
I am working with the following system:

```<code>Network Data Feed -> Third Party Nio Library -> My Objects via adapter pattern
</code>```

We recently had an issue where I updated the version of the library I was using, which, among other things, caused timestamps (which the third party library returns as long), to be changed from milliseconds after the epoch to nanoseconds after the epoch.

The Problem:

If I write tests that mock the third party library's objects, my test will be wrong if I have made a mistake about the third party library's objects. For example, I didn't realize that the timestamps changed precision, which resulted in a need for change in the unit test, because my mock returned the wrong data. This is not a bug in the library, it happened because I missed something in the documentation.

The problem is, I cannot be sure about the data contained in these data structures because I cannot generate real ones without a real data feed. These objects are big and complicated and have a lot of different pieces of data in them. The documentation for the third party library is poor.

The Question:

How can I set up my tests to test this behavior? I'm not sure I can solve this issue in a unit test, because the test itself can easily be wrong. Additionally, the integrated system is large and complicated and it's easy to miss something. For example, in the situation above, I had correctly adjusted the timestamp handling in several places, but I missed one of them. The system seemed to be doing mostly the right things in my integration test, but when I deployed it to production (which has a lot more data), the problem became obvious.

I do not have a process for my integration tests right now. Testing is essentially: try to keep the unit tests good, add more tests when things break, then deploy to my test server and make sure things seem sane, then deploy to production. This timestamp issue passed the unit tests because the mocks were created wrong, then it passed the integration test because it didn't cause any immediate, obvious problems. I do not have a QA department.

答:
The best would be to create a minimal prototype, and understand how the library works exactly. By doing that, you will gain some knowledge about the library with poor documentation. A prototype can be a minimalistic program that uses that library and does the functionality.

Otherwise, it makes no sense to write unit tests, with half-defined requirements and weak understanding of the system.

As for your specific problem - about using wrong metrics : I would treat it as a requirements change. Once you recognized the problem, change the unit tests and the code.


答:
It's a bit tough to say because these words are not well-defined. In common parlance, I think it's a bit atypical to call Node.js a framework, sure, but I'd have a hard time arguing as to why exactly it is not.

This all gets dicey, and I often see really poor uses of language, so I'll be explicit and start from the bottom

JavaScript is a computer language, which is to say, narrowly, a set of conventions which allow us to read and interpret a bunch of text as having execution semantics—a fancy word for "way of interpreting the language as a set of instructions". Classes of programs called interpreters, compilers, transpilers, linters, highlighters, etc. all take text in and attempt to do something with this conventional understanding of how to execute the code.

Interpreters actually perform the execution semantics by operating some machine—usually your computer. You can think of them as a little man inside your computer flipping switches like "print this character" based on instruction written in your JavaScript program.

Compilers try to convert the JavaScript text to a new set of text which has execution semantics for a different language—perhaps one with the special property that computers can directly execute it.

Transpilers are a generalized form of compiler in that they take JavaScript text in and output text of some other language. The difference is thus a little subjective, but usually one thinks of a compiler as outputting very low level code and a transpiler as outputting high level code.

Linters, highlighters, type checkers, etc. all take in JavaScript text and output some kind of analytical product, highlighted text e.g., which is influenced by the execution semantics, but not actually representative of it.

Now, let's dig into execution semantics a bit. Generally, execution semantics involves a process of reading language text and arriving at either a description of an abstract machine or a description of observable side effects. What I'd like to suggest is that both of these assume the need for there to be some kind of "low-level API" either to operate the machine or to perform the observable effects. These are usually considered to be part of the runtime environment

The runtime environment or runtime is a set of assumed primitives that the language convention requires to exist in order to operate. As far as the language goes, there may be some assumption about their behavior, but they are unobservable. In the imagery of the interpreter above, the "man inside" just flicks the runtime's switches---he cannot personally inspect what they're doing.

The word runtime is usually abused to mean both the set of assumed primitives themselves and an actual instantiation of them.

So, now we get to something hairy. A language is a set of conventions which assumes the existence of a runtime in order to provide meaning to its execution semantics. It never "probes into them" as they are out of scope.

In order to actually use a language you want something like a compiler or interpreter alongside a runtime implementation. The compiler/interpreter and this runtime go hand in hand in actually executing your code.

Chrome's V8, often called an engine, is a package deal containing an interpreter, compiler, runtime implementation compatible with the runtime interface demanded by the ECMA standard JavaScript conventions.

So where does Node.js fit into this?

We have to break it into parts:

Node.js expands the JavaScript language by providing a larger set of runtime environment primitives—those which are outside the scope of ECMA's standards. These include things like file I/O. This means that Node.js changes the language and is in some sense a new language: "Node.js JavaScript"

Node.js, as a package, contains an interpreter and a compiler. It just steals these from V8.

Node.js provides an implementation of the Node.js runtime environment which allows "Node.js JavaScript" to be executed.

Node.js provides a set of standard libraries built atop the new primitives which make them more accessible to end users of "Node.js JavaScript".

So Node.js is a lot of things!

But is it a framework?

This is where terminology totally falls apart—nobody has a good, consistent, meaningful definition of what a framework actually is.

There are debates that rage: "what is a framework versus a library" and they end on unsatisfactory things like "a library is something you call and a framework is something that calls you". I don't even really want to give such a sad explanation the light of day—but JavaScript, and Node.js JavaScript in particular, is an enormous blow to this definition since the whole callback-passing technique means you are constantly switching between calling and being called.

In my personal opinion, there is something substantial here. I don't want to draw a bright line, but so I'll merely say

A set of code is library-like if it works like a set of legos: divisible and made for assembly. While there might be some examples for how to use the library, it is generally on the user themselves to assemble it toward their needs.

A set of code is framework-like if it is non-divisible and implies conventions*: pulling pieces of it apart can cause many assumptions to fail so you have to understand conventional use in order to use a framework properly.

This is a hand-wavey line to be sure, but I want to draw out a really interesting point about frameworks:

Frameworks imply a set of conventions of how to interpret code; they are therefore a language in their own right.

This might be something that people want to argue about as well, but if you bought my earlier definition that a language is just a set of conventions which give life to a block of text, then whenever you lay down a new layer of conventions you've built a new language. Perhaps with frameworks the raw materials are the semantic interpretations of their host language instead of raw text files, but the idea is the same!

So with all that said, I'm totally happy to call Node.js a framework even if it goes a bit against the norm! Node.js adds functionality to raw JavaScript in the way of expanding the language. With it brings new assumptions and tools for working in this expanded language. Functionally, these ideas are the same as the ideas of other well-accepted frameworks like Ruby on Rails.

I would argue that if at this moment you feel a bit queasy and want to argue that there's a huge divide between Ruby on Rails and Node.js in this way of things then I'm right there with you, of course. The kind of conceptual worlds that the two live in are dramatically different—I merely want to say that they're the same kind of thing: sets of conventions for expanding the powers of a base language within a particular domain.

I'm also happy to suggest that Node.js's domain is tiny and tight and thus the conventions it adds are simple to reason about and relatively easy to make correct. OTOH, Ruby on Rails lives in a complex, poorly defined domain of "business web applications" which means that the conventions it lays are certainly fuzzy and broken.

But all of this is a long way of saying, yeah, recruiters probably have no idea what they mean when the say that. I'm guessing "framework" just sounds like a better, more grokkable word than "runtime" or "engine".

Title: Is Node.js a framework?

Body:
I keep seeing recruiters, developers, etc. refer to Node.js as a framework. In my opinion, this is out of ignorance for what Node.js really is.

Oftentimes, in job descriptions, Node.js is grouped in as a library among AngularJS, React, etc. Generally, I see it as being entered by someone that doesn't know the difference (HR, a recruiter, etc.).

In my opinion, Node.js is a platform, or a runtime environment; it switches out the DOM API (JavaScript in the browser) for various other APIs, like the file system (since it runs as a server, and not in the browser).

Why is it that people think Node.js is a framework; am I wrong? Is it actually a framework?


答:
1) Learning a functional language will increase someones overall ability as a programmer however this only applies to those who want to learn and improve. Not every programmer wants to become better nor do they want change in their work environment (know your team.)

2) I can't argue with this.  You will have to pay for the 6 month learning curve of any new language however already knowing .net libraries eliminates the extra years required to learn new libraries.

3) Community support while smaller than C# does have quite a few highly skilled active F# developers posting on the web.  Don't forget that most language support is library support and there is great support for .NET.

The thousand pound gorilla here is risk management.  "I can be cutting edge but not bleeding edge."  I'd argue that F# is not bleeding edge.  It has been released with VS2010 and is directly supported by Microsoft.  Bleeding edge is "beta" and a disclaimer from Microsoft saying something about not being responsible for anything.

OwnerDisplayName: gradbot


答:
I have used this approach quite a lot for copying and sharing dev environments.

It works quite well -- except the current Linux obsession with "trying to be as pretty as Apple" means that the VMs display and desktop gets regularly trashed if you allow automatic updates.

The alternative of turning of updates lets have a reasonable chance of the desktop working when you fire up the VM -- but if you require the latest libraries for your development then its painful to get them up to date manually.

Title: What happened to VM based deployments?


答:
You need integration and system tests.

Unit tests are great about verifying that your code behaves as you expect. As you realize, it does nothing to challenge your assumptions or ensure your expectations are sane.

Unless your product has little interaction with external systems, or interacts with systems so well known, stable and documented that they can be mocked with confidence (this rarely happens in the real world) - unit tests are not enough.

The higher level your tests are, the more they'll protect you against the unexpected. That comes at a cost (convenience, speed, brittleness...), so unit tests should remain the foundation of your testing, but you need other layers, including - eventually - a tiny bit of human testing which goes a long way at catching stupid things that nobody thought about.

Title: How do I test a system where the objects are difficult to mock?

Body:
I am working with the following system:

```<code>Network Data Feed -> Third Party Nio Library -> My Objects via adapter pattern
</code>```

We recently had an issue where I updated the version of the library I was using, which, among other things, caused timestamps (which the third party library returns as long), to be changed from milliseconds after the epoch to nanoseconds after the epoch.

The Problem:

If I write tests that mock the third party library's objects, my test will be wrong if I have made a mistake about the third party library's objects. For example, I didn't realize that the timestamps changed precision, which resulted in a need for change in the unit test, because my mock returned the wrong data. This is not a bug in the library, it happened because I missed something in the documentation.

The problem is, I cannot be sure about the data contained in these data structures because I cannot generate real ones without a real data feed. These objects are big and complicated and have a lot of different pieces of data in them. The documentation for the third party library is poor.

The Question:

How can I set up my tests to test this behavior? I'm not sure I can solve this issue in a unit test, because the test itself can easily be wrong. Additionally, the integrated system is large and complicated and it's easy to miss something. For example, in the situation above, I had correctly adjusted the timestamp handling in several places, but I missed one of them. The system seemed to be doing mostly the right things in my integration test, but when I deployed it to production (which has a lot more data), the problem became obvious.

I do not have a process for my integration tests right now. Testing is essentially: try to keep the unit tests good, add more tests when things break, then deploy to my test server and make sure things seem sane, then deploy to production. This timestamp issue passed the unit tests because the mocks were created wrong, then it passed the integration test because it didn't cause any immediate, obvious problems. I do not have a QA department.


答:
If you were using a popular, stable library, then you could perhaps assume that it won't play nasty tricks on you. But if things like what you described happen with this library, then obviously, this is not one. After this bad experience, each and every time something goes wrong in your interaction with this library, you will need to examine not only the possibility that you have made a mistake, but also, the possibility that the library may have made a mistake. So, let's say that this is a library that you are "unsure" about.

One of the techniques employed with libraries that we are "unsure" about is to build an intermediate layer between our system and said libraries, which abstracts the functionality offered by the libraries, asserts that our expectations of the library are right, and also greatly simplifies our life in the future, should we decide to give that library the boot and replace it with another library that behaves better.


答:
Here is a procedure we use for eliminating duplicates.

select a standard comment prefix for duplicates (we use [dupe] right after the comment marker;

write specs with your teams about names to use for the duplicate procedure;

first round: everybody takes some files, and adds [dupe][procedure_arbitrary_name] before the duplicated procedure;

second round: everybody takes a procedure, or a subset of procedure, and assigns a value indicating the order of likeability of the different same-purpose implementations (the string will then be: [dupe][procedure_arbitrary_name][n]);

third round: the responsible for each procedure rewrites it in the relevant class;

fourth round: grep happy!

Title: How do you dive into large code bases?

Body:
What tools and techniques do you use for exploring and learning an unknown code base?

I am thinking of tools like grep, ctags, unit-tests, functional test, class-diagram generators, call graphs, code metrics like sloccount, and so on. I'd be interested in your experiences, the helpers you used or wrote yourself and the size of the code base with which you worked.

I realize that becoming acquainted with a code base is a process that happens over time, and familiarity can mean anything from "I'm able to summarize the code" to "I can refactor and shrink it to 30% of the size". But how to even begin?