问:
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.

答:
I'll go through your points numerically, but first, there's something you should be very careful of: don't conflate how a consumer uses a library with how the library is implemented. Good examples of this are Entity Framework (which you yourself cite as a good library) and ASP.NET's MVC. Both of these do an awful lot under the hood with, for example, reflection, which would absolutely not be considered good design if you spread it through day-to-day code.

These libraries are absolutely not "transparent" in how they work, or what they're doing behind-the-scenes. But that's not a detriment, because they support good programming principles in their consumers. So whenever you talk about a library like this, remember that as a consumer of a library, it's not your job to worry about its implementation or maintenance. You should only worry about how it helps or hinders the code you write which uses the library. Don't conflate these concepts!

So, to go through by point:

Immediately we reach what I can only assume is an example of the above. You say that IOC containers set up most dependencies as static. Well, perhaps some implementation detail of how they work includes static storage (though given that they tend to have an instance of an object like Ninject's IKernel as their core storage, I doubt even that). But this is not your concern!

Actually, an IoC container is just as explicit with scope as poor man's dependency injection. (I'm going to keep comparing IoC containers to poor man's DI because comparing them to no DI at all would be unfair and confusing. And, to be clear, I'm not using "poor man's DI" as a pejorative.)

In poor man's DI, you'd instantiate a dependency manually, then inject it into the class that needs it. At the point where you construct the dependency, you'd choose what to do with it- store it in a locally scoped variable, a class variable, a static variable, don't store it at all, whatever. You could pass the same instance into lots of classes, or you could create a new one for each class. Whatever. The point is, to see which is happening, you look to the point- probably near the application root- where the dependency is created.

Now what about an IoC container? Well, you do exactly the same! Again, going by Ninject terminology, you look at where the binding is set up, and find whether it says something like InTransientScope, InSingletonScope, or whatever. If anything this is potentially clearer, because you have code right there declaring its scope, rather than having to look through a method to track what happens to some object (an object may be scoped to a block, but is it used multiple times in that block or just once, for example). So maybe you're repelled by the idea of having to use a feature on the IoC container rather than a raw language feature to dictate scope, but as long as you trust your IoC library- which you should!- there's no real disadvantage to it.

I still don't really know what you're talking about here. Do IoC containers look at private properties as part of their internal implementation? I don't know why they would, but again, if they do, it's not your concern how a library you're using is implemented.

Or, maybe, they expose a capability like injecting into private setters? Honestly I've never encountered this, and I'm dubious about whether this really is a common feature. But even if it's there, it's a simple case of a tool that can be misused. Remember, even without an IoC container, it's but a few lines of Reflection code to access and modify a private property. It's something you should almost never do, but that doesn't mean .NET is bad for exposing the capability. If somebody so obviously and wildly misuses a tool, it's the person's fault, not the tool's.

The ultimate point here is similar to 2. The vast majority of the time, IoC containers DO use the constructor! Setter injection is offered for very specific circumstances where, for particular reasons, constructor injection can't be used. Anybody who uses setter injection all the time to cover up how many dependencies are being passed in is massively absuing the tool. That's NOT the tool's fault, it's theirs.

Now, if this was a really easy mistake to innocently make, and one that IoC containers encourage, then okay, maybe you'd have a point. It'd be like making every member of my class public then blaming other people when they modify things they shouldn't, right? But anybody who uses setter injection to cover up violations of SRP is either willfully ignoring or completely ignorant of basic design principles. It's unreasonable to lay the blame for this at the IoC container.

That's especially true because it's also something you can do just as easily with poor man's DI:

```<code>var myObject
   = new MyTerriblyLargeObject { DependencyA = new Thing(), DependencyB = new Widget(), Dependency C = new Repository(), ... };
</code>```

So really, this worry seems completely orthogonal to whether or not an IoC container is used.

Changing how your classes work together is not a violation of OCP. If it was, then all dependency inversion would be encouraging a violation of OCP. If this was the case, they wouldn't both be in the same SOLID acronym!

Furthermore, neither points a) nor b) come close to having anything to do with OCP. I don't even know how to answer these with respect to OCP.

The only thing I can guess is that you think OCP is something to do with behaviour not being altered at runtime, or about where in the code the lifecycle of dependencies is controlled from. It's not. OCP is about not having to modify existing code when requirements are added or change. It's all about writing code, not about how code you've already written is glued together (though, of course, loose coupling is an important part of achieving OCP).

And one final thing you say:

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.

Yes, you can. There is absolutely no reason for you to think that these tools- relied on by vast numbers of projects- are any more buggy or prone to unexpected behaviour than any other third-party library.

Addendum

I just noticed your intro paragraphs could use some addressing too. You sardonically say that IoC containers "aren’t employing some secret technique we’ve never heard of" to avoid messy, duplication-prone code to build a dependency graph. And you're quite right, what they're doing is actually addressing these things with the same basic techniques as we programmers always do.

Let me talk you through a hypothetical scenario. You, as a programmer, put together a large application, and at the entry point, where you're constructing your object graph, you notice you have quite messy code. There are quite a few classes that are used again and again, and every time you build one of those you have to build the whole chain of dependencies under them again. Plus you find you don't have any expressive way of declaring or controlling the lifecycle of dependencies, except with custom code for each one. Your code is unstructured and full of repetition. This is the messiness you talk about in your intro paragraph.

So first, you start to refactor a bit- where some repeated code is structured enough you pull it out into helper methods, and so on. But then you start to think- is this a problem that I could perhaps tackle in a general sense, one that isn't specific to this particular project but could help you in all your future projects?

So you sit down, and think about it, and decide that there should be a class that can resolve dependencies. And you sketch out what public methods it would need:

```<code>void Bind(Type interfaceType, Type concreteType, bool singleton);
T Resolve<T>();
</code>```

Bind says "where you see a constructor argument of type interfaceType, pass in an instance of concreteType". The additional singleton parameter says whether to use the same instance of concreteType each time, or always make a new one.

Resolve will simply try to construct T with any constructor it can find whose arguments are all of types which have previously been bound. It can also call itself recursively to resolve the dependencies all the way down. If it can't resolve an instance because not everything has been bound, it throws an exception.

You can try implementing this yourself, and you'll find you need a bit of reflection, and some caching for the bindings where singleton is true, but certainly nothing drastic or horrifying. And once you're done- voila, you have the core of your very own IoC container! Is it really that scary? The only real difference between this and Ninject or StructureMap or Castle Windsor or whatever one you prefer is that those have a lot more functionality to cover the (many!) use cases where this basic version wouldn't be sufficient. But at its heart, what you have there is the essence of an IoC container.

Title: IOC Containers break OOP Principles

Body:
I'll go through your points numerically, but first, there's something you should be very careful of: don't conflate how a consumer uses a library with how the library is implemented. Good examples of this are Entity Framework (which you yourself cite as a good library) and ASP.NET's MVC. Both of these do an awful lot under the hood with, for example, reflection, which would absolutely not be considered good design if you spread it through day-to-day code.

These libraries are absolutely not "transparent" in how they work, or what they're doing behind-the-scenes. But that's not a detriment, because they support good programming principles in their consumers. So whenever you talk about a library like this, remember that as a consumer of a library, it's not your job to worry about its implementation or maintenance. You should only worry about how it helps or hinders the code you write which uses the library. Don't conflate these concepts!

So, to go through by point:

Immediately we reach what I can only assume is an example of the above. You say that IOC containers set up most dependencies as static. Well, perhaps some implementation detail of how they work includes static storage (though given that they tend to have an instance of an object like Ninject's IKernel as their core storage, I doubt even that). But this is not your concern!

Actually, an IoC container is just as explicit with scope as poor man's dependency injection. (I'm going to keep comparing IoC containers to poor man's DI because comparing them to no DI at all would be unfair and confusing. And, to be clear, I'm not using "poor man's DI" as a pejorative.)

In poor man's DI, you'd instantiate a dependency manually, then inject it into the class that needs it. At the point where you construct the dependency, you'd choose what to do with it- store it in a locally scoped variable, a class variable, a static variable, don't store it at all, whatever. You could pass the same instance into lots of classes, or you could create a new one for each class. Whatever. The point is, to see which is happening, you look to the point- probably near the application root- where the dependency is created.

Now what about an IoC container? Well, you do exactly the same! Again, going by Ninject terminology, you look at where the binding is set up, and find whether it says something like InTransientScope, InSingletonScope, or whatever. If anything this is potentially clearer, because you have code right there declaring its scope, rather than having to look through a method to track what happens to some object (an object may be scoped to a block, but is it used multiple times in that block or just once, for example). So maybe you're repelled by the idea of having to use a feature on the IoC container rather than a raw language feature to dictate scope, but as long as you trust your IoC library- which you should!- there's no real disadvantage to it.

