问:
Falsy values vs null, undefined, or empty string
I've worked with jQuery over the years. However, recently, I've found myself getting deeper into the JavaScript language. Recently, I've heard about "truthy" and falsey values. However, I don't fully understand them. Currently, I have some code that looks like this:

```<code>var fields = options.fields || ['id', 'query'];
</code>```

I need to identify if fields is null, undefined, or has a length of 0. I know the long way is to do:

```<code>if ((fields === null) || (fields === undefined) || (fields.length === 0)) {
 ...
}
</code>```

My question is, is the following the same:

```<code>if (!fields)  {
 ...
}
</code>```

答:
Your code means:

```<code>var fields;
if (options.fields)
    fields = options.fields;
else
    fields = ['id', 'query'];
</code>```

Now options.fields is converted to a boolean value. By definition null, undefined, 0, "" is converted to false, (mostly) anything else is converted to true (but I don't want to be so precise).

It does not mean the same, because the fields.length === 0 line. Empty arrays and other objects are converted to true.

note: Javascript is sometimes a big mess... For example there is no real need for 2 type checking operators (typeof and instanceof). It just confuses ppl when true instanceof Boolean does not work and using typeof(true) == "boolean" is error prone because of typing a string without autocompletion. Maybe in some new versions these problems will be solved.

Body:
Your code means:

var fields;
if (options.fields)
    fields = options.fields;
else
    fields = ['id', 'query'];

Now options.fields is converted to a boolean value. By definition null, undefined, 0, "" is converted to false, (mostly) anything else is converted to true (but I don't want to be so precise).

It does not mean the same, because the fields.length === 0 line. Empty arrays and other objects are converted to true.

note: Javascript is sometimes a big mess... For example there is no real need for 2 type checking operators (typeof and instanceof). It just confuses ppl when true instanceof Boolean does not work and using typeof(true) == "boolean" is error prone because of typing a string without autocompletion. Maybe in some new versions these problems will be solved.


问:
Naming a recursive association entity
For my current project, I need to create a database table to store a recursive association.  I've done a lot of searching and have read answers on questions, such as Naming convention for associative entity and How do you name your many-to-many relationship tables?, but they don't discuss the case of a recursive relationship.

My company ships out inventory, and they want some parts to automatically include other parts on an order.  For example, an order for a Widget will automatically have a Widget Guide added automatically.

The table's schema will basically just be two columns, each a foreign key to the InventoryProduct table.  My struggle has been naming this table and these columns.  I've considered something like:

```<code>InventoryAssociation
--------------------
ParentInventoryProductId : int, FK
ChildInventoryProductId : int, FK
</code>```

But I don't feel like "InventoryAssociation" is a great name for the table/entity, nor do I think the association between the two inventory products is really a parent/child relationship.

Does anyone have suggestions for better names?  Thanks!

答:
There are better patterns for describing hierarchical data structures for example the nested set model. (In your case you probably need a tree identifier because you want to describe multiple trees.)

About the naming. If you are not sure you describe a parent/child relationship, then it is better to describe a graph with nodes and links. In your case the nodes are the InventoryProducts and the links are the relationships between them. So I'd use

```<code>InventoryRelationships
--------------------
SourceInventoryProductId : int, FK
TargetInventoryProductId : int, FK
</code>```

and possibly another fields to describe the type of the relationship. (Btw. a graph database like neo4j would be better if you want to work on huge graphs.) If there is only a single relationship type. Then it should be included by the table name.

Currently I cannot find a better term that the inventory products are related to each other, but I'll check the link relations and some other vocabs, maybe I find a better solution. In the schema.org vocab there is a Product/isAccessoryOrSparePartFor property. So maybe the

```<code>InventoryAccessories
--------------------
InventoryProductId : int, FK
AcessoryInventoryProductId : int, FK
</code>```

or something like that would work for you. If not, then in your case I would try other business related RDF vocabs.

ContentLicense: CC BY-SA 3.0

Title: Naming a recursive association entity

Body:
There are better patterns for describing hierarchical data structures for example the nested set model. (In your case you probably need a tree identifier because you want to describe multiple trees.)

About the naming. If you are not sure you describe a parent/child relationship, then it is better to describe a graph with nodes and links. In your case the nodes are the InventoryProducts and the links are the relationships between them. So I'd use

InventoryRelationships
--------------------
SourceInventoryProductId : int, FK
TargetInventoryProductId : int, FK

and possibly another fields to describe the type of the relationship. (Btw. a graph database like neo4j would be better if you want to work on huge graphs.) If there is only a single relationship type. Then it should be included by the table name.

Currently I cannot find a better term that the inventory products are related to each other, but I'll check the link relations and some other vocabs, maybe I find a better solution. In the schema.org vocab there is a Product/isAccessoryOrSparePartFor property. So maybe the

InventoryAccessories
--------------------
InventoryProductId : int, FK
AcessoryInventoryProductId : int, FK

or something like that would work for you. If not, then in your case I would try other business related RDF vocabs.


问:
I get dependency injection, but can someone help me understand the need for an IoC container?
I apologize if this seems like yet another repeat of the question, but every time I find an article regarding the topic, it mostly just talks about what DI is. So, I get DI, but I'm trying to understand the need for an IoC container, which everyone seems to be getting into. Is the point of an IoC container really just to "auto-resolve" the concrete implementation of the dependencies? Maybe my classes tend to not have several dependencies and maybe that's why I don't see the big deal, but I want to make sure that I'm understanding the utility of the container correctly.

I typically break my business logic out into a class that might look something like this:

```<code>public class SomeBusinessOperation
{
    private readonly IDataRepository _repository;

    public SomeBusinessOperation(IDataRespository repository = null)
    {
        _repository = repository ?? new ConcreteRepository();
    }

    public SomeType Run(SomeRequestType request)
    {
        // do work...
        var results = _repository.GetThings(request);

        return results;
    }
}
</code>```

So it only has the one dependency, and in some cases it might have a second or third, but not all that often. So anything that calls this can pass it's own repo or allow it to use the default repo.

As far as my current understanding of an IoC container goes, all the container does is resolve IDataRepository. But if that's all it does, then I'm not seeing a ton of value in it since my operational classes already define a fallback when no dependency passed in. So the only other benefit I can think of is that if I have several operations like this use the same fallback repo, I can change that repo in one place which is the registry/factory/container. And that's great, but is that it?

答:
There are a number of reasons why you might want to use an IoC container.

Unreferenced dlls

You can use an IoC container to resolve a concrete class from an unreferenced dll.  This means that you can take dependencies entirely on the abstraction - i.e. the interface.

Avoid the use of new

An IoC container means that you can completely remove the use of the new keyword for creating a class.  This has two effects.  The first is that it decouples your classes.  The second (which is related) is that you can drop in mocks for unit testing.  This is incredibly useful, particularly when you are interacting with a long running process.

Write Against Abstractions

Using an IoC container to resolve your concrete dependencies for you allows you to write your code against abstractions, rather than implementing every concrete class you need as you need it.  For example, you may need your code to read data from a database.  Instead of writing the database interaction class, you simply write an interface for it and code against that.  You can use a mock to test the functionality of the code you're developing as you're developing it, rather than relying on developing the concrete database interaction class before you can test the other code.

Avoid brittle code

Another reason for using an IoC container is that by relying on the IoC container to resolve your dependencies, you avoid the need to change every single call to a class constructor when you add or remove a dependency.  The IoC container will automatically resolve your dependencies.  This isn't a huge issue when you're creating a class once, but it is a gigantic issue when you're creating the class in a hundred places.

Lifetime management and unmanaged resouce cleanup

The final reason I will mention is the management of object lifetimes.  IoC containers often provide the ability to specify the lifetime of an object.  It makes a lot of sense to specify the lifetime of an object in an IoC container rather than trying to manually manage it in code.  Manual lifetime management can be very difficult.  This can be useful when dealing with objects that require disposal.  Instead of manually managing the disposal of your objects, some IoC containers will manage the disposal for you, which can help prevent memory leaks and simplify your codebase.

The problem with the sample code that you have provided is that the class you're writing has a concrete dependency on the ConcreteRepository class.  An IoC container would remove that dependency.


问:
IOC Containers break OOP Principles
What is the purpose of IOC Containers?  The combined reasons for it can be simplified to the following:

When using OOP/SOLID Development principles, Dependency Injection gets messy.  Either you have the top-level entry points managing dependencies for multiple levels below themselves and passing dependencies recursively through construction, or you have somewhat duplicate code in factory/builder patterns and interfaces that build dependencies as you need them.

There is no OOP/SOLID way to perform this AND have super pretty code.

If that previous statement is true, then how do IOC Containers do it?  As far as I know, they aren’t employing some unknown technique that can't be done with manual D.I.  So the only explination is that IOC Containers break OOP/SOLID Principles by using static objects private accessors.

Do IOC Containers break the following principles behind the scenes?  This is the real question since I have a good understanding, but have a feeling somebody else has a better understanding:

Scope control.  Scope is the reason for nearly every decision I make on my code design.  Block, Local, Module, Static/Global.  Scope should be very explicit, as much at block-level and as few at Static as possible.  You should see declarations, instantiations, and lifecycle endings.  I trust the language and GC to manage scope as long as I’m explicit with it.  In my research I’ve found that IOC Containers set up most or all dependencies as Static and control them through some AOP implementation behind the scenes.  So nothing is transparent.

Encapsulation.  What is the purpose of encapsulation?  Why should we keep private members so?  For practical reasons it is so implementors of our API can’t break the implementation by changing the state (which should be managed by the owner class).  But also, for security reasons, it’s so injections can’t occur that overtake our member states and bypass validation and class control.  So anything (Mocking frameworks or IOC frameworks) that somehow injects code before compile time to allow external access to private members is pretty huge.

Single Responsibility Principle.  On the surface, IOC Containers seem to make things cleaner.  But imagine how you would accomplish the same thing without the helper frameworks.  You would have constructors with a dozen or so dependencies being passed in.  That doesn’t mean cover it up with IOC Containers, it is a good thing!  It’s a sign to re-factor your code and follow SRP.

Open/Closed.   Just like SRP isn’t Class-Only (I apply SRP down to single-responsibility lines, let alone methods).  Open/Closed is not just a high level theory to not alter the code of a class.  It’s a practice of understanding the configuration of your program and having control over what gets altered and what gets extended.  IOC Containers can change the way your classes work altogether partially because:

a.   The main code isn’t making the determination of switching out
dependencies, the framework configuration is.

b.   The scope could be altered at a time that isn’t controlled by the
calling members, it is instead determined externally by a static
framework.

So the configuration of the class isn’t really closed is it, it alters itself based on the configuration of a third party tool.

The reason this is a question is because I am not necessarily a master of all IOC Containers.  And while the idea of an IOC Container is nice, they appear to just be a façade that covers up poor implementation.  But in order to accomplish external Scope control, Private member access, and Lazy loading, a lot of non-trivial questionable things have to go on.  AOP is great, but the way it is accomplished through IOC Containers is also questionable.

I can trust C# and the .NET GC to do what I expect it to.  But I can’t put that same trust in a third party tool that is altering my compiled code to perform workarounds to things I wouldn’t be able to do manually.

E.G.: Entity Framework and other ORMs create strongly Typed objects and map them to database entities, as well as provide boiler-plate basic functionality to perform CRUD.  Anybody could build their own ORM and continue to follow OOP/SOLID Principles manually.  But those frameworks help us so we don’t have to re-invent the wheel every time.  Whereas IOC Containers, it seems, help us purposely work around OOP/SOLID Principles and cover it up.

答:
Don't IOC containers both break, and allow coders to break, a lot of OOP/SOLID principles?

The static keyword in C# allows developers to break a lot of OOP/SOLID principles but it's still a valid tool in the right circumstances.

IoC containers allow for well structured code and reduce the cognitive burden on developers.  An IoC container can be used to make following SOLID principles much easier.  It can be misused, sure, but if we excluded the use of any tool that can be misused we would have to give up programming altogether.

So while this rant raises some valid points about poorly written code, it is not exactly a question and it is not exactly useful.

Title: IOC Containers break OOP Principles


答:
According to the single responsibility principle every class must have only a single responsibility. Creating new instances of classes is just another responsibility, so you have to encapsulate this kind of code in one or more classes. You can do that using any creational patterns, for example factories, builders, DI containers etc...

There are other principles like inversion of control and dependency inversion. In this context they are related to the instantiation of dependencies. They state that the high level classes must be decoupled from the low level classes (dependencies) they use. We can decouple things by creating interfaces. So the low level classes have to implement specific interfaces and the high level classes have to utilize instances of classes which implement these interfaces. (note: REST uniform interface constraint applies the same approach on a system level.)

The combination of these principles by example (sorry for the low quality code, I used some ad-hoc language instead of C#, since I don't know that):

No SRP, no IoC

```<code>class SomeHighLevelService
{
    public doFooBar(){
        Crap crap = doFoo();
        doBar(crap);
    }

    public Crap doFoo(){
        //...
        return crap;
    }

    public doBar(Crap crap){
        //...
    }
}

SomeHighLevelService service = new SomeHighLevelService();
service.doFooBar();
</code>```

Closer to SRP, no IoC

```<code>class SomeHighLevelService
{
    public SomeHighLevelService(){
        Foo foo = new Foo();
        Bar bar = new Bar();
    }

    public doFooBar(){
        Crap crap = foo.doFoo();
        bar.doBar(crap);
    }
}

class Foo {
    public Crap doFoo(){
        //...
        return crap;
    }
}

class Bar {
    public doBar(Crap crap){
        //...
    }
}

SomeHighLevelService service = new SomeHighLevelService();
service.doFooBar();
</code>```

Yes SRP, no IoC

```<code>class HighLevelServiceProvider {
    public SomeHighLevelService getSomeHighLevelService(){
        SomeHighLevelService service = new SomeHighLevelService();
        service.setFoo(this.getFoo());
        service.getBar(this.getBar());
        return service;
    }

    private Foo getFoo(){
        return new Foo();
    }

    private Bar getBar(){
        return new Bar();
    }
}

class SomeHighLevelService
{
    public setFoo(Foo foo){
        this.foo = foo;
    }

    public setBar(Bar bar){
        this.bar = bar;
    }

    public doFooBar(){
        Crap crap = foo.doFoo();
        bar.doBar(crap);
    }

}

class Foo {
    public Crap doFoo(){
        //...
        return crap;
    }
}

class Bar {
    public doBar(Crap crap){
        //...
    }
}

HighLevelServiceProvider provider = new HighLevelServiceProvider();
SomeHighLevelService service = provider.getSomeHighLevelService();
service.doFooBar();
</code>```

Yes SRP, yes IoC

```<code>interface HighLevelServiceProvider {
    SomeHighLevelService getSomeHighLevelService();
}

interface SomeHighLevelService {
    doFooBar();
}

interface Foo {
    Crap doFoo();
}

interface Bar {
    doBar(Crap crap);
}

class ConcreteHighLevelServiceContainer implements HighLevelServiceProvider {
    public SomeHighLevelService getSomeHighLevelService(){
        SomeHighLevelService service = new ConcreteHighLevelService();
        service.setFoo(this.getFoo());
        service.getBar(this.getBar());
        return service;
    }

    private Foo getFoo(){
        return new ConcreteFoo();
    }

    private Bar getBar(){
        return new ConcreteBar();
    }
}

class ConcreteHighLevelService implements SomeHighLevelService
{
    public setFoo(Foo foo){
        this.foo = foo;
    }

    public setBar(Bar bar){
        this.bar = bar;
    }

    public doFooBar(){
        Crap crap = foo.doFoo();
        bar.doBar(crap);
    }

}

class ConcreteFoo implements Foo {
    public Crap doFoo(){
        //...
        return crap;
    }
}

class ConcreteBar implements Bar {
    public doBar(Crap crap){
        //...
    }
}

HighLevelServiceProvider provider = new ConcreteHighLevelServiceContainer();
SomeHighLevelService service = provider.getSomeHighLevelService();
service.doFooBar();
</code>```

So we ended up having a code in which you can replace every concrete implementation with another which implements the same interface ofc. So this is good because the participating classes are decoupled from each other, they know only the interfaces. Another advantage that the code of the instantiation is reusable.

Title: I get dependency injection, but can someone help me understand the need for an IoC container?

Body:
I apologize if this seems like yet another repeat of the question, but every time I find an article regarding the topic, it mostly just talks about what DI is. So, I get DI, but I'm trying to understand the need for an IoC container, which everyone seems to be getting into. Is the point of an IoC container really just to "auto-resolve" the concrete implementation of the dependencies? Maybe my classes tend to not have several dependencies and maybe that's why I don't see the big deal, but I want to make sure that I'm understanding the utility of the container correctly.

I typically break my business logic out into a class that might look something like this:

```<code>public class SomeBusinessOperation
{
    private readonly IDataRepository _repository;

    public SomeBusinessOperation(IDataRespository repository = null)
    {
        _repository = repository ?? new ConcreteRepository();
    }

    public SomeType Run(SomeRequestType request)
    {
        // do work...
        var results = _repository.GetThings(request);

        return results;
    }
}
</code>```

So it only has the one dependency, and in some cases it might have a second or third, but not all that often. So anything that calls this can pass it's own repo or allow it to use the default repo.

As far as my current understanding of an IoC container goes, all the container does is resolve IDataRepository. But if that's all it does, then I'm not seeing a ton of value in it since my operational classes already define a fallback when no dependency passed in. So the only other benefit I can think of is that if I have several operations like this use the same fallback repo, I can change that repo in one place which is the registry/factory/container. And that's great, but is that it?

Body:
According to the single responsibility principle every class must have only a single responsibility. Creating new instances of classes is just another responsibility, so you have to encapsulate this kind of code in one or more classes. You can do that using any creational patterns, for example factories, builders, DI containers etc...

There are other principles like inversion of control and dependency inversion. In this context they are related to the instantiation of dependencies. They state that the high level classes must be decoupled from the low level classes (dependencies) they use. We can decouple things by creating interfaces. So the low level classes have to implement specific interfaces and the high level classes have to utilize instances of classes which implement these interfaces. (note: REST uniform interface constraint applies the same approach on a system level.)

The combination of these principles by example (sorry for the low quality code, I used some ad-hoc language instead of C#, since I don't know that):

No SRP, no IoC

class SomeHighLevelService
{
    public doFooBar(){
        Crap crap = doFoo();
        doBar(crap);
    }

    public Crap doFoo(){
        //...
        return crap;
    }

    public doBar(Crap crap){
        //...
    }
}

SomeHighLevelService service = new SomeHighLevelService();
service.doFooBar();

Closer to SRP, no IoC

class SomeHighLevelService
{
    public SomeHighLevelService(){
        Foo foo = new Foo();
        Bar bar = new Bar();
    }

    public doFooBar(){
        Crap crap = foo.doFoo();
        bar.doBar(crap);
    }
}

class Foo {
    public Crap doFoo(){
        //...
        return crap;
    }
}

class Bar {
    public doBar(Crap crap){
        //...
    }
}

SomeHighLevelService service = new SomeHighLevelService();
service.doFooBar();

Yes SRP, no IoC

class HighLevelServiceProvider {
    public SomeHighLevelService getSomeHighLevelService(){
        SomeHighLevelService service = new SomeHighLevelService();
        service.setFoo(this.getFoo());
        service.getBar(this.getBar());
        return service;
    }

    private Foo getFoo(){
        return new Foo();
    }

    private Bar getBar(){
        return new Bar();
    }
}

class SomeHighLevelService
{
    public setFoo(Foo foo){
        this.foo = foo;
    }

    public setBar(Bar bar){
        this.bar = bar;
    }

    public doFooBar(){
        Crap crap = foo.doFoo();
        bar.doBar(crap);
    }

}

class Foo {
    public Crap doFoo(){
        //...
        return crap;
    }
}

class Bar {
    public doBar(Crap crap){
        //...
    }
}

HighLevelServiceProvider provider = new HighLevelServiceProvider();
SomeHighLevelService service = provider.getSomeHighLevelService();
service.doFooBar();

Yes SRP, yes IoC

interface HighLevelServiceProvider {
    SomeHighLevelService getSomeHighLevelService();
}

interface SomeHighLevelService {
    doFooBar();
}

interface Foo {
    Crap doFoo();
}

interface Bar {
    doBar(Crap crap);
}

class ConcreteHighLevelServiceContainer implements HighLevelServiceProvider {
    public SomeHighLevelService getSomeHighLevelService(){
        SomeHighLevelService service = new ConcreteHighLevelService();
        service.setFoo(this.getFoo());
        service.getBar(this.getBar());
        return service;
    }

    private Foo getFoo(){
        return new ConcreteFoo();
    }

    private Bar getBar(){
        return new ConcreteBar();
    }
}

class ConcreteHighLevelService implements SomeHighLevelService
{
    public setFoo(Foo foo){
        this.foo = foo;
    }

    public setBar(Bar bar){
        this.bar = bar;
    }

    public doFooBar(){
        Crap crap = foo.doFoo();
        bar.doBar(crap);
    }

}

class ConcreteFoo implements Foo {
    public Crap doFoo(){
        //...
        return crap;
    }
}

class ConcreteBar implements Bar {
    public doBar(Crap crap){
        //...
    }
}

HighLevelServiceProvider provider = new ConcreteHighLevelServiceContainer();
SomeHighLevelService service = provider.getSomeHighLevelService();
service.doFooBar();

So we ended up having a code in which you can replace every concrete implementation with another which implements the same interface ofc. So this is good because the participating classes are decoupled from each other, they know only the interfaces. Another advantage that the code of the instantiation is reusable.


问:
Exercise 3.6: Skiena Algorithm Design Manual
I am preparing for interview and try to solve the exercise problems of the book.

3-6. [5] Describe how to modify any balanced tree data structure such that search,
  insert, delete, minimum, and maximum still take O(log n) time each, but successor
  and predecessor now take O(1) time each. Which operations have to be modified
  to support this?

Solution: Maintain extra pointers to the successor and predecessor. Update the pointers on
insert and delete.

Nothing else right? Or is there some other trick involved.

Thanks

答:
```<code>`void delete( root, val )
{
    node = findNode( root, &par );
    nodePred = node->pred;
    nodeSucc = node->succ;
    if ( nodeSucc )
        nodeSucc->pred = nodePred;
    if( nodePred )
        nodePred->succ = nodeSucc;
    // Node delete the node as usual as only parent child relation changes and
    // succ pred relation will still remain intact
}

void insert( root, node )
{
    if ( root == NULL ) {
        root = node;
        node->succ = node->pred = NULL;
        return;
    }
    curr = root;
    while ( curr ) {
        par = curr;
        curr = node->val < curr->val ?  curr->left : curr->right;
    }
    if ( node->val < par->val ) {
        par->left = node;
        parPred = par->pred;
        node->succ = par;
        node->pred = parPred;
        par->pred = node;
        if ( oldPred )
            oldPred->succ = node;
    } else {
        par->right = node;
        oldSucc = par->succ;
        node->pred = par;
        node->succ = oldSucc;
        par->succ = node;
        if ( oldSucc )
            oldSucc->pred = node;
    }
}`
</code>```


答:
Does using an IoC container necessarily violate OOP/SOLID principles? No.

Can you use IoC containers in such a way that they violate OOP/SOLID principles? Yes.

IoC containers are just frameworks for managing dependencies in your application.

You stated Lazy injections, property setters, and a few other features I haven't yet felt the need to use, which I agree with can give you a less than optimal design.  However, the usages of these specific features are due to limitations in the technology you're implementing IoC containers in.

For example, ASP.NET WebForms, you are required to use property injection as it's not possible to instantiate a Page.  This is understandable because WebForms was never designed with strict OOP paradigms in mind.

ASP.NET MVC on the other hand, it's entirely possible to use an IoC container using the very OOP/SOLID friendly constructor injection.

In this scenario (using constructor injection), I believe it promotes SOLID principles for the following reasons:

Single Responsibility Principle - Having many smaller classes allows these classes to be very specific and have one reason for existing.  Using an IoC container makes organizing them much easier.

Open/Closed - This is where using an IoC container really shines, you can extend the functionality of a class by way of injecting different dependencies.  Having dependencies that you inject lets you modify the behavior of that class.  A good example is changing the class that you're injecting by writing a decorator to say add caching or logging.  You can completely change implementations of your dependencies if written in an appropriate level of abstraction.

Liskov Substitution Principle - Not really relevant

Interface Segregation Principle - You can assign multiple interfaces to a single concrete time if you want, any IoC container worth a grain of salt will easily do this.

Dependency Inversion - IoC containers let you do dependency inversion easily.

You define a bunch of dependencies and declare the relationships and scopes, and bing bang boom: you magically have some addon that alters your code or I.L. at some point and makes things work. That isn't explicit or transparent.

It is both explicit and transparent, you need to tell your IoC container how to wire up dependencies and how to manage object lifetimes.  This can be either by convention, by configuration files, or by code written in your system's main applications.

I agree that when I write or read code using IOC containers, it gets rid of some slightly inelegant code.

This is the whole reason for OOP/SOLID, to make systems manageable.  Using an IoC container is inline with that goal.

The writer of that class says, "If we didn't use an IOC Container, the Constructor would have a dozen parameters!!! That's horrible!"

A class with 12 dependencies is probably an SRP violation no matter what context you're using it in.

Title: IOC Containers break OOP Principles

Body:
What is the purpose of IOC Containers?  The combined reasons for it can be simplified to the following:

When using OOP/SOLID Development principles, Dependency Injection gets messy.  Either you have the top-level entry points managing dependencies for multiple levels below themselves and passing dependencies recursively through construction, or you have somewhat duplicate code in factory/builder patterns and interfaces that build dependencies as you need them.

There is no OOP/SOLID way to perform this AND have super pretty code.

If that previous statement is true, then how do IOC Containers do it?  As far as I know, they aren’t employing some unknown technique that can't be done with manual D.I.  So the only explination is that IOC Containers break OOP/SOLID Principles by using static objects private accessors.

Do IOC Containers break the following principles behind the scenes?  This is the real question since I have a good understanding, but have a feeling somebody else has a better understanding:

Scope control.  Scope is the reason for nearly every decision I make on my code design.  Block, Local, Module, Static/Global.  Scope should be very explicit, as much at block-level and as few at Static as possible.  You should see declarations, instantiations, and lifecycle endings.  I trust the language and GC to manage scope as long as I’m explicit with it.  In my research I’ve found that IOC Containers set up most or all dependencies as Static and control them through some AOP implementation behind the scenes.  So nothing is transparent.

Encapsulation.  What is the purpose of encapsulation?  Why should we keep private members so?  For practical reasons it is so implementors of our API can’t break the implementation by changing the state (which should be managed by the owner class).  But also, for security reasons, it’s so injections can’t occur that overtake our member states and bypass validation and class control.  So anything (Mocking frameworks or IOC frameworks) that somehow injects code before compile time to allow external access to private members is pretty huge.

Single Responsibility Principle.  On the surface, IOC Containers seem to make things cleaner.  But imagine how you would accomplish the same thing without the helper frameworks.  You would have constructors with a dozen or so dependencies being passed in.  That doesn’t mean cover it up with IOC Containers, it is a good thing!  It’s a sign to re-factor your code and follow SRP.

Open/Closed.   Just like SRP isn’t Class-Only (I apply SRP down to single-responsibility lines, let alone methods).  Open/Closed is not just a high level theory to not alter the code of a class.  It’s a practice of understanding the configuration of your program and having control over what gets altered and what gets extended.  IOC Containers can change the way your classes work altogether partially because:

a.   The main code isn’t making the determination of switching out
dependencies, the framework configuration is.

b.   The scope could be altered at a time that isn’t controlled by the
calling members, it is instead determined externally by a static
framework.

So the configuration of the class isn’t really closed is it, it alters itself based on the configuration of a third party tool.

The reason this is a question is because I am not necessarily a master of all IOC Containers.  And while the idea of an IOC Container is nice, they appear to just be a façade that covers up poor implementation.  But in order to accomplish external Scope control, Private member access, and Lazy loading, a lot of non-trivial questionable things have to go on.  AOP is great, but the way it is accomplished through IOC Containers is also questionable.

I can trust C# and the .NET GC to do what I expect it to.  But I can’t put that same trust in a third party tool that is altering my compiled code to perform workarounds to things I wouldn’t be able to do manually.

E.G.: Entity Framework and other ORMs create strongly Typed objects and map them to database entities, as well as provide boiler-plate basic functionality to perform CRUD.  Anybody could build their own ORM and continue to follow OOP/SOLID Principles manually.  But those frameworks help us so we don’t have to re-invent the wheel every time.  Whereas IOC Containers, it seems, help us purposely work around OOP/SOLID Principles and cover it up.


问:
writing functional/integration tests for python
I am new to python and functional/integration tests as a whole. I know how to write unit tests, but in this case i do not need isolation for specific functions, rather i need my python script to be run with some command line parameters and then tested for output(for example if the program is successful, a specific REST call is made).
So i need a a way to write an automated test that would treat the whole script as a black box, calling it with some arguments and watching what kind of output comes out the other end. I've heard that it's possible to do this with the standard pyunit, but i'm very unclear on how to approach running whole scripts instead of just functions in pyunit. Are there any ways to achieve what i've described? If so, could i please have a small example? Maybe there is a tool for just this kind of thing?</p>

答:
If your "whole" script is written as a set of functions including "main" function and is ending like

```<code>if __name__ == "__main__":
    main()
</code>```

then all you need is actually call that main. If you have some command line parameters that are parsed, you can provide them as well.

As for REST calls - you use mocks. You either mock the actual call (if it's enough for you to just check that it was correct) or you set up a mock REST server and point your app to it.

For example, my app has an OpenID authentication. So I created my own simple OpenID server and point my application to use it as provider. That is rather slow, so I use it only when I run scenarios involving authentication. In all other cases I just patch the authentication method (I'm using tornado and I'm patching get_current_user to return a predefined user ID).

Body:
If your "whole" script is written as a set of functions including "main" function and is ending like

if __name__ == "__main__":
    main()

then all you need is actually call that main. If you have some command line parameters that are parsed, you can provide them as well.

As for REST calls - you use mocks. You either mock the actual call (if it's enough for you to just check that it was correct) or you set up a mock REST server and point your app to it.

For example, my app has an OpenID authentication. So I created my own simple OpenID server and point my application to use it as provider. That is rather slow, so I use it only when I run scenarios involving authentication. In all other cases I just patch the authentication method (I'm using tornado and I'm patching get_current_user to return a predefined user ID).


问:
How to unit test code that downloads a file from a github repo
This is my solution's structure:

```<code>Storage.csproj
   > FileDownloader.cs
   > GitHubProvider.cs (implements IStorageProvider)
   > IStorageProvider.cs

Storage.Test.csproj
   > FileDownloaderFixture.cs
</code>```

The idea is that I can use the class FileDownloader, inject it with a IStorageProvider, call myFileDownloader.Download(url), and it will download the file to the filesystem.

Now, the question is: how do I unit test this? I wrote the following test:

```<code>[TestClass]
    public class FileDownloaderFixture
    {
        [TestMethod]
        public void TestDownload()
        {
            //Arrange
            var storageProviderMock = new Mock<IStorageProvider>(MockBehavior.Strict);
            storageProviderMock.Setup(s => s.Download("http://host.com/file.txt")).Returns(Status.Success);
            var myFileDownloader = new FileDownloader(storageProviderMock.Object);

            //Act
            myFileDownloader.DownloadFile("http://host.com/file.txt");

            //Assert
            storageProviderMock.Verify(s => s.Download("http://host.com/file.txt"));
        }
    }
</code>```

It looks nice and clean, but... it's useless. It doesn't prove the fact that the code in GitHubProvider.Download(url) works. I don't even use methods from GitHubProvider. So what's the point?

The only other idea I have is to set up a test GitHub account & repository, and work with that. But this solution won't work very well if, for instance, I had to pay for each access to the repository. What then?

答:
The file downloader has two external dependencies: a connection to Git is where data comes in. A connection to the file system is where data goes out.

To be a unit test, your test should abstract from both these collaborators - you don't want to test the Git network protocol, and you don't want to test file system code either. That leaves the behaviour of your class simple and easily testable: it issues commands to the Git hub to obtain data and issues commands to the storage system to write them. That makes for a pretty primitive test, and this is good. A class should do one thing, and do it well. ideally, it should be so simple that it is obviously correct (and have a unit test as well, for cases when the obviousness is misleading).

You're right that this doesn't prove that your system successfully downloads stuff. That is the task of an integration, acceptance, or load test, and you need those as well, but as far as unit testing goes, there is nothing wrong with tests that seem almost trivial. Your project will grow in complexity soon enough, and without a safety net composed of almost trivial checks, you can't manage that growth responsibly.


答:
Your test is not useless. A unit test FileDownloaderFixture tests the FileDownloader not more, not less. Don't expect a unit test to test more than one unit.

To test GitHubProvider.Download, you need a second, different test. Since there is an external resource involved which is almost completly out of control of your test environment, it probably does not make sense to implement this test as part of your "regular" unit test suite. So the better strategy for such a component is often to provide a manual or "semiautomatic" test, to be run manually whenever you change something in GitHubProvider. This test may involve the use of a GitHub account & repository. You can use your unit testing tool for this test, but if the manual test needs some additional manual steps, you can also implement something completely different (like a small test program with a simple UI or command line interface, whatever causes the smallest effort) That's a feasible approach as long as the internals of GitHubProvider is not too complex.

Title: How to unit test code that downloads a file from a github repo

Body:
This is my solution's structure:

```<code>Storage.csproj
   > FileDownloader.cs
   > GitHubProvider.cs (implements IStorageProvider)
   > IStorageProvider.cs

Storage.Test.csproj
   > FileDownloaderFixture.cs
</code>```

The idea is that I can use the class FileDownloader, inject it with a IStorageProvider, call myFileDownloader.Download(url), and it will download the file to the filesystem.

Now, the question is: how do I unit test this? I wrote the following test:

```<code>[TestClass]
    public class FileDownloaderFixture
    {
        [TestMethod]
        public void TestDownload()
        {
            //Arrange
            var storageProviderMock = new Mock<IStorageProvider>(MockBehavior.Strict);
            storageProviderMock.Setup(s => s.Download("http://host.com/file.txt")).Returns(Status.Success);
            var myFileDownloader = new FileDownloader(storageProviderMock.Object);

            //Act
            myFileDownloader.DownloadFile("http://host.com/file.txt");

            //Assert
            storageProviderMock.Verify(s => s.Download("http://host.com/file.txt"));
        }
    }
</code>```

It looks nice and clean, but... it's useless. It doesn't prove the fact that the code in GitHubProvider.Download(url) works. I don't even use methods from GitHubProvider. So what's the point?

The only other idea I have is to set up a test GitHub account & repository, and work with that. But this solution won't work very well if, for instance, I had to pay for each access to the repository. What then?


问:
Who can learn to program?
I always hesitate when talking to professors about trying to improve the percentage of people who graduate with a CS type degree compared to the number that start out thinking that is what they want. On one hand I really do think it is important for professionals to be involved and give this feedback, on the other hand it would be better if less sub-par students ended up with CS degrees.

I don't think every mind is built for this field and you have to be a good life long student. You have to have a high degree of patience and problem solving skills just to eek by. If you do have the "right" kind of brain, those hard problems are what drives you to continue. If you just get a long list of easy problems you get bored so these people are actually not good at more repetitive jobs. I don't need to go into all the details... if you are reading this you probably know what I'm getting at.

So the question is: How do you find the balance of a degree program that is accessible to enough people to be funded and considered successful but also doesn't turn out people who aren't really cut out for the job? Maybe a better question is, what metric do you use to know if the changes you are making in a degree program are making it better? I don't know that a higher graduation rate is a good metric. And it seems that the feedback that you could try to capture many years later about the jobs that the graduates hold would be too far delayed.

I've struggled with this question for a long time, mostly because I don't think there is an answer. But I thought I'd ask to see if anyone knows of any research that has actually been done on it.

Addition: I recently had a very wise professor remind me that not everyone who graduates with a CS degree even wants to be a full-time programmer once they have actually discovered what that means. But, with the education that they received they could possibly make great Project Managers, Managers, system admins, etc. I think this was a very good point that I hadn't thought to consider here. There are a very high percentage of people who don't end up working in the field they majored in, CS isn't an exception to that. Having the extra folks helps not only in budget for the degree but also to expand the percentage of non-programmers who still know enough about it to work with programmers.

答:
A few aspects would help, I think -

Profs who are aware of the modern real world. If they are able to talk about current tech and how it fits into theoretical frameworks, that's much more relevant to history-unaware undergrads than dissections of VAXen without reference to the current tech.

Department-supported internships. If the dept can guarantee at least 2 summers of paid work with tech companies, then there's a great incentive to stick around.

Frankly, modern computer science students are much more blessed than ones living even 5-10 years ago. The ability to purchase a low-end system, and then to install a VM, and learn multiple languages, operating systems, etc, for free is such an enabler, it's hard to overstate it.

Of course, the seminal people like Hopper and Knuth taught themselves without the shinies. Genius will out.

Title: Who can learn to program?

ContentLicense: CC BY-SA 2.5


问:
Real time middleware system: Direct DB access vs REST API access
I'm developing a complex environment which involves a web application, a mobile app and a real time middleware system which accesses the DB for on-site tag readings. Currently, the web application exposes some services over a REST API, which are accessed by the mobile app to let it perform its business work (in this case, time delay is not critical). However, for my middleware system, I access the DB directly (through a ORM), in order to provide faster responses.

Am I doing it right or should I take advantage from the REST API to access the information to be processed in the middleware system too? Actually, this system, the web application and the DB belong to the same physical server.

Any recommendation about that will be welcomed!

答:
From personal experience I suspect you are approaching it in a sensible way - there would be a performance hit by using the RESTful API for 'internal' access.

However, what you might consider is building an internal linking library that takes internal requests to access the DB and convert it into a form that is essentially what the RESTful API uses internally once it has accepted/authenticated and translated the request messages.

This is a model that splits the RESTful API into two layers - the message transport and control layer facing the Internet or network, and the internal message handlers. By having a 'local' linking library that bypasses the top layer but then goes through a common layer of handlers, you keep the advantages of one code base, one monitoring and maintenance/audit system etc.


问:
LDAP users synchronization
I'm looking for a way to synchronize a users database between a piece of software and a ldap directory. Currently I'm thinking of three possibilities to keep the track of a specific user :

Guid : it seems to be AD-specific but I guess other directories have an equivalent unique identifier. I can use a LDAP query (&(objectClass=user)(guid=xxx)) to get the user.

SamAccountName : also AD-specific and searchable via a LDAP query

Path (DN) : should be consistent accross different LDAP providers. As I'm using the System.DirectoryServices namespace, I just have to do var userEntry = new DirectoryEntry(path, username, password); to get the user

Are there other possibilities to achieve this ? What is the most reliable way to link the users from the database with the ones from the AD directory ? What would be the impact of these solution in term of performances ?

答:
sAMAccountName (or uid in most Unixy LDAPs IIRC) is not unique - its only unique within each domain.

If you want unique, you use the ObjectGUID - if a user gets renamed or moved, this is the only bit that will remain constant. That means you need this if you have totrack a user getting a new username or moved to a different ou.

Title: LDAP users synchronization


问:
Dealing with co-workers in a stressful work environment
Our department has been hit by some layoffs over the past year and we're running a skeleton crew.  They got rid of most of our support staff.  The remaining team members would rather worry about what others are doing rather than work as a team and figure out how to improve their own situations.

The one co-worker (who does network administration) spends long hours in the office.  Part of it is due to the workload but another part of it is due to bad time management (his own fault and management).  He'll walk past my desk and make snide remarks like "working hard?" and "do something".  If I offer to help, he acts like he doesn't need it.  He's kind of the insecure type and likes to do everything himself and then hold it over everyone else.  I'm afraid he might end up burning out.

Another guy has been bitching about his workload.  He spends as much time worrying about what others are doing than getting stuff done himself.  He thinks he's too good for "grunt work" and wants to be a manager.  When his plate is full, he makes sure everyone else knows it when he has to do get stuff done.

They're not bad guys but the stress seems to be getting to everyone.  I'm the only one left who knows how to code so a lot of time is spent on programming projects but also have support duties.  I can't get a whole lot done due to the interruptions.  The guys in the office don't consider what I'm doing to be "work"....and seem to think that I should be helping them with support and not programming.  So basically they think I'm supposed to work on IT support and then go back to the office to work on programming projects while they surf the internet.  I don't whine and moan and complain like everyone else does so they assume that I don't have enough to do.  So now I get to listen to snide remarks about my workload.  Management likes my projects because they save the company money.

What is the best way to deal with this situation?

答: Don't care what other guys say. Talk to your boss and consider changing your job to a dedicated role with specific responsibility.

OwnerDisplayName: Lance


问:
Is this a pattern: stand-alone classes
Having recently discovered python, I attempted to write a simple logger. Data is read from a device, processes, displayed and stored on disc. Those different tasks belong to different modules, of course.

What appeared to be cool at the time, was to provide command-line interface to each module, as explained here: https://docs.python.org/2/tutorial/modules.html#executing-modules-as-scripts

The result is tat although the program as a whole uses import x and the uses the classes in the modules, the modules can be used form the command line as well. For example, invoking hw_comm.py would open the default device with default options and stream to stdout. Also plot.py expects data form stdin and draws a plot.

I can see a ton of advantages to this design, such as

easy to debug

easy to adapt for different use cases

easy to test

provides immediate value to the end user, long before the project is finished.

I have read only a few thousand lines of python yet, but haven't seen this approach (modules as both importable classes and stand-alone scripts) elsewhere. Why would be that? Is the extra work to support this format too much for an enterprise project? Or maybe, unlike my tiny project, business scale projects can not easily support this behavior, with hundreds of modules doing different things just to accomplish one complex goal together?

答:
The benefits of being able to execute a module from the command line are clear, as you outline.

However, what are the benefits of this functionality lying in the module itself?    That is not so clear.  You could easily accomplish the same thing with a simple wrapper script that called the module.  This would be no more work to code and just as convenient to use.

And, in my mind, it is better to logically separate the module from code that uses the module.

Title: Is this a pattern: stand-alone classes


问:
Are CRUD operations intended to be used with collections?
CRUD operations, by definition are...

interfaces that permit users to create, remove, modify or retrieve data

Implementations of CRUD interfaces can come in various shapes and sometimes they are even extended to SCRUD. What most CRUD interfaces have in common is that they refer to all major functions of e.g. a relational database. A basic implementation may look like this:

```<code>class CrudInterface {
    void add(obj entity);
    void get(obj entityKey);
    void update(obj entity);
    void delete(obj entityKey);
}
</code>```

But now consider the following additional method on the example interface above:

```<code>void add(Collection<obj> entities);
</code>```

Does such a thing belong on a CRUD interface? Wikipedia says

the software (which offers the CRUD interface) must allow the user to create or add new entries

So the example above seems valid by this definition. However, most relational database technologies don't support such a operation. And if they do, they mostly just loop through the collection and add the objects individually, which can have major drawbacks when a operation is coupled with a condition or a event hook.

So, is the use of collections on CRUD interfaces valid and/or legitimate?

答:
It is not true that most relational database technologies only support adding items one at a time.  Most major RDBMS have a bulk insert or load command that adds many rows at once.  This is much more efficient than calling insert over and over again.

Thus, any CRUD interface that needs to handle loading large volumes of data should have some mechanism for adding multiple rows at once.


答:
The only other idea I have is to set up a test GitHub account &
  repository, and work with that. But this solution won't work very well
  if, for instance, I had to pay for each access to the repository. What
  then?

Testing on a real account is called integration test and not unit test. You don't need a github repo to test a file download through HTTP. Every HTTP server can be enough. If you have some github specific problem, then you can create the repo and test on it. After that you can assume that the interface of the github won't change for a long time, so you can skip this integration test by running your tests, because it is slow and it does not (should not) depend on components you probably want to change. You'll probably run integration tests by version changes of the product integrated into your application. For example by a new database version, etc...


问:
Should I put my company in the footer of the site of a client?
I am a web developer and I am wondering if I should put my company's name in the footer of my client's websites.

I am doing this since I began and never had anyone asking if I would remove it. So I saw no problem, until...

on Webmasters.SE I saw someone saying that 'only amateuristic web developers put their company names in the footer of client's websites and that it's bad for SEO'.

Why is this 'amateuristic'?

Is the second statement true?

Should I offer some kind of 'branding removal' option?

答:
If you think that your actions may have an effect on the branding or reputation of your client (and this may well do) the professional approach is to ask the client their permission. If they don't know enough to be able to give you an informed decision then I would say that you are obliged to explain. If you don't know enough to make an informed decision then no.
This is an opinion question though.


答:
Using an if __name__ == "__main__" block to run a few quick tests is not unusual - you can even find it in the standard library.

However, if you intend to distribute your package as a command-line app, users generally expect there to be one entry point to the executable. (Imagine how hard rm would be to use if, instead of adding a -r flag to recurse directories, you had to type rmdir, a completely different command).

In Python-land we generally achieve this using a single main script which imports the package's internal modules and calls different functions as required.

Title: Is this a pattern: stand-alone classes

Body:
Having recently discovered python, I attempted to write a simple logger. Data is read from a device, processes, displayed and stored on disc. Those different tasks belong to different modules, of course.

What appeared to be cool at the time, was to provide command-line interface to each module, as explained here: https://docs.python.org/2/tutorial/modules.html#executing-modules-as-scripts

The result is tat although the program as a whole uses import x and the uses the classes in the modules, the modules can be used form the command line as well. For example, invoking hw_comm.py would open the default device with default options and stream to stdout. Also plot.py expects data form stdin and draws a plot.

I can see a ton of advantages to this design, such as

easy to debug

easy to adapt for different use cases

easy to test

provides immediate value to the end user, long before the project is finished.

I have read only a few thousand lines of python yet, but haven't seen this approach (modules as both importable classes and stand-alone scripts) elsewhere. Why would be that? Is the extra work to support this format too much for an enterprise project? Or maybe, unlike my tiny project, business scale projects can not easily support this behavior, with hundreds of modules doing different things just to accomplish one complex goal together?


答:
Putting your company name on a client website provides no benefit for them, but might have negative consequences as it detracts from their content. It only has a benefit for you in form of free advertising.

Using their website (they paid for it, so it's 100% theirs now) to advertise for you is a service they provide for you, and it's a service you should pay them for.

You could charge them extra for removing your advertisement. However, it might be more palatable instead to offer a discount for clients which allow you to do this. In any case, this should be part of the contract you make with the client.

Title: Should I put my company in the footer of the site of a client?

Body:
I am a web developer and I am wondering if I should put my company's name in the footer of my client's websites.

I am doing this since I began and never had anyone asking if I would remove it. So I saw no problem, until...

on Webmasters.SE I saw someone saying that 'only amateuristic web developers put their company names in the footer of client's websites and that it's bad for SEO'.

Why is this 'amateuristic'?

Is the second statement true?

Should I offer some kind of 'branding removal' option?


问:
Is this caution in Android API documentation an indication of suboptimal design?
The content below is from the Android developer site:

According to the phrase it is expecting the developer to store this info in his head. Shouldn't this be simple if they kept only setDataAndType and let user to set both, either or none, in which we don't have to remember this caveat since it is taken care by design.

As the code is from Google, I would like to check with the community if there is any good reason for they doing this that I am missing to see?

Signatures:

```<code>setType(String)

setData(Uri)

setDataAndType(Uri, String)
</code>```

答:
From the fragment you show there is no good reason - if both URI type and MIME type can be present simultaneously, it seems strange to null either when setting the other. There might be hidden reasons, but I can't think of any right now, therefore I'm leaning towards "This just isn't a very good API". </p>

<p>(Note also that the API talks about "type" and "data", but the documentation talks about "URI" and "MIME type". Such inconsistent language is another sign of an inexperienced API writer.)</p>

Body:
From the fragment you show there is no good reason - if both URI type and MIME type can be present simultaneously, it seems strange to null either when setting the other. There might be hidden reasons, but I can't think of any right now, therefore I'm leaning towards "This just isn't a very good API".

(Note also that the API talks about "type" and "data", but the documentation talks about "URI" and "MIME type". Such inconsistent language is another sign of an inexperienced API writer.)


答:
I suggest you remember clearly who pays your paycheck, and cater to their needs.  I'm not talking about "sucking up", but genuinely caring about how you can personally be most useful to them.  Regarding the co-workers, patience and grace will take it a long way.  If you take the high road, you will stand out in due time.

The company where I work has several competitors (financial software). Most of them focus on solving the problems of all the low level workers, and don't put a lot of focus on the high level management.  We, on the other hand, make the software work well for the low level people, and really, really, really focus on making it flow for the CEO/CFO level.

The end result is that out of dozens of clients, the highest level of management at these companies cannot say enough good about us, and therefore recommend us, and pay us, and recommend us, and pay us, etc...

I recall reading a story very similar to this in the book "How to Win Friends and Influence People", about a man who rose above his (similar peers) to become the most trusted employee of the company.  Wait, maybe it was "Seven Habits of Highly Effective People", but regardless, I'd read both if I were you.

Title: Dealing with co-workers in a stressful work environment

Body:
Our department has been hit by some layoffs over the past year and we're running a skeleton crew.  They got rid of most of our support staff.  The remaining team members would rather worry about what others are doing rather than work as a team and figure out how to improve their own situations.

The one co-worker (who does network administration) spends long hours in the office.  Part of it is due to the workload but another part of it is due to bad time management (his own fault and management).  He'll walk past my desk and make snide remarks like "working hard?" and "do something".  If I offer to help, he acts like he doesn't need it.  He's kind of the insecure type and likes to do everything himself and then hold it over everyone else.  I'm afraid he might end up burning out.

Another guy has been bitching about his workload.  He spends as much time worrying about what others are doing than getting stuff done himself.  He thinks he's too good for "grunt work" and wants to be a manager.  When his plate is full, he makes sure everyone else knows it when he has to do get stuff done.

They're not bad guys but the stress seems to be getting to everyone.  I'm the only one left who knows how to code so a lot of time is spent on programming projects but also have support duties.  I can't get a whole lot done due to the interruptions.  The guys in the office don't consider what I'm doing to be "work"....and seem to think that I should be helping them with support and not programming.  So basically they think I'm supposed to work on IT support and then go back to the office to work on programming projects while they surf the internet.  I don't whine and moan and complain like everyone else does so they assume that I don't have enough to do.  So now I get to listen to snide remarks about my workload.  Management likes my projects because they save the company money.

What is the best way to deal with this situation?


问:
How does Google manage their Google Images SSL certificate?
When an SSL certificate is installed on a website, but the page also calls content from another website without an SSL certificate, the SSL certificate icon will turn grey instead of green:

instead of:

Their site Google Images is also protected with an SSL certificate, but it stays green:

even though they call content (the images that are shown in the results) from websites without an SSL certificate.

How is this possible?

(Screenshots from my own question at Webmasters.SE)

答: If you inspect the images with devtools, you will see that they don't use external urls, but instead use base64 encoded data uri's as the image source:


答:
Looking at the source from a results page, the image thumbnails are not being fetched from other sites, but rather being served as base64 encoded data.

Expanding the images does load them from their real address, but that does cause the https icon to turn grey (at least in the most recent version of chrome).

Title: How does Google manage their Google Images SSL certificate?

Body:
When an SSL certificate is installed on a website, but the page also calls content from another website without an SSL certificate, the SSL certificate icon will turn grey instead of green:

instead of:

Their site Google Images is also protected with an SSL certificate, but it stays green:

even though they call content (the images that are shown in the results) from websites without an SSL certificate.

How is this possible?

(Screenshots from my own question at Webmasters.SE)


问:
Why are part-time jobs in programming an anomaly?
I've recently quit my full time developing job at mega-corp, and I decided that I'll look for a part time job. Since then I've talked to half a dozen potential employers, and every one of them had the same reaction when I said the magic words "part-time" - they all closed up and became suspicious. Now, I understand that it might just be me, so as control I asked every one of them what if I were willing to work full time, and they all said I would probably get an offer.

My question is two fold:

Why, as an employer, would you give up a competent, even great, developer, simply because he wants to work 3 days a week and not 5?

How do I sell the story of part time job better? I usually just list my reasons which are that I prefer that balance currently in my life and that I want to work on my own projects, but it leaves them even more suspicious - am I going to start something myself and quit? Am I just lazy?

答:
Most answers I see are rationalizations for the status quo, but really, I don't think there is a good reason for this state of things. Most programmers seem to believe not having a life is part of the deal and spoil it for the rest of us. Managers are good at screwing everybody around, unions are a joke, everybody says the economy sucks, but then there's always a need for programmers, and this should be exploited by the category.

Also I'm kind of flustered no-one pointed out that a wonderful reason for asking for a part-time job, would be "having a kid."

As soon as a critical mass of people starts asking for part-time programming jobs, there will be plenty of offerings. So go on, and convince more people to do the same. This is the closest we get to a union battle.


答:
Including your company name and website in the footer is a totally normal and common practice.

I think whether it's okay or not depends on the expectations you set in the beginning.

If you show your client a version of their website without your company name in the footer over and over again for 6 months and then when you go live you slap it on there, I can imagine the client being unpleasantly surprised that you did that, and I'd say justifiably so.

But if you somehow communicate to the client at the very beginning of the project that every website you do includes certain things, and one of those certain things is a link to your site, then that of course eliminates the possibility of surprise later.

I often offer my clients a "Chevy version", "Pontiac version" and "Cadillac version" of a project/feature/website I might build for them. I would recommend to you that you do this in general. Your Chevy version could include your advertisement and your Cadillac version could exclude it. (Offering multiple packages is a good idea anyway because it changes the question from should we proceed to how should we proceed, and it lets the client feel like they're in more control than if you offer a single take-it-or-leave-it package.)

So to answer your questions:

Is it amateuristic? If you sneak the link in hoping no one will notice, that's super amateuristic. If you include the link as part of a certain package and communicate the fact up front, then that's totally professional. Whether it's amateuristic depends not on whether you do it, but how you do it.

Is it bad for SEO? I'm not an SEO expert but I have a hard time thinking of how it might be bad for your SEO or the client's. I would bet money that it would be good for your SEO and have a negligible effect on your client's.

Should you offer a "branding removal" option? Yes, but I would position it by default as a line item in a package rather than a standalone option.


问:
Customer wants to modify the .properties files packaged in our WAR file
I have a customer who wants the ability to modify the .properties files packaged in the web applications WAR file so that they have the control to modify environments at settings.  They will be hosting this site on their own servers so I can't say I blame them but I am a little unsure what the best course is.

I would think that any adminstrator of a Java EE application server should know how to drill into the WAR package with a zip tool and find and modify the properties files themselves.  I am unsure if this is common knowledge or not.

I have typically always packaged my build artifacts with the property files appropriate for a given environment, but this is kind of an oddball case where WE build the WAR and hand it off to the customer.  I might try to keep the property files external from the WAR but then it gets messy because of classloader issues (JBoss classloader, Tomcat classloader, etc...)

I am thinking that as a convenience we maintain properties files for THEIR environments and change and build these on their requests. My manager likes this idea because it keeps us in control but the customer doesn't like this.

What would you do?

答: If the data in the .properties file needs to change often, I'd say that's data that's a good candidate for putting in a database so that binaries will not have to be modified.</p>


问:
Why does changing from one language to another make a programmer fresher?
Right now I have been working on language X for the last 2 years. I am very good at it, but language X is not popular so jobs are not readily available for it. Consequently, I am thinking to change from language X to language Y. But that means I'll be a fresher again. Is making the change worth it? Even if it means losing all the experience I have in the other language? </p>

答:
I'm going to assume you meant career. A carrier is either someone who carries things(e.g., a mule), or a phone company... A good career move would be to spruce up your English...anyway...

Typically learning more programming languages helps you think in principles instead of language.

It's better to be a software engineer than a "X programmer". Labor-wise, the statistics indicate "X Programmer" positions are decreasing and are less well paid than software engineers.

X programmers have a reputation for being bad outside of X.

For a given value of X


答:
I see multiple mistakes and misunderstandings in your question. The first major one is that you are missing distinction between property/field injection, constructor injection and service locator. There has been lots of discussion (eg. flamewars) about which is the right way to do things. In your question, you seem to assume only property injection and ignore constructor injection.

Second thing is that you assume that IoC containers somehow affect design of your code. They don't, or at least, it should not be necessary to change the design of your code if you use IoC. Your problems with classes with many constructors is case of IoC hiding real problems with your code (most possibly a class that has breaks SRP) and hidden dependencies are one of the reasons why people discourage use of property injection and service locator.

I don't understand where the problem with open-closed principle comes into this, so I won't comment on it. But you are missing one part of SOLID, that has major influence on this : Dependency Inversion principle. If you follow DIP, you will find out, that inverting a dependency introduces an abstraction, whose implementation needs to be resolved when an instance of class is created. With this approach, you will end up with lots of classes, that require multiple interfaces to be realized and provided at construction to function properly. If you were to then provide those dependencies by hand, you would have to do lots of additional work. IoC containers make it easier to do this work and even allow you to change it without having to recompile the program. You are probably confusion Open/Closed principle with Dependency Inversion principle in your question.

So, the answer to your question is no. IoC containers don't break OOP design principles. Quite contrary, they solve problems caused by following SOLID principles (especially Dependency-Inversion principle).

Title: IOC Containers break OOP Principles


问:
Strategy for storing mixed value and reference types without boxing
I'm looking for a way to store a large quantity of individual data values, with the following constraints.

Assume that the types are bool, int32, double, decimal, string and blob (byte array).

The type of each value will not be known at compile time (but the set of possible types is).

The type of each value will be known at run time, so it doesn't need to know its own type.

There are lots of them -- think millions at least.

Values are collected into rows/bags of (say) 1-100 values and accessed by index (from a dictionary as it happens).

Values are created and destroyed sometimes, read often and updated rarely.

Strategies I have so far are just these:

Array of object, but would require value types to be boxed and that's a load on the GC that I would prefer to avoid.

Serialise to a byte stream. String and blob would require an embedded length. Cost to read/update is high.

In C++ this could be an array of union of scalar and pointer types, but that strategy is unavailable (or at least highly unsafe) in .NET. This is a place where I really don't need a GC (object destruction is deterministic), so calling out to unmanaged code is a possibility.

The question is whether I've missed any viable strategies in the .NET world. Suggestions/comments welcome.

For my particular application it appears that creation/deletion happens in batches (rows/bags/sets) and individual values are not added or deleted. Think serialise/deserialise rather than random access. There are also set operations, so value-compare-equals is a common operation and boxing is bad for that.

答:
I would create a strongly typed array for each value type, and use each array as a pool of potential value holders. Another option, slightly slower, is to use a set of List where each List instance contains a different value types.

This is similar to the pooling strategy commonly used for memory allocation optimization. A List, or your own array, will have to expand sometimes. In this case, a new array must be allocated, and the old contents copied over to the new one.

Whether using List or an array, in both cases you avoid boxing entirely, and use memory as efficiently as possible in the CLR. The index for an element in your pool consists of: the type (to know which list or array to access) and the array or list index. The only other optimization I can think of is to consolidate types where possible: UInt32 and Int32 can share the same container, for example.

Beware boxing when writing the methods that store or retrieve values. You will need strongly typed arguments.

Variable sized objects, such as byte arrays, are most efficiently stored in a stream. However, to use the stored object as a byte array, you must allocate a new one, and copy part of the stream to the new array. It is more efficient to reuse previously allocated arrays.


问:
Is this instance of mixing FP and OOP a good design?
I had a strange-feeling pattern come up in some code I was writing. In a project with user accounts, there was a lot of code that needed to do common things such as creating accounts, deleting them, logging them in and out, extending their logged-in session, etc. etc. etc. Now when I was first writing this, I just threw all those responsibilities into one class (which was horrible I know). When it was time to clean this up, I ended up going with an approach that felt right but also strange.

I set up an AccountAccessor class which held private functions for getting the data transfer objects associated with an account, then I made several "action" classes that each would do one thing with access to an account, letting me write:

```<code>new AccountPasswordSetter(new AccountAccessor(username)).SetPassword(password);
</code>```

This felt wrong, because

The action classes were very, very tightly coupled with the AccountAccessor class - there was no hope of testing them

The AccountAccessor class would have to expose it's data access functions for the action classes to use them.

I have to expose construction of the action classes to the client code. This felt problematic because really, there's no sensible reason anything outside the project needs to concern itself with their instantiation.

Each of the action classes only needed one of the data transfer objects the AccountAccessor provided - for example an action class responsible for logging the user out doesn't need access to the account's password.

Writing this feels very wordy and "inside out".

What I ended up doing instead was I made the action classes all able to be constructed only inside the project, and instead of needing an AccountAccessor I had them set up to simply accept a function that would take a connection to the database and return the one particular DTO they needed. Then, when the account accessor was constructed, would would create a whole slew of these action objects and pass each of them one of it's private methods for getting the DTO. Something like:

```<code>public class AccountAccessor {
    public AccountPasswordSetter PasswordSetter { get; private set; }
    public AccountSessionExtender SessionExtender { get; private set; }
    public string Username { get; private set; }

    public AccountAccessor(string username) {
        Username = username;
        PasswordSetter = new PasswordSetter(getPasswordEntity);
        SessionExtender = new SessionExtender(getSessionEntity);
    }

    private PasswordEntity getPasswordEntity(Connection databaseConnection) { ... }
    private SessionEntity getSessionEntity(Connection databaseConnection) { ... }
}
</code>```

Now, client code can simply call something like:

```<code>new AccountAccessor(username).PasswordSetter.Set(password)`
</code>```

The responsibilities are split up, and the action classes don't have to know or care about what an AccountAccessor is. The client code doesn't have to know or care about how the various objects that provide functionality are set up. The AccountAccessor only selectively exposes access to the database entities. This felt much, much better. What I liked most about this design was it solved a lot of the problems I was having without imposing any architectural headaches on the client code. If client code wants to log out an account and delete it, they just get an accessor then log it out and delete it – no need to work out how to properly pass objects around. The obvious approach for the client code just works.

But it still seems a little off – passing private methods as arguments to other objects comes across as fundamentally strange to me. I wanted to know more about what sort of problems this has, and what I should keep in mind when designing things fitting this sort of scenario in the future.

答:
passing private methods as arguments to other objects comes across as fundamentally strange to me.

They're called first-class functions.  It's a perfectly valid technique.

That said, are you sure that this isn't all a bit over-engineered?  What's wrong with simply doing something like this?

```<code>user.SetPassword(newPassword);
</code>```

If you're bothered by tight-coupling, then provide a constructor overload that hands the necessary machinery for setting a password to the User object.  Dependency Injection is also a perfectly valid technique.  If you want even further decoupling, use an IoC container.

Body:
passing private methods as arguments to other objects comes across as fundamentally strange to me.

They're called first-class functions.  It's a perfectly valid technique.

That said, are you sure that this isn't all a bit over-engineered?  What's wrong with simply doing something like this?

user.SetPassword(newPassword);

If you're bothered by tight-coupling, then provide a constructor overload that hands the necessary machinery for setting a password to the User object.  Dependency Injection is also a perfectly valid technique.  If you want even further decoupling, use an IoC container.


问:
Can I create a type, typedef or using statement that results in a different type if instantiated a second time or more?
Suppose I have a class that evaluates some computationally intensive function:

```<code>class Value
{
private:
  int eval()
  {
    mCached = ExpensiveOperation();
    return mCached;
  }
  static int mCached;
};
</code>```

Now suppose that Value is actually some template expression, like Plus<1, Multiply<2, 3>> or something to that effect. It may itself be nested and might appear multiple times as part of a larger expression.

I don't know what the expression is, but I do know, based on its position in the expression, which instantiation of it (if there are multiple instantiations of exactly the same type) will be evaluated first.

I want to memoize the result for subsequently instantiated types, such that they are not evaluated more than once each time the expression is evaluated.

The easy way of achieving this is store the cached results in some sort of hash_map or to use singletons which check whether a static member is evaluated, but heap allocation and lookups are expensive, plus we already know the types at compile time and we know which instance is going to be evaluated first, so why not prepare the memoization at compile time as well?

What if we had something like a Cached type, which simply pulled the result from the first class of the same type:

```<code>template <typename Expression>
class Cached
{
  int eval()
  {
    return Expression::mCached; // cheap!
  }
};
</code>```

The problem is that I now have to remember to place Cached everywhere if an expression is repeated!

```<code>// Inefficient but nice expression:
Add<Multiply<2, 3>, Multiply<2, 3>>

// Efficient but ugly expression
Add<Multiply<2, 3>, Cached<2, 3>>;
</code>```

How can I create an expression that looks like the "inefficient but nice expression" yet still automatically generates a Cached type?

答:
You can look at the cached value as a Lazy Singleton object.<br>
This way it will only be calculated once per type.  </p>

```<code>int eval()
  {
    if (mCached == nullptr)
    {
       //Lock here
       if (mCached == nullptr) //double check after lock
       {
          int tempValue = ExpensiveOperation();
          mCached.reset(new int(tempValue));
       }
    }
    return *mCached.get();
  }
static uinque_ptr<int> mCached;
</code>```

Body:
You can look at the cached value as a Lazy Singleton object.

This way it will only be calculated once per type.

int eval()
  {
    if (mCached == nullptr)
    {
       //Lock here
       if (mCached == nullptr) //double check after lock
       {
          int tempValue = ExpensiveOperation();
          mCached.reset(new int(tempValue));
       }
    }
    return *mCached.get();
  }
static uinque_ptr<int> mCached;