I still don't really know what you're talking about here. Do IoC containers look at private properties as part of their internal implementation? I don't know why they would, but again, if they do, it's not your concern how a library you're using is implemented.

Or, maybe, they expose a capability like injecting into private setters? Honestly I've never encountered this, and I'm dubious about whether this really is a common feature. But even if it's there, it's a simple case of a tool that can be misused. Remember, even without an IoC container, it's but a few lines of Reflection code to access and modify a private property. It's something you should almost never do, but that doesn't mean .NET is bad for exposing the capability. If somebody so obviously and wildly misuses a tool, it's the person's fault, not the tool's.

The ultimate point here is similar to 2. The vast majority of the time, IoC containers DO use the constructor! Setter injection is offered for very specific circumstances where, for particular reasons, constructor injection can't be used. Anybody who uses setter injection all the time to cover up how many dependencies are being passed in is massively absuing the tool. That's NOT the tool's fault, it's theirs.

Now, if this was a really easy mistake to innocently make, and one that IoC containers encourage, then okay, maybe you'd have a point. It'd be like making every member of my class public then blaming other people when they modify things they shouldn't, right? But anybody who uses setter injection to cover up violations of SRP is either willfully ignoring or completely ignorant of basic design principles. It's unreasonable to lay the blame for this at the IoC container.

That's especially true because it's also something you can do just as easily with poor man's DI:

var myObject
   = new MyTerriblyLargeObject { DependencyA = new Thing(), DependencyB = new Widget(), Dependency C = new Repository(), ... };

So really, this worry seems completely orthogonal to whether or not an IoC container is used.

Changing how your classes work together is not a violation of OCP. If it was, then all dependency inversion would be encouraging a violation of OCP. If this was the case, they wouldn't both be in the same SOLID acronym!

Furthermore, neither points a) nor b) come close to having anything to do with OCP. I don't even know how to answer these with respect to OCP.

The only thing I can guess is that you think OCP is something to do with behaviour not being altered at runtime, or about where in the code the lifecycle of dependencies is controlled from. It's not. OCP is about not having to modify existing code when requirements are added or change. It's all about writing code, not about how code you've already written is glued together (though, of course, loose coupling is an important part of achieving OCP).

And one final thing you say:

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.

Yes, you can. There is absolutely no reason for you to think that these tools- relied on by vast numbers of projects- are any more buggy or prone to unexpected behaviour than any other third-party library.

Addendum

I just noticed your intro paragraphs could use some addressing too. You sardonically say that IoC containers "aren’t employing some secret technique we’ve never heard of" to avoid messy, duplication-prone code to build a dependency graph. And you're quite right, what they're doing is actually addressing these things with the same basic techniques as we programmers always do.

Let me talk you through a hypothetical scenario. You, as a programmer, put together a large application, and at the entry point, where you're constructing your object graph, you notice you have quite messy code. There are quite a few classes that are used again and again, and every time you build one of those you have to build the whole chain of dependencies under them again. Plus you find you don't have any expressive way of declaring or controlling the lifecycle of dependencies, except with custom code for each one. Your code is unstructured and full of repetition. This is the messiness you talk about in your intro paragraph.

So first, you start to refactor a bit- where some repeated code is structured enough you pull it out into helper methods, and so on. But then you start to think- is this a problem that I could perhaps tackle in a general sense, one that isn't specific to this particular project but could help you in all your future projects?

So you sit down, and think about it, and decide that there should be a class that can resolve dependencies. And you sketch out what public methods it would need:

void Bind(Type interfaceType, Type concreteType, bool singleton);
T Resolve<T>();

Bind says "where you see a constructor argument of type interfaceType, pass in an instance of concreteType". The additional singleton parameter says whether to use the same instance of concreteType each time, or always make a new one.

Resolve will simply try to construct T with any constructor it can find whose arguments are all of types which have previously been bound. It can also call itself recursively to resolve the dependencies all the way down. If it can't resolve an instance because not everything has been bound, it throws an exception.

You can try implementing this yourself, and you'll find you need a bit of reflection, and some caching for the bindings where singleton is true, but certainly nothing drastic or horrifying. And once you're done- voila, you have the core of your very own IoC container! Is it really that scary? The only real difference between this and Ninject or StructureMap or Castle Windsor or whatever one you prefer is that those have a lot more functionality to cover the (many!) use cases where this basic version wouldn't be sufficient. But at its heart, what you have there is the essence of an IoC container.


问:
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>

答:
You make the false assumption that the experience you have on language x will be lost. Ever heard of the learn a new language a year motto? It is based around the idea that learning new languages will result in useful experiences you can bring back to your "primary" (let's call it) language.

Your second false assumption, which results from the first one, is that you are very good at language x. Are you? Ever heard of the humble programmer? Question yourself. I suggest that knowing how to program is not simply knowing a language's syntax or some of its libraries. If you knew language x really well, that would mean you would understand its core concepts and therefore be able to reuse that understanding with language y.

After carefully reasoning about this, you may realize you need to start at the beginning of understanding programming itself. In which case I recommend reading Structure and Interpretation of Computer Programs.

Ever heard of using the right tool for the job? Why do you assume that you have to choose language x or language y, instead of using them as tools under your belt.

C'mon, if you want to be a good programmer, be serious about it.

ContentLicense: CC BY-SA 2.5


问:
Python property best practices
Is there any situation where it makes sense to define a python property, where getting (not setting) it would raise an exception? I don't think this ever happens for fields in classes, hence the question.

Or is always better in these cases to use a method instead?

答:
I've created properties that raise exceptions in situations where I didn't want __init__ to raise exceptions and/or I wanted to delay processing.

```<code>class Identifier:

    def __init__(self, value):
        self._value = value

    @property
    def prefix(self):
        # ...
        # parse prefix from self._value
        # raise ValueError is provided value cannot be parsed
        # ...
        return prefix

    @property
    def suffix(self):
        # ...
        # parse suffix from self._value
        # raise ValueError is provided value cannot be parsed
        # ...
        return suffix
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python property best practices

Body:
I've created properties that raise exceptions in situations where I didn't want __init__ to raise exceptions and/or I wanted to delay processing.

class Identifier:

    def __init__(self, value):
        self._value = value

    @property
    def prefix(self):
        # ...
        # parse prefix from self._value
        # raise ValueError is provided value cannot be parsed
        # ...
        return prefix

    @property
    def suffix(self):
        # ...
        # parse suffix from self._value
        # raise ValueError is provided value cannot be parsed
        # ...
        return suffix


问:
when using dependency injection, should I always pass an interface
When using depending injection, you generally pass everything around as an interface (perhaps with the exception of primitives and strings). That allows you to easily chance the behavior, without changing the implementation.

Is there ever a case where I should not be passing some complex object through an interface though?

答:
Any case where there is only ever going to be a single implementation.

Any case where you are passing an instance of a derived type, rather than an instance that fulfills a particular interface.


问:
Storing a pointer to an argument passed by (non-const) reference
When designing an interface for passing objects which are meant to be stored for later use and which should not be 'null', I am always a bit uncertain if the argument should be passed by reference or as a pointer.

This is an example of what I mean:

```<code>class Foo
{
private:
    Bar* m_bar;

public:
    Foo() : m_bar(nullptr)
    {
    }

    void Register(Bar& bar)
    {
        m_bar = &bar;
        m_bar->Registered();
    }
    // -- OR --
    void Register(Bar* const bar)
    {
        if (bar == nullptr)
        {
            // Error!
        }

        m_bar = bar;
        m_bar->Registered();
    }

    // Some method makes use of the stored pointer later
    void DoSomething()
    {
        if (m_bar == nullptr)
        {
            // Error!
        }

        m_bar->DoOtherThing();
    }
};
</code>```

My thoughts on this are:

The passed in reference may go out of scope before DoSomething gets called, but that may happen with the pointed to object as well.

Using the pass-by-non-const-reference version gets rid of duplicating the check for null and tells the caller that it is not possible to register 'nothing'.

It would be better to pass a reference in the constructor of Foo as it is required by DoSomething, but sometimes it this is not an option.

It would be better to pass a reference to DoSomething directly, but again, this is not always possible.

So if I need that kind of separate setter/register method, would it be clearer to use a reference or a pointer?

PS I know there is are two very similar questions Storing a pass-by-reference parameter as a pointer - Bad practice? and Reference vs dereference pointers in arguments C++/C, but I think they both are concerned with slightly different problems. The former deals mostly with the (ab)use of const and the latter does not say anything about storing a pointer. There may be another question/answer out there, if so, please just mark this a duplicate then!

答:
Our coding guide -- written partially by me :-) -- says to always pass by pointer in this case where you want to hold on to a pointer.

With pointers, you can mostly correctly use const and non const versions, whatever is more appropriate (i.e., you may only want to hold on to a const Bar*, in which case you then can also only pass a const Bar*) Using a const Bar& as parameter type is bound to result in a runtime crash sooner rather than later because:

a const ref binds --  silently -- to temporaries : holding to temporaries is obviously a bad idea

among other things, any implicit type conversion creates a temporary, so this will bite you even when you pass an lvalue that is of an implicitly convertible type.

If you state to always pass pointers, noone will get funny ideas and try to hold on to a constreference. (see bullet above)

The client side may be slightly more aware of potential lifetime issues when the interface involves a pointer, even if the pointer isn't always visible syntactically. That is, when I see an interface Register(Bar*) personally speaking, I'd be less surprised if it holds on to the pointer than if I see a Register(Bar&)

That "it should not be null" does, IMHO, not matter too much for this decision. Passing a pointer means that the function can actually check it, but again this may or may not be appropriate. (Maybe it's just an (normally unchecked) precondition violation.)


问:
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?

答: Life is too short to spend it in a miserable environment. Even in this economy, there are great companies out there dying to get a hold of talented people.</p>

OwnerDisplayName: Lance


答: In a typical situation, you only pass a pointer if you want to accept nullptr or the typical usage of the type is not as a value. This is, for example, some (but not all!) interfaces. In most cases you always take a (potentially const) reference.

Title: Storing a pointer to an argument passed by (non-const) reference

Body:
When designing an interface for passing objects which are meant to be stored for later use and which should not be 'null', I am always a bit uncertain if the argument should be passed by reference or as a pointer.

This is an example of what I mean:

```<code>class Foo
{
private:
    Bar* m_bar;

public:
    Foo() : m_bar(nullptr)
    {
    }

    void Register(Bar& bar)
    {
        m_bar = &bar;
        m_bar->Registered();
    }
    // -- OR --
    void Register(Bar* const bar)
    {
        if (bar == nullptr)
        {
            // Error!
        }

        m_bar = bar;
        m_bar->Registered();
    }

    // Some method makes use of the stored pointer later
    void DoSomething()
    {
        if (m_bar == nullptr)
        {
            // Error!
        }

        m_bar->DoOtherThing();
    }
};
</code>```

My thoughts on this are:

The passed in reference may go out of scope before DoSomething gets called, but that may happen with the pointed to object as well.

Using the pass-by-non-const-reference version gets rid of duplicating the check for null and tells the caller that it is not possible to register 'nothing'.

It would be better to pass a reference in the constructor of Foo as it is required by DoSomething, but sometimes it this is not an option.

It would be better to pass a reference to DoSomething directly, but again, this is not always possible.

So if I need that kind of separate setter/register method, would it be clearer to use a reference or a pointer?

PS I know there is are two very similar questions Storing a pass-by-reference parameter as a pointer - Bad practice? and Reference vs dereference pointers in arguments C++/C, but I think they both are concerned with slightly different problems. The former deals mostly with the (ab)use of const and the latter does not say anything about storing a pointer. There may be another question/answer out there, if so, please just mark this a duplicate then!


问:
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?

答:
The IoC container isn't about the case where you have one dependency. It's about the case where you have 3 dependencies and they have several dependencies which have dependencies etc.

It also help you to centralize the resolution of a dependency, and life cycle management of dependencies.


问:
What Is λ-calculus essentially?
I have what I would call a philosophical question about λ-calculus.

When you explore λ-calculus you will be surprised to see all the things that you can do there.  You can define integers, arithmetic operations, booleans, if-then-else statements, loops, recursive functions, etc.  I believe it has been proven computationally complete.

But on the other side, if you consider what you can do with functions in λ-calculus, you realize that the only thing you can do is to feed it a function and it returns another function.  And that process never ends.

So how can you extract a result from a computation?

Suppose the result of an expression is function f.  You want to check whether f is what you expected.  You can test it, take a function you know, apply f to it and receive g.  But to check g is correct, you now need to verify what g does.  And you start all over.  So how can you tell anything about f?

It seems to me that you can replace all functions in λ-calculus by a single function, the identity function I = λx.x, and everything still works as described in λ-calculus.  The Church numeral 3 when given f and x returns f(f(f(x))).  But since f and x can only be I, it returns I.  I applied to I and I also returns I.  So I satisfies the definition of 3.  The “booleans” (λxy.x) and (λxy.y) need 2 arguments, which will be I and I so both booleans will return I.  Each is equivalent to the identity, even though they behave exactly according to their definitions.

So how do you make the difference?  How do you show that λ-calculus deals with more than just a single function?

Is there a concept of identity?  Can you identify a function immediately without evaluating it?  I believe it was proven that there is no way to test 2 functions for equality.

Or is λ-calculus not about functions, but about the formal description of what they do?  That would mean that λ expressions not only define what the functions do but are also the data that the functions manipulates.  So when you write A B, you don't apply A to B, but you apply the function described by the string A to formal definition of a function contained in B returning another formal definition.

What is actually going on in λ-calculus?  What is the mathematical objects it deals with?

Followup:

OK, from the answer below it seems that λ-calculus is not so much about functions in the mathematical sense, but about the subset of functions that can be expressed as λ expressions.  Or even more about the manipulation of λ expresssions.

答:
It is indeed impossible to determine semantic equivalence of lambda calculus terms. This is one application of Rice's theorem. However, it's easy to compare terms syntactically, that is, test if they have the exact same structure (equivalently, if their "string representation" is the same). That's really all you need to get results.

For example, to compute functions n = f(i) from the naturals to the naturals, you supply the church encoding of i as parameter to your lambda calculus function, apply reduction rules until you come to a stop, and inspect the resulting term. If it matches the structure of church numerals, extract the number n which it encodes. That's your result.
If the resulting term doesn't look like a church numeral, or reduction doesn't halt, the function is undefined at i.

Terms effectively pull double duty as "code" and "data". That's nothing special: A Turing machine's tape (a string over some alphabet) can be --- and frequently is --- interpreted as an encoding of a Turing machine or of some aspect thereof. Likewise, the bits in a von Neumann machine's main memory can be either an encoding of a program or an encoding of something else. Or even both at once. It's only the "default perspective" that differs.

Title: What Is λ-calculus essentially?


问:
Database design, how to handle freelancers
The context

I'm modeling a database for a small ERP system. However I've recently hit a difficult spot that I'm having a hard time wrapping my head around. The logic of it involves a few special cases, I'm hoping someone with DB design background might help (this is my first large DB model project).

Contact is a table holding information on various people.

A contact has a organization_id field which is a foreign key to Organization, id

We handle a case where if a contact has no organization
(organization_id = null)      it is a "freelancer"...

Organization is a table holding information on organizations. An organization is linked to many contacts.

Invoice is a table holding invoice information.

The problem: Suppose a contact A has an invoice X and that contact changes organization (after the transaction). Who owns the invoice? (in other words, how do I link invoices to certain entities).

Possible solutions I have explored

Link Invoice to Organization with a foreign key (organization_id) in table Invoice.

However, this does not handle the case where a Contact has no organization (is a freelancer). If such a contact has a sale/invoice... the system can't handle it.

Link Invoice to Contact with a foreign key (contact_id) in table Invoice.

However, if a contact changes organization, that organization would inherit the contact's past invoices (which is WRONG).

On the front-end, auto-generate an Organization based on a Contact's information when that contact is a "freelancer".

To be honest, I don't like this solution. It feels like a cheap hack.

Force contacts to have an organization...

I'm hoping there is another solution than this one...

EDIT #1

After analyzing some the answers, I've realized an important piece of information is missing. The small ERP system will be used by many clients, some of which follow the B2B (Business-to-Business) model and others which follow the B2C (Business-to-Customer) model.
In the B2C model, Contacts DON'T have an Organization. But they should still be able to have projects/sales associated to them.

答:
At first blush, I would say two things would make things simpler:

Create an Organization that represents "Freelancers" and assign all freelance Contacts to that Organization.

and

An Invoice should contain both an OrganizationId and a ContactId, which represents the Organization and Contact relationship at the time of the invoice.

If the Contact changes Organizations later, it won't matter, because the Invoice still has the original OrganizationId.


答:
Preparing my flame-retardant suit, as I feel some bias must be present in any answer to this question.

First, I would like to note that I work within the embedded world, so RAII and stack allocation are generally the way to go. In almost any circumstance, I see passing something in by reference as a good idea because of the obvious reason: it can't be NULL. But notably, this is because I primarily do stack allocation - so I'm not typically taking something from the heap and stuffing it into a reference when passing it in. This style of programming eliminates common sources of issues for concerns 1, 3, and 4 that you listed.

If I do pass in a pointer, it's for one of two reasons: 1) NULL really is an option (somewhat rare) or 2) I want to signal that my object is taking ownership of the one being passed in. I realize this comes down somewhat to style and domain, but it's a rule of thumb that's helped me make fewer errors and communicate with the programmers on my team about what my code is doing.


问:
What are the tecnhical reasons for email HTML, CSS, Javascript limitations and their persistance
If you've ever made a custom email you'll know that there are significant limitations in  you need to be aware of.

The most obvious limitations being:

No support for Javascript in emails

No support for internal CSS (CSS placed in the HTML file header). Its rather understandable that external CSS is still not supported.

Email browsers encourage the use of HTML and CSS coding that is now considered deprecated and bad practice. For example; using tables to organise content rather than divs with CSS (float, etc.). Also as an example; the strict/over use of inline CSS

No support for forms

Whilst its understandable that early browsers would not support Javascript or CSS. Why do these limitations persist in modern browsers? What are the technical purposes (if any) that modern email browsers still have these limitations and inconsistencies with web browsers?

To point out the most obvious reason Javascript was/is not supported: Security. But as Internet Explorer has shown; when dealing with the security issues around ActiveX (I think thats what it's called?) they didn't ban or remove Javascript completely - they took other actions to resolve the security problems. So why hasn't the same approach been taken with Email Browsers?

答:
Lack of need and use of protocols that don't support or reflect that method of communication.  The separated actions of sending and reading.

Also the reading device could be any one of hundreds of different devices and the only medium really guaranteed to work correctly on all of them is text.  Plus it will work in very low bandwidth conditions.


答:
Unlike webpages, e-mails are:

Primary intended for basic communication. The most basic form being plain text, some features from HTML can empower the users of e-mails, but they probably won't use (or won't use properly) every feature available in HTML and CSS.

In other words, being able to make text bold or italic or to make it blue and bigger than the rest of the content is great. Being able to use CSS 3 transitions won't be useful.

What about ads? Well, you don't need too much features neither. As I said, this is not a website. You don't need interactivity. You don't need advanced formatting. You won't send an e-mail which looks like this page, because the purposes are simply different: the home page of the website is here to showcase a product or a company; the purpose of an e-mail, on the other hand, is to communicate a piece of information. "Hey, we just released our new Cloud platform, come visit our site to discover it!" is a piece of information, and can be expressed as simply as I did: through plain text.

What can't be expressed through plain text can be through an image. Most e-mail clients allow to display images, so you have an option you need. You want videos, sound, interactivity? Not a good idea, because e-mails are not a good place for that.

Displayed not only a bunch of browsers, but also multiple e-mail clients, each one having its own restrictions and its own way to render e-mail contents. Take Microsoft: they have already a hard time implementing the standards in Internet Explorer. Would they rather assign to their best developers to work on the next version of IE which would support better the standards, or rather move those developers to a team which works on Outlook Express?

Moreover, you know the problem all front-end developers had a few years ago, right? Do we need to support Internet Explorer 6, since a large part of our users are still using it? Today, the problem was largely reduced. There are much less users of Internet Explorer 6, and I also believe that web developers are so excited by HTML 5 that they simply stopped to care about legacy browsers. But the same problem exists for e-mail browsers: I'm completely happy using Microsoft Office 2007 and see no reason to buy a new version; this also means that Microsoft Outlook I use won't be upgraded in the next five years.

Prone to spam. The fact that the system itself is so much misused by spammers as well as companies willing to track who actually read their marketing stuff makes e-mails the first target. This also means that e-mail clients should take care of protecting their customers. You have images such as http://tracking.example.com/?id=babc7b16-c9fe-448d-aa84-2ccd37df6db7? Well, I think I prefer viewing your e-mail without actually loading the images. You want to track how long I spent reading your e-mail? Luckily, my e-mail client doesn't run JavaScript.

Often displayed inside a page. Web-based e-mail clients may display the content of the e-mail inside a page, surrounded by the e-mail client commands and other content. In this context, JavaScript is out of question (imagine a security threat if an e-mail can do redirects: so I click to read some spam, and see that my GMail suddenly disconnects and presents itself with a form asking me to provide my password to log on again). Full CSS support is problematic too: an attacker can make a part of the e-mail look like GMail interface.

Title: What are the tecnhical reasons for email HTML, CSS, Javascript limitations and their persistance

Body:
If you've ever made a custom email you'll know that there are significant limitations in  you need to be aware of.

The most obvious limitations being:

No support for Javascript in emails

No support for internal CSS (CSS placed in the HTML file header). Its rather understandable that external CSS is still not supported.

Email browsers encourage the use of HTML and CSS coding that is now considered deprecated and bad practice. For example; using tables to organise content rather than divs with CSS (float, etc.). Also as an example; the strict/over use of inline CSS

No support for forms

Whilst its understandable that early browsers would not support Javascript or CSS. Why do these limitations persist in modern browsers? What are the technical purposes (if any) that modern email browsers still have these limitations and inconsistencies with web browsers?

To point out the most obvious reason Javascript was/is not supported: Security. But as Internet Explorer has shown; when dealing with the security issues around ActiveX (I think thats what it's called?) they didn't ban or remove Javascript completely - they took other actions to resolve the security problems. So why hasn't the same approach been taken with Email Browsers?


问:
How do I write my BLL to make it re-usable?
Most of it was written 4-5 years ago.  Our teams long term objectives are to use Entity Framework. Though we aren't gonna do it right away as our deadlines aren't allowing us to do so.
Now we have our own framework. I want to be able to segregate the Business logic layer in such a way that it need not be re-written when we move to EF. Please guide us with best practices, advise us in this direction.

Our business logic layer is very fragmented today (UI Code Behind + Stored Procedures/functions SqlServer/ C# persistent classes) : What if I want to segregate it totally and draw a very prominent line between  Storage | DAL | Business Logic | UI

I want to know if it's ok to move the BLL totally in SQl stored Procedures or does it have to be totally C# classes?

Also to avoid re-writing the BLL as we are going to move to EF eventually. What steps should I take so that I can readily use the entire BLL with EF without changing the code.

A lot of the stored procedures (which have the BL) lie in the storage DB itself. Does segregating the BLL mean the SP's and functions should be in a different database altogether? or for all practical purposes it's ok for them to be in the same DB?

I've seen multiple questions on SO which were really helpful, but I just couldn't get a clear picture of the solution or advise I seek, so I put everything in one post.

Please correct me if I'm wrong. I'm a novice when it comes to system design. I wanna be able to foresee  what I'm getting into before actually implementing it.

答:
It's up to you

Use trace bullets, a POC

n/a

If the long term goal is to use EF, then move to EF now. If the mangers don't get the benefits then try convincing then really hard! Buy them books and so on...

If you do not know how EF fits your solution? Make a POC on a small part of the system (one use case), but make sure it's implemented through all the layers of your application. Then you will know how EF fits you and you might have a better understanding on the scope to use it all together. You should be able to do this without affecting the deadline.

Good luck!

OwnerDisplayName: Pavitar


问:
How do multiple levels of inheritance affect virtual function call overhead in C++?
I am considering using a class hierarchy with more than a single level of inheritance, where virtual member functions form a "chain", for example:

```<code>struct Base
{ virtual void foo(); };

struct D1 : Base
{ virtual void foo(); };

struct D2 : D1
{ void foo(); };
</code>```

However I would like to know before using similar code in practice if this would cause additional dynamic dispatch overhead when calling trough a base class pointer. Consider the following example:

```<code>D2 instance;
D1* d1ptr = &instance;
Base* baseptr = &instance;

//normal function call to "D2::foo()", no dynamic dispatch.
instance.foo();
//virtual function call to "D2::foo()", one dynamic dispatch.
d1ptr.foo();
//virtual function call to "D2::foo()", does this incur additional
//..overhead compared to "d1ptr.foo()"?
baseptr.foo();
</code>```

答:
In your example, the depth of the inheritance tree does not affect performance. The reason is simple, every instance has its pointer to some vtable (containing function pointers), and a virtual function call goes just thru that vtable.

In other words, your code works like the following C code:

```<code>struct vtable {
   void (*fooptr) (struct D1*);
};

struct D1 {
   const struct vtable*vptr;
};

struct D2 {
   const struct vtable*vptr;
};
</code>```

And e.g. baseptr->foo() is "transformed" at compilation time to baseptr->vptr.fooptr(baseptr) (and of course d1ptr->foo() is "transformed" to d1ptr->vptr.fooptr(d1ptr) etc...)

So the execution cost is the same: get the vtable, and call indirectly the function pointer inside. The cost remains the same even if you had a struct D4 subclass of struct D3 subclass of struct D2 subclass of struct D1. You could have a struct D99 with 99 inheritances and the execution cost would remain the same.

On some processors, any indirect call may be slower than a direct call, e.g. because of branch predictor cost.

The data of the vtable themselves is built at compilation time (as constant static data).

Things become a bit more complex with virtual inheritance and/or multiple inheritance

BTW, some C object frameworks (e.g. GObject from Gtk, or several data structures inside the Linux kernel) also provide their vtable (or class data). Pointing to a data structure containing function pointers is quite common (even in C). Read also about closures and you'll see a relation with "vtables" (both closures and objects are mixing code with data).

Some C++ compilers (e.g. GCC) may provide devirtualization as an optimization technique.

Body:
In your example, the depth of the inheritance tree does not affect performance. The reason is simple, every instance has its pointer to some vtable (containing function pointers), and a virtual function call goes just thru that vtable.

In other words, your code works like the following C code:

struct vtable {
   void (*fooptr) (struct D1*);
};

struct D1 {
   const struct vtable*vptr;
};

struct D2 {
   const struct vtable*vptr;
};

And e.g. baseptr->foo() is "transformed" at compilation time to baseptr->vptr.fooptr(baseptr) (and of course d1ptr->foo() is "transformed" to d1ptr->vptr.fooptr(d1ptr) etc...)

So the execution cost is the same: get the vtable, and call indirectly the function pointer inside. The cost remains the same even if you had a struct D4 subclass of struct D3 subclass of struct D2 subclass of struct D1. You could have a struct D99 with 99 inheritances and the execution cost would remain the same.

On some processors, any indirect call may be slower than a direct call, e.g. because of branch predictor cost.

The data of the vtable themselves is built at compilation time (as constant static data).

Things become a bit more complex with virtual inheritance and/or multiple inheritance

BTW, some C object frameworks (e.g. GObject from Gtk, or several data structures inside the Linux kernel) also provide their vtable (or class data). Pointing to a data structure containing function pointers is quite common (even in C). Read also about closures and you'll see a relation with "vtables" (both closures and objects are mixing code with data).

Some C++ compilers (e.g. GCC) may provide devirtualization as an optimization technique.


答:
This depends on the programming language, the availability of a mocking framework and your need for mocking those complex objects. For C# and Java, there are frameworks available which allow you to mock out classes without creating interfaces first. (In the environment where I work, we don't use any of those frameworks, so whenever we have to mock a class for a unit test, we are going to create an interface.) In C++, you can avoid the need for interface-based mocking by injecting your "complex class" as a template parameter into every other component which is going to use it (the drawback is you have to templatize those classes, which means a certain amount of overhead).

In weakly typed languages there's often not even a language construct "interface" because you can replace an object of a class just by an object of a different type as long as the replacement fulfills the implicit contract (i.e. provides methods with correct names and signature).

Furthermore, I agree that DI does not work well with infrastructure classes like "strings". See this former PSE question & my answer to it.

I would like to add that your question sounds like "shall I always provide an interface 'just in case'". IMHO it is better to follow the YAGNI principle, start without an interface, and as soon as you need one, maybe for mocking purposes, refactor your code and introduce the interface afterwards.

Title: when using dependency injection, should I always pass an interface

Body:
When using depending injection, you generally pass everything around as an interface (perhaps with the exception of primitives and strings). That allows you to easily chance the behavior, without changing the implementation.

Is there ever a case where I should not be passing some complex object through an interface though?


答:
There is nothing wrong with providing an individual organization for each freelancer, even when there is only one "employee" in this organization. Actually, this reflects the legal situation much better, since a freelancer can have the role of a company (own address/mail account / phone number) and the fully separated role of a private person or employeed person as well. And it will help you to model other things more uniform as well.

The CRM we are using in our company works exactly like this

you first create a new organization/company in the system, with address, central mail address, web site, telephone etc.

contact persons are always added to the "active" organization. You can enter an address differing from the companies address, if you like (but you don't need to). And you cannot add contacts without an organization.

contact persons never change their company; they may become inactive, and you can add a new contact person beeing a copy of an existing one. This helps to manage the historic information who once was my contact person in the past (even when in a new company today) and avoids problems like yours.

The last point is surely not the best solution for every system. You have to decide of this kind of model suits your needs in your specific case.

To your edit: for the case where you really want organizations and individual persons to be accountable, it may be better to follow Fowler's ideas from his book "Analysis patterns" on how to model accountability (see page 4). Create an additional table "party" for persons and organizations. Each entity in "party" has either an corresponding entry in "organization" or one in "person". When doing object-relational modeling, "party" would be just the base class of person and organization. Invoice gets just a "PartyID" as the referencing foreign key.

This will allow to deal with individual persons as well as with organizations in a uniform manner.

Title: Database design, how to handle freelancers

Body:
The context

I'm modeling a database for a small ERP system. However I've recently hit a difficult spot that I'm having a hard time wrapping my head around. The logic of it involves a few special cases, I'm hoping someone with DB design background might help (this is my first large DB model project).

Contact is a table holding information on various people.

A contact has a organization_id field which is a foreign key to Organization, id

We handle a case where if a contact has no organization
(organization_id = null)      it is a "freelancer"...

Organization is a table holding information on organizations. An organization is linked to many contacts.

Invoice is a table holding invoice information.

The problem: Suppose a contact A has an invoice X and that contact changes organization (after the transaction). Who owns the invoice? (in other words, how do I link invoices to certain entities).

Possible solutions I have explored

Link Invoice to Organization with a foreign key (organization_id) in table Invoice.

However, this does not handle the case where a Contact has no organization (is a freelancer). If such a contact has a sale/invoice... the system can't handle it.

Link Invoice to Contact with a foreign key (contact_id) in table Invoice.

However, if a contact changes organization, that organization would inherit the contact's past invoices (which is WRONG).

On the front-end, auto-generate an Organization based on a Contact's information when that contact is a "freelancer".

To be honest, I don't like this solution. It feels like a cheap hack.

Force contacts to have an organization...

I'm hoping there is another solution than this one...

EDIT #1

After analyzing some the answers, I've realized an important piece of information is missing. The small ERP system will be used by many clients, some of which follow the B2B (Business-to-Business) model and others which follow the B2C (Business-to-Customer) model.
In the B2C model, Contacts DON'T have an Organization. But they should still be able to have projects/sales associated to them.


问:
PHP as a target language
Are there stable well tested SDKs (as opposed to simple language converters) that allow you to develop your application in some decent language (I believe it is widely accepted that PHP is not a well designed platform) and then give PHP code as an output, so you can host your application on a server that only accepts PHP as a server-side scripting language? </p>

答:
If you hate PHP so much, you should avoid developing web applications to be hosted on PHP servers. Even if there would be any SDKs (and I don't know any), you would still need to to spend a great amount of time reading PHP—for example when debugging the application.

The same applies for language translators or supersets. A few years ago, I was working on a superset like that: a sort of PHP, but strongly typed when needed and with a set of features I liked in other languages, such as C#'s Code contracts (which cannot be implemented as-is in PHP). The only problem was that I still had to use PHP while debugging or profiling the apps.

In other words, TypeScript is great, but you still have to know JavaScript. LESS is great, but when things go wrong, you're back to the inspection of plain CSS code.

I may suggest you the following:

If you're doing a project for a customer who told you that he has only PHP-based hosting, discuss it with your customer. Tell that that you don't consider PHP as a great programming language. Tell that he has a choice between considering another hosting platform, or search for another person to develop the application for him.

If you're working on a product for sale which would be hosted on multiple platforms, consider either not supporting PHP (which could be a problem, given the number of inexpensive hosting providers which have PHP only) or hiring a team of skillful PHP developers to add the support.

Another important thing is that you should consider using a PHP framework (if you're not yet using one). Many popular PHP frameworks reduce the discomfort of PHP inconsistencies and abstract some of the weird parts of the language.

While I haven't tried it myself, Laravel seems promising.

Title: PHP as a target language


答:
You won't lose "all the experience". Don't be afraid to dive into more languages. Sure, libraries, idioms, etc. will be different -- don't get me wrong, you will have to learn these and that will take more longer than a few minutes -- but unless you're out to learn a "vastly different from everything else" language (say, Haskell), many of the concepts that take beginners days to grok and weeks or months to get comfortable with are the same in the new language and the language(s) you already know. Flow control, algorithms, data strucutres, etc. are 95% language-agnostic. You won't be writing great Y programs after two days, but it won't take anywhere as long as becoming a decent programmer in the first place.
On the other hand, unless X and Y are extremely similar (say, Java and C# (ignoring all the neat non-OO stuff added to C# during the last versions)), you get to learn new language-agnostic concepts that can be used in other languages as well. For example, learning Haskell made me get used to recursion and recursive data structures (read: trees) - and now I'm processing XML (trees!) with Python.

Even if there were tons of great jobs for language X, you should learn more languages. As they say, when all you have is a hammer, everything looks like a nail. I.e. know many tools so you know which one is right for the job.

Title: Why does changing from one language to another make a programmer fresher?

Body: 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>


问:
Which design pattern for a single class accessing an object representing a data structure?
Which design pattern should I use when I have a class representing a data structure (aka C-style struct) and I wish to have only a single class to be able to access it.

I was thinking of simply declaring the class that represents a data structure as an inner class but wanted to know if there is a better way to design this.

eg:

```<code>class XXManager{
getXX();
setXXAtrtribute();
}

class XX{
  String name;
  String email;
  String job;
}
</code>```

Here I want to design a class XXManager which will handle the creation and managment of 'XX' objects and no one should be able to access XX other than through the XXManager.

答: To me it seems like you might want to take a look at the Proxy design pattern. With that said not everything you create has be based on design patterns. It might lead to some overengineering.</p>


问:
Best approach for multilingual Java Enum
I'm running into issues with an approach I am taking and am now wondering if I just started down the wrong path and should rethink my approach.  Here is what I attempting.

I would like to use an Enum to represent different possible Account Statuses (there are other finite data sets that I will be setting up using a duplicate approach):

A, Active

I, Inactive

P, Pending

Those Account Statuses must be presented to the user in their language if preference.

Example: Account Status is A, show it as Active for English speakers and Activo for Spanish.

There are also situations where I would like to show a dropdown list of all possible Account Statuses in the appropriate locale preference.

Current Approach

Use an AccountStatusEnum class with values of (A,I,P).

In a private static member variable store an EnumMap of localized Account Statuses inside a EnumMap of possible Locales.

Example:

```<code>private static EnumMap<LocaleEnum, EnumMap<AccountStatusEnum, String>> localeAccountStatuses = new EnumMap<LocaleEnum, EnumMap<AccountStatusEnum, String>>(LocaleEnum.class);
</code>```

This would get loaded within a static initialization block.

I could then use the following methods to get all the values for a dropdown:

```<code>public static EnumMap<AccountStatusEnum, String> getAccountStatuses(LocaleEnum locale) {
        return localeAccountStatuses.get(locale);
    }
</code>```

Or I could use this method to get a single description for a given Enum:

```<code>public String getDescription(LocaleEnum locale){
            return getAccountStatuses(locale).get(this);
        }
</code>```

Example Usage: AccountStatusEnum.A.getDescription(LocaleEnum.es_MX);

I'm curious about your thoughts on this approach and possible better approaches for accomplishing the same thing.

EDIT
The logic to get the values to populate the Enums would be centralized within a single helper class.  Therefore if the source of the descriptions changes to come from a new source, the code change is minimized.

Thanks

答:
I would approach this problem as I would approach any localization issue:  ResourceBundle.  I use a class called I18n that has a static method called getMessage that takes a key and optionally a list of arguments.  The key gets looked up in a ResourceBundle configured to use the default Locale or whatever you prefer (specifics here aren't important, so long as the caller to I18n doesn't have to know about what the Locale is).

The I18n class is as follows:

```<code>public final class I18n {
    private I18n() {
    }

    private static ResourceBundle bundle;

    public static String getMessage(String key) {
        if(bundle == null) {
            bundle = ResourceBundle.getBundle("path.to.i18n.messages");
        }
        return bundle.getString(key);
    }

    public static String getMessage(String key, Object ... arguments) {
        return MessageFormat.format(getMessage(key), arguments);
    }
}
</code>```

In your project, you would have in package path.to.i18n, files containing messages.properties (default), messages_en.properties (Locale en), messages_it.properties (Locale it), etc.

When you need to translate an enum value, you shouldn't have to treat it any differently than any other key, except the key is the enum term.

In other words, you have:

```<code>public enum AccountStatusEnum {
  Active,
  Inactive,
  Pending
}
</code>```

When you call I18n.getMessage, you pass with AccountStatusEnum.Active.toString() and the translation will be found in a property file with key "Active".  If you're like me, and you prefer to use lower-case keys, then you should perform toLowerCase() on the string.  Better still, you create a new I18n.getMessage that takes an Enum rather than a key, and that method calls the String version of I18n.getMessage with the enum value converted to string and in lowercase.

So you'd then add this to the I18n class:

```<code>    public static String getMessage(Enum<?> enumVal) {
        return getMessage(enumVal.toString().toLowerCase());
    }
</code>```

I prefer to use this method because it incorporates the same translation logic in the same part of the program without impacting your design.  You may even want to differentiate enum keys from your other keys, in which case you can begin each enum key with "enum.", so you would prepend "enum." when calling getMessage.  Just remember to name your keys in your properties files accordingly.

I hope that helps!

Body:
I would approach this problem as I would approach any localization issue:  ResourceBundle.  I use a class called I18n that has a static method called getMessage that takes a key and optionally a list of arguments.  The key gets looked up in a ResourceBundle configured to use the default Locale or whatever you prefer (specifics here aren't important, so long as the caller to I18n doesn't have to know about what the Locale is).

The I18n class is as follows:

public final class I18n {
    private I18n() {
    }

    private static ResourceBundle bundle;

    public static String getMessage(String key) {
        if(bundle == null) {
            bundle = ResourceBundle.getBundle("path.to.i18n.messages");
        }
        return bundle.getString(key);
    }

    public static String getMessage(String key, Object ... arguments) {
        return MessageFormat.format(getMessage(key), arguments);
    }
}

In your project, you would have in package path.to.i18n, files containing messages.properties (default), messages_en.properties (Locale en), messages_it.properties (Locale it), etc.

When you need to translate an enum value, you shouldn't have to treat it any differently than any other key, except the key is the enum term.

In other words, you have:

public enum AccountStatusEnum {
  Active,
  Inactive,
  Pending
}

When you call I18n.getMessage, you pass with AccountStatusEnum.Active.toString() and the translation will be found in a property file with key "Active".  If you're like me, and you prefer to use lower-case keys, then you should perform toLowerCase() on the string.  Better still, you create a new I18n.getMessage that takes an Enum rather than a key, and that method calls the String version of I18n.getMessage with the enum value converted to string and in lowercase.

So you'd then add this to the I18n class:

    public static String getMessage(Enum<?> enumVal) {
        return getMessage(enumVal.toString().toLowerCase());
    }

I prefer to use this method because it incorporates the same translation logic in the same part of the program without impacting your design.  You may even want to differentiate enum keys from your other keys, in which case you can begin each enum key with "enum.", so you would prepend "enum." when calling getMessage.  Just remember to name your keys in your properties files accordingly.

I hope that helps!


问:
Why does this function work even though the vars are different
```<code>$inumber1 = 10;
$inumber2 = 20;

     function add($number1, $number2) {

        echo $number1 + $number2;
     }

     add($inumber1, $inumber2);
</code>```

I'm learning PHP coding for the first time and I'm following tutorials online.

The tutorial fails to explain why the above works and adds the numbers even if the vars don't match what is used in the function. I did some trial and error and it seems that if they match when the function is called it will work.  No matter what I name them like so.

```<code>$inumber1 = 10;
$inumber2 = 20;

 function add($sum1, $sum2) {

    echo $sum1 + $sum2;
 }

 add($inumber1, $inumber2);
</code>```

How does the function know to add the above value's if they have different names, and how is this useful in programming PHP?

答:
When you write code like

```<code>$inumber1 = 10;
$inumber2 = 20;

 function add($sum1, $sum2) {

    echo $sum1 + $sum2;
 }

 add($inumber1, $inumber2);
</code>```

What you are saying is "assign the value of $inumber1 to the function parameter $sum1."  So now $sum1 contains the same value that $inumber1 does.

It's done this way so that you can pass any value or variable you want to the function.

The second example works exactly the same way.  There's no name clash, because the formal parameter names take precedence over the names outside of the function.

$sum1 cannot be used outside the function.

Body:
When you write code like

$inumber1 = 10;
$inumber2 = 20;

 function add($sum1, $sum2) {

    echo $sum1 + $sum2;
 }

 add($inumber1, $inumber2);

What you are saying is "assign the value of $inumber1 to the function parameter $sum1."  So now $sum1 contains the same value that $inumber1 does.

It's done this way so that you can pass any value or variable you want to the function.

The second example works exactly the same way.  There's no name clash, because the formal parameter names take precedence over the names outside of the function.

$sum1 cannot be used outside the function.


问:
Adding complexity to remove duplicate code
I have several classes that all inherit from a generic base class. The base class contains a collection of several objects of type T.

Each child class needs to be able to calculate interpolated values from the collection of objects, but since the child classes use different types, the calculation varies a tiny bit from class to class.

So far I have copy/pasted my code from class to class and made minor modifications to each. But now I am trying to remove the duplicated code and replace it with one generic interpolation method in my base class. However that is proving to be very difficult, and all the solutions I have thought of seem way too complex.

I am starting to think the DRY principle does not apply as much in this kind of situation, but that sounds like blasphemy. How much complexity is too much when trying to remove code duplication?

EDIT:

The best solution I can come up with goes something like this:

Base Class:

```<code>protected T GetInterpolated(int frame)
{
    var index = SortedFrames.BinarySearch(frame);
    if (index >= 0)
        return Data[index];

    index = ~index;

    if (index == 0)
        return Data[index];
    if (index >= Data.Count)
        return Data[Data.Count - 1];

    return GetInterpolatedItem(frame, Data[index - 1], Data[index]);
}

protected abstract T GetInterpolatedItem(int frame, T lower, T upper);
</code>```

Child class A:

```<code>public IGpsCoordinate GetInterpolatedCoord(int frame)
{
    ReadData();
    return GetInterpolated(frame);
}

protected override IGpsCoordinate GetInterpolatedItem(int frame, IGpsCoordinate lower, IGpsCoordinate upper)
{
    double ratio = GetInterpolationRatio(frame, lower.Frame, upper.Frame);

    var x = GetInterpolatedValue(lower.X, upper.X, ratio);
    var y = GetInterpolatedValue(lower.Y, upper.Y, ratio);
    var z = GetInterpolatedValue(lower.Z, upper.Z, ratio);

    return new GpsCoordinate(frame, x, y, z);
}
</code>```

Child class B:

```<code>public double GetMph(int frame)
{
    ReadData();
    return GetInterpolated(frame).MilesPerHour;
}

protected override ISpeed GetInterpolatedItem(int frame, ISpeed lower, ISpeed upper)
{
    var ratio = GetInterpolationRatio(frame, lower.Frame, upper.Frame);
    var mph = GetInterpolatedValue(lower.MilesPerHour, upper.MilesPerHour, ratio);
    return new Speed(frame, mph);
}
</code>```

答:
In deciding whether it's better to have one larger method or two smaller methods with overlapping functionality, the first $50,000 question is whether the overlapping portion of the behavior might change, and whether any change should be applied to the smaller methods equally.  If the answer to the first question is yes but the answer to the second question is no, then the methods should remain separate.  If the answer to both questions is yes, then something must be done to ensure that every version of the code remain in sync; in many cases, the easiest way to do that is to only have one version.

There are a few places where Microsoft seems to have gone against DRY principles.  For example, Microsoft has explicitly discouraged having methods accept a parameter which would indicate whether a failure should throw an exception.  While it's true that a "failures throw exceptions" parameter is ugly in a method's "general usage" API, such parameters can be very helpful in cases where a Try/Do method needs to be composed of other Try/Do methods.  If an outer method is supposed to throw an exception when a failure occurs, then any inner method call which fails should throw an exception which the outer method can let propagate.  If the outer method isn't supposed to throw an exception, then the inner one isn't either.  If a parameter is used to distinguish between try/do, then the outer method can pass it to the inner method.  Otherwise, it will be necessary for the outer method to call "try" methods when it's supposed to behave as "try", and "do" methods when it's supposed to behave as "do".


答:
I think logic should always stay as much as possible in your application code. The application code is version controlled but your DB is not. If you have some code that relies on some logic in your DB, you might run into trouble later on. So if you're not changing your DB to some major state, keep your logic in your application code.

Just refactor your DAL but don't change interface/functions or how the BLL communicates with the DAL. This way you can easily switch to EF without refactoring your BLL. And when refactoring, always think of the SRP and don't think too big. You don't need to rewrite everything at once, just take a small portion at a time.

It's ok for them to be in the same DB, but like I wrote before, try to move them into your application code. Most of the logic should be there, except some major state change of your DB, then it's ok for it to be in a Stored Procedure.

Title: How do I write my BLL to make it re-usable?

Body:
Most of it was written 4-5 years ago.  Our teams long term objectives are to use Entity Framework. Though we aren't gonna do it right away as our deadlines aren't allowing us to do so.
Now we have our own framework. I want to be able to segregate the Business logic layer in such a way that it need not be re-written when we move to EF. Please guide us with best practices, advise us in this direction.

Our business logic layer is very fragmented today (UI Code Behind + Stored Procedures/functions SqlServer/ C# persistent classes) : What if I want to segregate it totally and draw a very prominent line between  Storage | DAL | Business Logic | UI

I want to know if it's ok to move the BLL totally in SQl stored Procedures or does it have to be totally C# classes?

Also to avoid re-writing the BLL as we are going to move to EF eventually. What steps should I take so that I can readily use the entire BLL with EF without changing the code.

A lot of the stored procedures (which have the BL) lie in the storage DB itself. Does segregating the BLL mean the SP's and functions should be in a different database altogether? or for all practical purposes it's ok for them to be in the same DB?

I've seen multiple questions on SO which were really helpful, but I just couldn't get a clear picture of the solution or advise I seek, so I put everything in one post.

Please correct me if I'm wrong. I'm a novice when it comes to system design. I wanna be able to foresee  what I'm getting into before actually implementing it.


问:
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?

答:
If I understood your question correctly, you can just use a local static variable to store the result of the expensive calculation.</p>

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

Body:
If I understood your question correctly, you can just use a local static variable to store the result of the expensive calculation.

class Value
{
private:
  int eval()
  {
    static int mCached = ExpensiveOperation();
    return mCached;
  }
};


问:
Best Git workflow suitable for our needs
I need help with the workflow that is best suitable for our needs. We are a 3-4 person team and are working on 4 different projects.

We have three main branches:

master - deployable production branch

staging - features under QA on live data

dev - features under QA on test data

Then for each feature, we create a feature branch

What we need:

Sometimes we would like to create a release (for many features that have something in common) and would be deployed in the end of the month.

Sometimes we would like to deploy a specific feature/change (without creating a release). This is what we do most of the time.

Now to the workflow:

I start working on some feature. I create a feature branch off from dev.

I finish my feature (with 30 commits).

I squash merge my feature into dev - so it becomes just one commit.

The feature is automatically deployed to a testing environment and QA tests out my feature on test data.

The feature tested OK, so I cherry-pick my feature commit hash to a staging branch. The feature is automatically deployed to a staging environment and QA tests out my feature on live data.

The feature passes QA (test and staging) and is either cherry-picked to master or to a release branch, which will be merged with master in the end of the month.

Here's a picture explaining what I have in mind:

Does this all make sense? Is there a better way to achieve this goal? Thanks for your time.

答:
Seems very reasonable. We are using something very similar. My advise is just to keep the feature branches small. Maybe one days work. Longer brances means lower productivity due to a large number of merge conflicts. Mostly one feature branch equals one post it note on our scrum board.

One note is you write "I start working on some feature. I create a feature branch off from dev." This is a good approach 80% of the times. Remember you have the option to branch of a pending pull request. We have a rule on the team that we should get someone else from the team to review and merge pull requests. Sometimes PRs stay in the queue for a few hours. Since we are using quite small pull requests. Sometimes feature B depends on feature A, but feature A is not going to be merged for a few hours and thus not in dev. When you want to start working on feature B just merge off of A instead of dev. It is better to merge off dev if possible, but it is a good tool in your belt. You should in that case probably wait to create the PR for feature B before feature A is merged to dev because diffs will look like both A+B which is misleading.


问:
"A proof is a program; the formula it proves is a type for the program"
This might be a philosophical kind of question, but I believe that there is an objective answer to it.

If you read the wikipedia article about Haskell, you can find the following:

The language is rooted in the observations of Haskell Curry and his intellectual descendants, that "a proof is a program; the formula it proves is a type for the program"

Now, what I'm asking is: doesn't this really apply to pretty much all the programming languages? What feature (or set of features) of Haskell makes it compliant with this statement? In other words, what are the noticeable ways in which this statement affected the design of the language?

答:
The Kleene Hierarchy shows us that proofs are not programs.

The first recursive relation is either:

```<code>R1( Program , Iteration )  Program halts at Iteration.
R2( Theorem , Proof ) Proof proves a Theorem.
</code>```

The first recursively enumerable relations are:

```<code>(exists x) R1( Program , x )  Program Halts.
(exists x) R2( Theorem , x)   Theorem is provable.
</code>```

So that a program is a theorem and the iteration that exists at which the program halts is like the proof that exists that proves the theorem.

```<code>Program = Theorem
Iteration = Proof
</code>```

When a program is correctly produced from a specification, we must be able to prove that it satisfies the specification, and if we can prove a program satisfies a specification then it is correct program synthesis.  So we perform program synthesis iff we prove the program satisfies the specification.  The theorem that the program satisfies the specification is the program in that the theorem refers to the program that is synthesized.

Martin Lof's false conclusions have never produced any computer programs and it is amazing that people believe it is a program synthesis methodology.  No complete examples have ever been given of a program being synthesized.  A specification such as "input a type and output a program of that type" is not a function.  There are multiple such programs and to choose one randomly is not a recursive function or even a function.  It is just a silly attempt to show program synthesis with a silly program that does not represent a real computer program calculating a recursive function.

Body:
The Kleene Hierarchy shows us that proofs are not programs.

The first recursive relation is either:

R1( Program , Iteration )  Program halts at Iteration.
R2( Theorem , Proof ) Proof proves a Theorem.

The first recursively enumerable relations are:

(exists x) R1( Program , x )  Program Halts.
(exists x) R2( Theorem , x)   Theorem is provable.

So that a program is a theorem and the iteration that exists at which the program halts is like the proof that exists that proves the theorem.

Program = Theorem
Iteration = Proof

When a program is correctly produced from a specification, we must be able to prove that it satisfies the specification, and if we can prove a program satisfies a specification then it is correct program synthesis.  So we perform program synthesis iff we prove the program satisfies the specification.  The theorem that the program satisfies the specification is the program in that the theorem refers to the program that is synthesized.

Martin Lof's false conclusions have never produced any computer programs and it is amazing that people believe it is a program synthesis methodology.  No complete examples have ever been given of a program being synthesized.  A specification such as "input a type and output a program of that type" is not a function.  There are multiple such programs and to choose one randomly is not a recursive function or even a function.  It is just a silly attempt to show program synthesis with a silly program that does not represent a real computer program calculating a recursive function.


答:
A caution from an experienced designer who loves databases:  Trying to guess data relationships without having an executive approved set of Business Use Cases, Entity-Relationship Diagrams, a Master Data Flow Diagram across the enterprise, etc. is dangerous. Your question seems to show that you are trying to capture the relationship flaws "on-the-fly" from the database perspective, instead of planning the structure from the approved data diagrams and then building the bridges you may need to wedge the old system into the new. That can lead to accounting problems... not just data nightmares like the ones you have already surmised. (a sample case )

An interesting trend I have seen with some systems is to have Persons tracked as data objects, who can be validated as real-world objects by personally identifiable information.  Persons can have a portfolio including Roles and Histories, allowing them to be referenced as they move across organizations, or Tags allowing them to be referenced across various data services or data warehouses.  Watch out for privacy concerns...

Customer as a role that can toggle between using data from Organization objects or Person objects, with a flag indicator, may allow you to manage your b2c b2b integration problem without requiring too much transitional modification.  In general Transactions store details as the foreign key of an object in the position of a role and timestamp. For example an object called Location, connected to GIS, could have a role as ship-from, ship-to, bill-to, bill-from or mail-to.

Tables for critical systems should have: unique id, active/inactive flag, active date-time, last modified date-time, inactive date-time, status code - These will allow you the best control over historical data queries and transaction control logs.  Status code allows you to track things like merging records, entered in error, legal flags, etc. as well as minimizing data duplication in transactions

Newer ERP systems will deal with structured Database and unstructured data, SQL and NoSQL, etc.  Objects, Roles and Transactions as a mindset used in planning may minimize your headaches going forward.


问:
Why don't developers make installation wizards on linux?
I'm sure it's not about laziness or anything like that but I fail to understand why developers of even mainly consumer facing apps don't make any sort of installation wizard where you go next-next-finish. The same apps usually have installers for Windows and Mac OS so why not Linux?

Is there any technical reason for this trend or is it just convention?

EDIT (23-09-2014):
This question was not asked to start a Windows vs Linux flame war. I have used all 3 major operating systems and apart from Linux, the other two (Windows and Mac OS) both have installers. I have not installed Oracle yet but whatever I have needed to install, I never saw any GUI installer for Linux.

Yes, I know that Linux has package managers so the developers don't "need" to make the installers. But there is still a huge amount of software that is either outdated in the default package managers, or simply not available. Plus, since Linux is sold as an alternative to Windows for casual users (Ubuntu is trying hard in this domain), it would make much more sense to just give the users what they are familiar with.

Take for example, setting up a LAMP stack. Those are all open-source software in the default repositories, but can you set-up everything in one go without a script? Now look at the WAMP server in Windows. You just run an installer and it installs multiple software in such a way that they work well with each other. Then it sets up good defaults and stuff. Installers can do that, package managers don't. Yes, you can find a script for that online, but where? And which one?

Installers aren't some obsolete technology from the past. They are still useful, and 95% users are already comfortable with them.

答:
Usually, the installation doesn't need interaction with a user (most apt-get packages for example), or can be scripted. This makes it very easy to automate in order to deploy a piece of software on many machines. Instead of doing things through the wizard, you do those same things through scripting or through configuration files.

Given that in Linux world, terminal comes first, and the GUI is optional, it becomes obvious why do they lack actual installation wizards.

Windows, on the other hand, is very user-oriented. Most MSI files can easily be deployed in unattended way, in the same way Windows installation can be unattended (how easy/difficult is to get WAIK to work is a different subject). This also means that a bunch of applications for Windows are not based on MSI, and are not scriptable. Among enterprise-scale application, Adobe products, for example, are known for being rather difficult to install in a scripted way.


答:
Developers just need to provide a package for a distribution. Each distribution then has a way to install this package. This way can be in a terminal (apt-get) or via a graphical interface, e.g. Ubuntu Software Center.

The beauty is that developers just have to care about building a proper package; the distribution makers take care of the rest, and each package installation has the same process.

Title: Why don't developers make installation wizards on linux?

Body:
I'm sure it's not about laziness or anything like that but I fail to understand why developers of even mainly consumer facing apps don't make any sort of installation wizard where you go next-next-finish. The same apps usually have installers for Windows and Mac OS so why not Linux?

Is there any technical reason for this trend or is it just convention?

EDIT (23-09-2014):
This question was not asked to start a Windows vs Linux flame war. I have used all 3 major operating systems and apart from Linux, the other two (Windows and Mac OS) both have installers. I have not installed Oracle yet but whatever I have needed to install, I never saw any GUI installer for Linux.

Yes, I know that Linux has package managers so the developers don't "need" to make the installers. But there is still a huge amount of software that is either outdated in the default package managers, or simply not available. Plus, since Linux is sold as an alternative to Windows for casual users (Ubuntu is trying hard in this domain), it would make much more sense to just give the users what they are familiar with.

Take for example, setting up a LAMP stack. Those are all open-source software in the default repositories, but can you set-up everything in one go without a script? Now look at the WAMP server in Windows. You just run an installer and it installs multiple software in such a way that they work well with each other. Then it sets up good defaults and stuff. Installers can do that, package managers don't. Yes, you can find a script for that online, but where? And which one?

Installers aren't some obsolete technology from the past. They are still useful, and 95% users are already comfortable with them.