问:
When should I mix functions with data in a class?
Based on some questions I asked (1, 2,3), I am frequently suggested to separate data from functions (because of changes in function, single responsibility, separation of concerns, adopting interfaces, immutability, ...).

Then my question is: In which situation functions should be encapsulated with data? what type of functions are they? Is representing an entity or a concept a single responsibility? if yes then I may conclude no function should be introduced in a class which represents an entity! Did I miss something?

According to the following approaches, what happens if I always follow the second approach! Please note in the second approach class Entity has no private state variable as it has no function, then its fields are accessible in class EntityOp1 and EntityOp23

```<code>class Entity
{
    public data;
    private s1, s2, s3;
    operation1;
    operation2;
    operation3;
}
</code>```

vs.

```<code>class Entity
{
   public data;
}

class EntityOp1
{
     Entity e;
     private s1;
     operation1;
}
class EntityOp23
{
     Entity e;
     private s2, s3;
     operation2;
     operation3;
}
</code>```

答:
If you need examples when to bind data and behavior and when to separate, patterns books like GoF do have them. Important part: every pattern has a well-defined applicability area, telling when to use it.

Another basic design principle is "Low coupling (between entities), high cohesion (inside single entity)", the entities being objects or functions or pure data objects.

Together with patterns, you need a vision what to apply them to - that is, what to model. I recommend Martin Fowler's "Analysis patterns" book and Eric Evans' "Domain-driven design" AKA "DDD".


问:
How important are code formatting guidelines?
Coding standards are common in any software development organization, but how important are they to follow?  I can understand the need for some consistency, but when dealing with simple things like the position of braces, line length, etc., I'm not sure excessively strict standards contribute much to software development.

Isn't it more important that your code is readable, not that it conforms to a predefined standard?  It seems they're more like... guidelines anyway.

答:
If you use and IDE that does the basics of this for you (Visual Studio for example), let the IDE do it's thing and whatever seems to still be hard to look at you modify as long as you still let the IDE do it's thing or the next person that auto-formats it is just going to kill it anyway.

What is most readable to one person will not be for all people.

If you are not using this sort of IDE get one.  Even thinking about this for more than 10 minutes is a waste of resources IMHO.

ContentLicense: CC BY-SA 2.5


问:
Is it advisable to disable the Microsoft enforced coding standards in VC# 2010?
Coming from eclipse I've developed my own coding standards which I got used to. In Visual C# 2010 however, it appears that some coding standards that MS recommends are enforced in the default configuration.

E.g.: I'm used to write conditional statements like this:

```<code>if (somecondition) {
    return true;
} else {
    return false;
}
</code>```

But the braces are forced to a newline in visual c#. Is it recommended to use that standard ?

答:
Brace style in C# is not enforced by Visual Studio. In fact you can customize it to format source matching your style.

Look under Tools > Options, Text Editor > C# > Formatting > New Lines there you'll find lots of options to control the behavior.

Obviously, you may want to consider having your coding style adapt to the style of other team members but you should not need to change the style to match the defaults in the IDE.

OwnerDisplayName: Max


问:
Using Open Source code in a project
I'm having a little trouble in understanding how exactly Open Source licenses actually work. I have programmed for a while, but just for my personal use and I wrote all the code I needed myself.

As I'm thinking of making some apps for people and I need a fast XML parser, I thought I could use RapidXml. However, I'm not sure how it's going to be like under the license.

So, here's my question: if I use some code as part of my application, without any modification, how does it's license affect me? Exactly as if I was modifying it and distributing it? Do I have to publish my entire code?

Also, coding this app will require knowing the implementation of another open source project. Though, I'm going to write my code in a different language, i.e. I just need to know how it works for me to reproduce it. How does the license work here? (As a matter of fact, this one is GPLv3, and the other is not.)

答:
There are lots and lots of different open source licenses which have lots and lots of different conditions and fine-prints. They all work differently.

RapidXML is dual-licensed under the MIT license and Boost License, and you are allowed to choose freely under which license you want to use it. They are both so-called permissive open source license. A permissive license allows you to modify and/or use the software as part of a product which is licensed under any license conditions you want. You don't need to publish your sourcecode, even when you modify the library. The only condition is that you place the original copyright message with the license conditions in the credits of your product so the end-users know that it uses the RapidXML library.

The GPL, however, is a different beast. It is a so-called copyleft or share-alike license, which means that any product which includes GPL-licensed code must also be licensed under the GNU GPL. However, when you reimplement features with completely original code and do not use any of the original code, you are creating an own work which is only bound to your license conditions. But be aware that a straight 1:1 translation into another programming language is a legal gray area. The GNU GPL FAQ says that this is not allowed:

What does the GPL say about translating some code to a different programming language?

Under copyright law, translation of a work is considered a kind of modification. Therefore, what the GPL says about modified versions applies also to translated versions.

<advertising>When you have more questions about open source licenses, you might want to commit to the new proposal Open Source Stackexchange. It still needs people to commit to it so it can go into beta phase.</advertising>

ContentLicense: CC BY-SA 3.0

Title: Using Open Source code in a project


问:
Why are my unit tests so expensive?
I am a Java developer, working on a small project. We are three people in the team, we have a budget for 3 months of coding (+ some time for the Analyst, Project Manager and QA team). It is a small project, the budget is really limited. There is some support in our organization to do the unit tests, but I didn't meet any expert in this area. Motivated by books and discussions, I started to do the unit tests. I have some limited experience with frameworks and approaches, so I don't test every getter, I focus on business code, I use Mockito and MoreUnit Eclipse plugin to generate the skeleton and Mocks. I design my code upfront, I use plenty of design patterns, I keep my code clean, with short methods, I respect the Single Responsibility Principe and I have much more public methods then the private ones. It is not perfect, but it is the best I can do after 5 years of commercial experience in one corporation and one mid size company.

So why does making unit tests take me the same or even higher amount of time then coding productive code? After last two days of unit testing I found just one minor bug and it didn't come from the tests, I just randomly found it when I was looking into the production code. Where are the benefits the people are talking about? Every refactoring caused just throwing away existing unit tests and they never told me if I influenced the rest of the system. Every class I test has mocked out its surroundings, so if I change one class, it will not affect the other tests and I won't know if I messed up the system by my change.

What am I missing? Am I doing it wrong?

Edit: To add some numbers, I spend about 80% of time by designing and coding, and 20% by unit testing, so just small amount of my code is covered by tests. I try to do unit test fot 1,5 month, usually after I finish some functionality and roughly test in on my local development machine.

答:
If you first test things manually through a user interface, until you do not find any bugs any more, and write unit tests afterwards, it is not very surprising that those unit tests do not reveal many bugs.  You are probably just automating things you already have done manually, but do not code many test cases which were not already part of the manual tests.

Unit tests and other automated tests will show up their value much clearer when you

can use them for testing things which you cannot easily test through the UI

when you develop small, UI independent components and test them through unit test without actually having coded the UI for them

when your application becomes bigger, and after release no. 25 or later you notice that repeating the same tests again and again through the UI becomes tedious

when you develop software without any UI  or where the UI lets you only access a small part of the system directly (for example, a google-like UI).

when you do TDD, where you must write unit tests, otherwise you cannot even start with writing code

So if you are not going to switch to TDD style coding, and as long as you are writing UI applications up-front, with most functionality directly accessable through the UI, do not be astonished that test automation of any kind will be an additional investment, which may look tedious to you and will not show its real value immediately.

Title: Why are my unit tests so expensive?


答:
One thing to remember about testing is that you're going to do it either way. Whether you're printing application variables to the screen, using a debugger to inspect your application's state or just visually verifying the final output of the application's input, at the end of the day, you'll have spent quite a bit of time commenting out code, perhaps setting breakpoints or performing other testing tasks in an attempt to verify that your code is functioning within the expected business rules. The question to ask yourself is, will you codify the fruits of your labor in a repeatable process, or simply delete/comment out the ephemeral test code once everything appears to function correctly?

The benefits of testing become more visible the longer the project goes on. When one first designs a piece of software it might feel like tests are unnecessary because it's easy to imagine many of the edge cases in one's mind, however, as a project matures and becomes more complex, you'll eventually encounter unforeseen problems that when solved may inadvertently break something you've already fixed and tested manually. If it's been a long time or someone else ends up fixing the bug, you won't even realize that time has been wasted retracing the path of the problem, assuming the bug is even rediscovered at all. Unit tests let you move forward in confidence knowing you're building on top of a foundation that performs as specified. Creating tests means that every bug you fix is also solved forever, never to be inadvertently reintroduced into a live product through subsequent code changes by yourself or someone else on the team.

Writing tests sometimes feels like more work because you can look at the test and identify it as the product of your time spent working during a session, however, every experienced developer knows that sometimes one can spend hours trying to debug what seems like a very simple problem, only without tests, we simply attribute the time spent to "necessary debugging" rather than "writing tests all day". You can't blame a bug that no longer exists, but it feels natural to look at a paltry set of tests and wonder why you don't have more to show for your time when in reality both outcomes are the same.

Now, this isn't to say that it's not possible to waste time fiddling with test tooling or writing inefficient or unnecessary tests. It does take a bit of time to get a feel for writing appropriate tests but in my experience the best way to avoid these problems is to plan ahead. Define a specification that serves as a definition for a properly functioning baseline or prototype of your application and test to the spec. If you find that the spec is constantly changing and you're always throwing out tests then it probably means that your design is flawed or that the problem space is not properly understood. The key to writing successful tests is having confidence that the tests truly represent the product you want to produce.

Title: Why are my unit tests so expensive?

Body:
I am a Java developer, working on a small project. We are three people in the team, we have a budget for 3 months of coding (+ some time for the Analyst, Project Manager and QA team). It is a small project, the budget is really limited. There is some support in our organization to do the unit tests, but I didn't meet any expert in this area. Motivated by books and discussions, I started to do the unit tests. I have some limited experience with frameworks and approaches, so I don't test every getter, I focus on business code, I use Mockito and MoreUnit Eclipse plugin to generate the skeleton and Mocks. I design my code upfront, I use plenty of design patterns, I keep my code clean, with short methods, I respect the Single Responsibility Principe and I have much more public methods then the private ones. It is not perfect, but it is the best I can do after 5 years of commercial experience in one corporation and one mid size company.

So why does making unit tests take me the same or even higher amount of time then coding productive code? After last two days of unit testing I found just one minor bug and it didn't come from the tests, I just randomly found it when I was looking into the production code. Where are the benefits the people are talking about? Every refactoring caused just throwing away existing unit tests and they never told me if I influenced the rest of the system. Every class I test has mocked out its surroundings, so if I change one class, it will not affect the other tests and I won't know if I messed up the system by my change.

What am I missing? Am I doing it wrong?

Edit: To add some numbers, I spend about 80% of time by designing and coding, and 20% by unit testing, so just small amount of my code is covered by tests. I try to do unit test fot 1,5 month, usually after I finish some functionality and roughly test in on my local development machine.


问:
How do you unit test \ use TDD methods for ETL's and reporting projects?
ETL projects are projects created using an ETL (Extract - Transform - Load) tool such as SSIS, PowerCenter,etc

These typically involve reading data from an external source, loading it to a staging database, performing certain transformations and loading it to a final database

A simple example would be to use SSIS to read excel files provided by schoolteachers using SSIS and load them into a database. Then write stored procedures or more SSIS packages to calculate the grades of each student and load that data into a data mart\warehouse

You then build stored procedures on top of the mart to generate output which is used by reporting tools (SSRS\Excel\etc) to generate visualizations.

I'm trying to understand how to perform TDD and proper unit testing in this scenario. Tests for ETL's are mostly about ensuring the data loaded in the staging tables matches is the right subset of the data from the source. So implementing a test for it leads to implementing a mini version of the ETL. The output of the report SP's depends on the data in the tables themselves, so one cannot have a stable set of output data without a maintenance nightmare even if you do create a database containing scrubbed test data

Example:

Sprint 1 : Student table contains Name, Age, Grade

You create test data for this table, and unit tests based on that

Sprint 2: A gender field is added to the table.

Now, if you refresh the data in the student field to populate the gender attribute, the test cases are invalidated since the data changed. And if you dont, you cant create test cases that require the gender column

答:
ETL can be done with TDD and tests pretty similarly to most projects, i.e.

write a test that fails (red)
fix the failure (green)
make the code performent & maintainable (refactor)

So for ETL that might be:

write a script to load 1 record

fail (no data source defined)

define source [green]

no refactor need

write a test to load 1 record with only 1 field filled in

fail (no code written for that field)

define code details for that field

refactor

define failing tests that look for attributes having valid values [red]

etc


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

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

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

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

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

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

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
I would like to see a legit method of creating/defining CONSTANT arrays. There are a few hackish ways to simulate this kind of functionality but it would be nice if it was just a straight up feature of PHP.  It would be nice if you could create an array in a way that is similar to Java's "final" declaration.

I created a login system that is very quick to setup. All you have to do is change the contents of an array in a text file to specify the fields you want for user information.  Using a swath of for loops it handles everything from form generation and input sensitization, to database calls but it is all dependent on this original array.

The file with the array is locked down with permissions but once the array is moving around in the ether it is mutable. Although I feel the system is pretty secure I don't like leaving anything to chance.  A method to finalize arrays would be nice for a situation like this.

New Idea!!

Ohhh, I thought of something else I would really really like in php.  I would like some kind of system to control php file operations and directory operations similar to the way .htaccess works.

The .phpaccess file should trigger some kind same domain/same origin policy.

For example, If I were hosting many sites with virtual hosts I could have a .phpaccess file in a directory that would tell php to check the orgin of any scripts being executed which are trying to operate on my protected directory.  If the script did not come from that directory or its sub-directories then the file operations / or socket operations will be denied.

I think a system like this would make virtual hosting a much safer environment.  If you could place one of these at the top of each virtual host it would lessen the chance of someone finding a way to sneak in from a neighboring virtual host.

Also if it would be good to have a method of securing it in the inverse of this manner. ie, restricting the reach of scripts in a single directory to that directory.

Its the yin and the yang ya know!


问:
Client wants source code, but it contains a lot of shared code I reuse with other projects
I have a client who would like me to deliver the source code with a developed application binary. They originally said nothing about source code, but they recently said they need it. The contract is not finalized. They agreed to the work, did not sign, and then came back with this clause.

The issue is: I have a code base I've created over the years and used as a template for most of the applications I write. It is far larger than the scope of the project.

I also intend to use it for a product, so I really don't wish to provide it for a relatively small project.

I'm guessing this is not the first time that this has happened in this industry. What is the best way to circumvent this issue? I'm guessing things like shared libraries could help.

答: If you use a third party with the software that you deliver,  chances are that you don't have the source code for this third party. You will still deliver the software to the company with binaries of the third party. The code that you developed as a framework shared in all your projects is exactly like third party even if is owned by you. In this case, the company have exactly the same risk with the binaries of your framework than with the third party. Why in this case would you give to the company the source code of your framework. You can provide to her a good API documentation with a licence agreement and that it. If your code contain the next big thing that will revolutionize the industry, it's another story but it's generally not the case. </p>


问:
IoC invalidation
I have a bunch of services that get registered as singletons by my IoC container on startup, all of these services have a constructor which takes in a connection string which is used by the underlying storage provider.

This has been fine given the connection string was static and never changed during a session, however, I now need to implement the ability for users to change the connection string at runtime (e.g. they can choose to point to a local/cloud DB).

Ultimately, what this means is I need to somehow invalidate all my services in the IoC container and as far as I could see my chosen IoC container doesn't appear to provide a means of doing this, so it's down to me to come up with a practical solution.

Now there are many ways I could do this but I am looking for feedback, suggestions (from experience if possible) on what would be considered the optimal solution. Here is a simplified service

```<code>public class Service
{
    public Service (string connectionString)
    {
        this.ConnectionString = connectionString;
    }

    // marked as protected as derived services may need access to them
    protected string ConnectionString { get; set; }
    ...
}
</code>```

And here is how it is currently registered

```<code>public static void StartUp(IAppSettings appSettings)
{
    container.Register<IService, Service> (new Service(appSettings.ConnectionString));
    ...
}
</code>```

The simplest solution, which I personally don't like, is simply to have all my services take a reference to IAppSettings rather than ConnectionString and use a read-only property e.g.

```<code>protected string ConnectionString { get { return appSettings.ConnectionString; } }
</code>```

However, given all that the services need from IAppSettings is the connection string this just seems wrong from a modelling point of view. Keeping with this approach, but improving on it slightly would be to introduce a new interface which exposes only the information needed from IAppSettings e.g.

```<code>public interface IDbSettings
{
    string ConnectionString { get; set; }
}

public class AppSettings : IAppSettings, IDbSettings
{
    ...
}
...
container.Register<IService, Service> (new Service(appSettings as IDbSettings));
</code>```

I say slightly because ultimately I still have the same problem (services are still referencing a large object for one simple property).

The type of approach I would like, and what I feel would be best, would be to extend the current IoC container to introduce an Invalidate method whereby I can simply set the internal instance to null and have it re-initialized when resolved. I see this looking something like

```<code>appSettings.ConnectionString = "database=db1";
container.Register<IService, Service>(new Service(appSettings.ConnectionString));
...
var svc = container.Resolve<IService>(); // connects to db1
appSettings.ConnectionString = "database=db2";
...
var svc = container.Resolve<IService>(); // still connects to db1
container.Invalidate<IService>();
var svc = container.Resolve<IService>(); // connects to db2
</code>```

For me this gives all round benefits

You control exactly when you want the changes to take affect

It keeps with the Singleton pattern

It means the only thing that changes is the IoC container

I would be interested in everyones thoughts, critiques etc.

答:
Your second approach is the correct one, I feel.

I say slightly because ultimately I still have the same problem (services are still referencing a large object for one simple property).

The size of the object that your other objects are referring to is not the issue.  The size of the interface that they're referring to is the issue.  It doesn't matter that the interface is implemented by an object that has 1000 properties on it, if the interface only exposes a single property.

I think your third solution is a really bad solution.  It is creating a very leaky extraction.  Why should the class that's responsible for changing the connection string care about other classes that use the connection string?  Why should the IOC container care about the state of its objects and not simply the management of their lifetimes?

The primary purpose of an IoC container is to manage your object graph.  It handles the creation and destruction of your objects for you.  It allows you to more easily write code that follows the Dependency Inversion Principle.  In this case, the dependency is the connection string.  If many of your classes are dependent only on the connection string, then it makes sense that they should be dependent on an interface that only defines a connection string (and any methods/properties related specifically to that connection string).  It doesn't matter which class actually implements that interface and provides that functionality (unless that class has significant performance issues).

This is part of the point of the DIP.  It allows you to refactor the classes behind the interfaces without having to worry about the classes that use the interfaces.  In this case if you created the connection string interface and had everything use that, it would be a cinch to refactor your appSettings class into an AppSettings and ConnectionSettings class behind the scenes without affecting any of the dependent classes.

Following the Dependency Inversion Principle is the best way to go in this case.  Create the small interface and have your code dependent on it.  The IoC container can then do what it was designed to do.

Title: IoC invalidation


问:
Handling the end of sprint cycle between testers and developers
I've convinced our organization to move to a full-team definition of "Done", i.e. one that includes the QA testing and not just code completion. As a result, we can now more accurately tell where the bottlenecks are and see what our real velocity is. As well, this project continuously integrates and deploys regularly. Prior to this, code-complete items were considered done, and QA would routinely be getting around to accepting stories from 3-5 sprints ago. They would only get the delivered code at the end of the sprint.

So, as you can expect, things are running much more smoothly, but I have a question that hasn't quite been answered before in my search. Even with sprinting, there seems to be a max time in the sprint that a story can be finished by developers and deployed before there isn't sufficient time left for QA. Depending on the story and volume of things that still need testing, this seems to be about 2-3 days before sprint end.

Currently, we just continue working on things and just move all items not accepted by QA (i.e. things in progress and things deployed but not tested) to the next sprint if they are unable to complete testing. Is this an OK practice? Some devs that were used to working under the old system complain that this doesn't give the developers credit for completing the work that they were assigned, but I feel that the idea is to get a picture of what the whole team did, not just development. The end-user gets no value from things not tested and deployed. However, this process is having a tendency to pre-load the next sprint, which makes planning slightly more problematic.

Additionally, I have heard that having an end of sprint developer lull is actually OK. Should we be instead looking to leave some open developer time at the end?

答:
It is your team's responsibility -- the whole team -- to make sure everything is done. If the devs are finished coding and there are still tests to write or perform, they should pitch in and help the testers.

There shouldn't be any "open developer time" -- why penalize your testers by giving the developers free time? The developers need to help with the testing. It will make your product better, it will make your developers into better developers, and it will make your testers feel more valued.

The developers should not be "pre-loading" the next sprint until all of the work in the current sprint is done. There are exceptions of course, but in general they shouldn't be starting any new work until all of the existing work is done.

Some devs that were used to working under the old system complain that
  this doesn't give the developers credit for completing the work that
  they were assigned

This is good, because developers aren't supposed to get any credit at all. The team gets credit, and by not giving the devs credit, the whole team is made stronger.


问:
What's the point/Use of writing out just the method signatures for an API in .Net Web Api
I have been asked to write the signatures for and API end points GET/POST/PUT methods. I'm having a hard time wrapping my head around what the point of this is. My co-worker asked if I could do this before they come in and add the implementation. Would this mean that all I'm adding to the Web Api controller is a bunch of code that looks like this below?

```<code>GetSomething(string value1, string value2)

PutSomething(string value1, string value2)

PostSomething(guid value1, int value2, string value3)
</code>```

I'm having a hard time understanding what the point of this would be. Since with out having the return types and what not the code isn't usable if they have not been declared. I can see this being useful in documentation though.

答:
The general case here is identifying the external interface.

It should be possible to write an interface for two systems or modules to interact, define what the method signatures are, data formats, preconditions/postconditions, etc. with zero implementation behind it.

Next, separate teams work on separate code that use that interface. Perhaps one team implements the code that makes the interface work while another team implements the code that invokes the interface.

Interfaces can be difficult. Moving data between systems, formats, etc. can be fraught with problems. By identifying interfaces early, documenting them, and having plenty of time to test, you have a better shot at having a fully functioning system by the time it is supposed to be delivered.

In this specific case it might be true that return types or certain other details are not known yet, but enough is known to begin work. It is impossible for anyone here to say for sure given we are not on your team at work. However, I have seen interface development proceed this way in the past. Customer says "we need a web service that adheres to this interface, but we are not quite sure what to return yet. We need customer data, but do not have a list of all the fields yet." That is enough to start on. I have a pretty good idea of what the code behind the interface needs to do, I am just not sure about petty details which can be ironed out later without affecting the schedule.


答:
Languages all have their own odd coding styles - I'd say it's easiest just to follow them and don't think too much about it. If everyone just follows the most common standard of the language, then no time is wasted on fighting about personal ideas of good style.

In the case of C#, the programs StyleCop and FxCop check's your C# code and .NET binaries against some coding style guidelines defined by Microsoft.

Title: Is it advisable to disable the Microsoft enforced coding standards in VC# 2010?

Body:
Coming from eclipse I've developed my own coding standards which I got used to. In Visual C# 2010 however, it appears that some coding standards that MS recommends are enforced in the default configuration.

E.g.: I'm used to write conditional statements like this:

```<code>if (somecondition) {
    return true;
} else {
    return false;
}
</code>```

But the braces are forced to a newline in visual c#. Is it recommended to use that standard ?


答:
Some devs that were used to working under the old system complain that this doesn't give the developers credit for completing the work that they were assigned

Did they really complete the work in time when there is not enough time left in the sprint for completing the test cycle? Maybe, maybe QA needed more time than expected, who knows, but the customer is not interested in who in your team is to blame.

One of the core ideas of agile is to adjust your planning with every sprint. If your VCS and branching model gives you the ability of simply moving feature implementations from one sprint to the next, then use that - not delivering untested code will surely give you a better product, your customers will value that. Just make sure you do not pollute your released product with "developed, but untested" code - such code is always unfinished.

And - as you already noted in your question - you have to make sure you adapt your planning for the next sprint. When your devs already provide a newly implemented feature at the first hour of the new sprint (because it was developed in fact during the previous sprint), then your QA people will need more time for testing in the current sprint, or less additional features to test. If that happens regularly, and your devs produce constantly more output than QA can test, you have to change something in your process or your organization (maybe you need more QA people, maybe you should assign your devs more tasks in the area of test automation).

Title: Handling the end of sprint cycle between testers and developers

Body:
I've convinced our organization to move to a full-team definition of "Done", i.e. one that includes the QA testing and not just code completion. As a result, we can now more accurately tell where the bottlenecks are and see what our real velocity is. As well, this project continuously integrates and deploys regularly. Prior to this, code-complete items were considered done, and QA would routinely be getting around to accepting stories from 3-5 sprints ago. They would only get the delivered code at the end of the sprint.

So, as you can expect, things are running much more smoothly, but I have a question that hasn't quite been answered before in my search. Even with sprinting, there seems to be a max time in the sprint that a story can be finished by developers and deployed before there isn't sufficient time left for QA. Depending on the story and volume of things that still need testing, this seems to be about 2-3 days before sprint end.

Currently, we just continue working on things and just move all items not accepted by QA (i.e. things in progress and things deployed but not tested) to the next sprint if they are unable to complete testing. Is this an OK practice? Some devs that were used to working under the old system complain that this doesn't give the developers credit for completing the work that they were assigned, but I feel that the idea is to get a picture of what the whole team did, not just development. The end-user gets no value from things not tested and deployed. However, this process is having a tendency to pre-load the next sprint, which makes planning slightly more problematic.

Additionally, I have heard that having an end of sprint developer lull is actually OK. Should we be instead looking to leave some open developer time at the end?

ContentLicense: CC BY-SA 4.0


问:
Report to capture scope creep in iteration
I am looking for a report to capture the "Scope Creep" within an iteration.  We are using Scrum on TFS 2013 on premise.

We are constantly asked by management to bring work into an iteration, but are still pressured to meet the commitments made in the planning meetings.  Unfortunately it happens often enough that it isn't a matter of manually tracking 1 or 2 work items per iteration.

Also sometimes we have just underestimated work and it takes longer than we had planned.

I would like to pull a report from TFS or the warehouse/cube which shows when work is brought into an iteration (i.e. new PBI/Bug added) or work on an existing item increases.

I would like to use this report to show management the impacts of bringing in unplanned work and/or use the report as data to improve our estimates.

答:
Here is a script that I prepared that will look through the workitemhistory view to work out when an iteration changes on a date which is between the iteration start and end date.

It is a work in progress, but it demonstrates that the answer is there if you need it.

```<code>DECLARE @iteration VARCHAR(300)
DECLARE @startDate DATETIME
DECLARE @endDate DATETIME

SELECT @iteration = '\TeamProject\Team\Sprint 4';

SELECT @startDate = startdate, @endDate = finishDate
FROM DimIteration
WHERE iterationpath = @iteration;

WITH CTE_ALLWorkItemsInIteration
AS (
    SELECT DISTINCT system_id
    FROM WorkItemHistoryView
    WHERE IterationPath = @Iteration
    )
,CTE_WorkItemHistory
AS (
    SELECT *
        ,ROW_NUMBER() OVER (
            PARTITION BY System_Id ORDER BY [System_ChangedDate] ASC
            ) AS Recency
    FROM WorkItemHistoryView
    WHERE system_id IN (
            SELECT system_id
            FROM CTE_ALLWorkItemsInIteration
            )
    )
SELECT CurrentWI.System_id
    ,CurrentWI.System_WorkItemType
    ,CurrentWI.IterationPath AS currentIteration
    ,PreviousWI.IterationPath AS previousIteration
    ,currentwi.system_changeddate
    ,CurrentWI.System_ChangedBy
    ,CurrentWI.System_Title
    ,(
        CASE
            WHEN CurrentWI.IterationPath = @iteration
                THEN 1
            ELSE 0
            END
        ) AS AddedToIteration
    ,(
        CASE
            WHEN PreviousWI.IterationPath = @iteration
                THEN 1
            ELSE 0
            END
        ) AS RemovedFromIteration
FROM CTE_WorkItemHistory CurrentWI
LEFT JOIN CTE_WorkItemHistory PreviousWI ON CurrentWI.System_id = PreviousWI.System_id AND CurrentWI.Recency - 1 = PreviousWI.Recency
WHERE (
        CurrentWI.IterationPath <> PreviousWI.IterationPath
        OR PreviousWI.IterationPath IS NULL
        )
    AND (
        CurrentWI.IterationPath = @iteration
        OR PreviousWI.IterationPath = @iteration
        )
    AND (CurrentWI.System_ChangedDate BETWEEN @startDate
         AND @endDate)
</code>```

Body:
Here is a script that I prepared that will look through the workitemhistory view to work out when an iteration changes on a date which is between the iteration start and end date.

It is a work in progress, but it demonstrates that the answer is there if you need it.

DECLARE @iteration VARCHAR(300)
DECLARE @startDate DATETIME
DECLARE @endDate DATETIME

SELECT @iteration = '\TeamProject\Team\Sprint 4';

SELECT @startDate = startdate, @endDate = finishDate
FROM DimIteration
WHERE iterationpath = @iteration;

WITH CTE_ALLWorkItemsInIteration
AS (
    SELECT DISTINCT system_id
    FROM WorkItemHistoryView
    WHERE IterationPath = @Iteration
    )
,CTE_WorkItemHistory
AS (
    SELECT *
        ,ROW_NUMBER() OVER (
            PARTITION BY System_Id ORDER BY [System_ChangedDate] ASC
            ) AS Recency
    FROM WorkItemHistoryView
    WHERE system_id IN (
            SELECT system_id
            FROM CTE_ALLWorkItemsInIteration
            )
    )
SELECT CurrentWI.System_id
    ,CurrentWI.System_WorkItemType
    ,CurrentWI.IterationPath AS currentIteration
    ,PreviousWI.IterationPath AS previousIteration
    ,currentwi.system_changeddate
    ,CurrentWI.System_ChangedBy
    ,CurrentWI.System_Title
    ,(
        CASE
            WHEN CurrentWI.IterationPath = @iteration
                THEN 1
            ELSE 0
            END
        ) AS AddedToIteration
    ,(
        CASE
            WHEN PreviousWI.IterationPath = @iteration
                THEN 1
            ELSE 0
            END
        ) AS RemovedFromIteration
FROM CTE_WorkItemHistory CurrentWI
LEFT JOIN CTE_WorkItemHistory PreviousWI ON CurrentWI.System_id = PreviousWI.System_id AND CurrentWI.Recency - 1 = PreviousWI.Recency
WHERE (
        CurrentWI.IterationPath <> PreviousWI.IterationPath
        OR PreviousWI.IterationPath IS NULL
        )
    AND (
        CurrentWI.IterationPath = @iteration
        OR PreviousWI.IterationPath = @iteration
        )
    AND (CurrentWI.System_ChangedDate BETWEEN @startDate
         AND @endDate)


答: When in Rome...or Redmond.  I switch back and forth between C# and Java in my job, and I use the convention of each language because, as mentioned earlier, it avoids issues when looking at other's code, or for others to read mine.</p>


问:
Am I planning my database/backend correctly?
I'm an iOS developer and to be honest I'm not really looking to become a database expert right at this moment, but I do need to know how to properly plan out what I believe to be a pretty cookie cutter social network style backend/database.

I'll keep this short and sweet:

Social network app will have users, posts, comments, and favorites.

Using comments as an example:

Each comment is an object that has been created in my backend for a class called "Comments" (Is this overkill? I don't see how else it could be achieved but I just can't believe how a server would handle so many individual comment objects if an app became popular, but maybe I'm just underestimating the power of a good backend?)

A comment object consists of a URL for the commenter's avatar, the commenter's user ID, a unique object ID, the post object's ID that the comment is for, and the comment text.

Posts and Favorites would also be their own classes/objects in the backend and would follow the same model as comments in the example above.

So my main question is, am I on track with the above? I want to make sure I'm structuring my backend properly.

My second question is, how should the user should keep track of all of their posts, comments, and favorites?

My initial idea was to just have array fields for the User class and store the ID's of the posts, comments, and favorites eg. User class has an array field called "Posts" with ID's of post objects.

The thing that confuses me is, is it overkill to keep track of these in the User class, when I'm storing the User's ID on the post, comment, and favorite classes already? And then I would just query those classes and filter for the user's ID, but then I think about it and if the app had a ton of usage, it might take longer to query all those objects and filter by the user's ID when the user could just keep track of their objects via fields on the User class.

Last but not least, last week I read the following in some Parse.com (popular Backend as a Service) docs:

"When you’re thinking about one-to-many relationships and whether to implement Pointers or Arrays, there are several factors to consider. First, how many objects are involved in this relationship? If the "many" side of the relationship could contain a very large number (greater than 100 or so) of objects, then you have to use Pointers."

I'm confused on what Pointers are in a backend?

I realize these are all pretty noob questions but I really want to make sure I setup my backend properly and make sure that it's structure makes sense.

Hopefully some of you guys will be willing to read this giant wall of text and help a brotha out.

Thanks for the help!

答:
A bit about relational databases

One of the most powerful features of relational databases is the ability to connect sets of data through common points. In order to do this efficiently, a database should follow the rules of normalization. To sum those rules up, a database should have:

No repeating elements or groups of elements

No partial dependencies on a concatenated key

No dependencies on non-key attributes

With these rules in mind, an example table for the comments could look like this:

```<code>----------------------------------------------------------------------
| comments                                                           |
|--------------------------------------------------------------------|
| comment_id (key, auto-increment) |  comment  | post_id |  user_id  |
|----------------------------------|-----------|---------|-----------|
| 1                                | <text...> |    1    |   123452  |
----------------------------------------------------------------------
</code>```

Here, the comment_id is the 'key,' or unique identifier, of the table. It's also been set to 'auto increment,' which means that it will automatically increase its value as 'records,' or rows, are added to the table. As shown, the table containing information related to comments only knows what it needs to know. How, then, do you relate user-specific information to a comment? This is where the 'relational' part of 'relational database' comes into play:

```<code>--------------------------------------------|
| users                                     |
|-------------------------------------------|--------------------------------|
| user_id (key, auto-increment) |   avatar  | additional fields not shown... |
|-------------------------------|-----------|--------------------------------|
| 123452                        | <img_url> |
---------------------------------------------
</code>```

Note that the user_id column contains the same data for both the comments table and the users table. This way, you can 'join' data from the two tables. For example, to get all of the comments made by a user, you could run the MySQL query:

```<code>SELECT comment_id, comment, post_id FROM comments NATURAL JOIN users WHERE user_id=123452;
</code>```

This method also answers the question

how should the user should keep track of all of their posts, comments, and favorites?

The user table should not keep track of such information in itself, but rather the respective tables should contain references to a globally unique user ID.

Almost there

So basically, you were on the right track. The only real change from the model you specified was to move the user's avatar information to the table concerning users, instead of in the table concerning comments.

As you seem to be leaning away from using a raw SQL database, you could consider the tables to be classes, and use the rules of normalization as a design guideline.

Finally, the Pointers vs. Arrays thing: both of those are very specific to the Parse backend (and admittedly, neither are explained very well). The best comparison I can come up with is that Pointers would be like Lists (as in Java or C#), and Arrays would be like, well, Arrays. The difference between the two is that Arrays can only store a predetermined amount of data, while Lists (or Pointers, in Parse's case) can store an unspecified amount. In theory, the amount would be infinite, but in practice the amount is determined by the amount of space available in the heap. For more information about the difference between Lists and Arrays, see this question. If you are planning to use Parse, I would recommend using Pointers in conjunction with Join Tables (which are essentially wrappers around the SQL method I described above), as those are the options offering the most flexibility.

Body:
A bit about relational databases

One of the most powerful features of relational databases is the ability to connect sets of data through common points. In order to do this efficiently, a database should follow the rules of normalization. To sum those rules up, a database should have:

No repeating elements or groups of elements

No partial dependencies on a concatenated key

No dependencies on non-key attributes

With these rules in mind, an example table for the comments could look like this:

----------------------------------------------------------------------
| comments                                                           |
|--------------------------------------------------------------------|
| comment_id (key, auto-increment) |  comment  | post_id |  user_id  |
|----------------------------------|-----------|---------|-----------|
| 1                                | <text...> |    1    |   123452  |
----------------------------------------------------------------------

Here, the comment_id is the 'key,' or unique identifier, of the table. It's also been set to 'auto increment,' which means that it will automatically increase its value as 'records,' or rows, are added to the table. As shown, the table containing information related to comments only knows what it needs to know. How, then, do you relate user-specific information to a comment? This is where the 'relational' part of 'relational database' comes into play:

--------------------------------------------|
| users                                     |
|-------------------------------------------|--------------------------------|
| user_id (key, auto-increment) |   avatar  | additional fields not shown... |
|-------------------------------|-----------|--------------------------------|
| 123452                        | <img_url> |
---------------------------------------------

Note that the user_id column contains the same data for both the comments table and the users table. This way, you can 'join' data from the two tables. For example, to get all of the comments made by a user, you could run the MySQL query:

SELECT comment_id, comment, post_id FROM comments NATURAL JOIN users WHERE user_id=123452;

This method also answers the question

how should the user should keep track of all of their posts, comments, and favorites?

The user table should not keep track of such information in itself, but rather the respective tables should contain references to a globally unique user ID.

Almost there

So basically, you were on the right track. The only real change from the model you specified was to move the user's avatar information to the table concerning users, instead of in the table concerning comments.

As you seem to be leaning away from using a raw SQL database, you could consider the tables to be classes, and use the rules of normalization as a design guideline.

Finally, the Pointers vs. Arrays thing: both of those are very specific to the Parse backend (and admittedly, neither are explained very well). The best comparison I can come up with is that Pointers would be like Lists (as in Java or C#), and Arrays would be like, well, Arrays. The difference between the two is that Arrays can only store a predetermined amount of data, while Lists (or Pointers, in Parse's case) can store an unspecified amount. In theory, the amount would be infinite, but in practice the amount is determined by the amount of space available in the heap. For more information about the difference between Lists and Arrays, see this question. If you are planning to use Parse, I would recommend using Pointers in conjunction with Join Tables (which are essentially wrappers around the SQL method I described above), as those are the options offering the most flexibility.


答:
It may take you longer to write code complete with unit tests. In fact it probably will. What makes it a more productive way of working for the organisation as a whole is all the things that don't happen further down the line, and in particular don't happen to other people, when you have your code armed with a full battery of tests. Fewer manual testers required to achieve the same level of quality. Fewer expensive emergency support calls. Fewer customers who quietly slink off to a competitor without alerting you to bugs. Less time spent bringing a new colleague up to speed, because your test code documents what the production code should be doing. Less time spent mending damage caused by a substandard new colleague.

This view of productivity is hard to measure, though, which is why management and programmers often instinctively revert to measuring the time taken to go from blank screen to something that mostly works, most of the time.

Title: Why are my unit tests so expensive?


问:
Turn over cards in minimum number of steps
Imagine you're given an array of cards. Some of them are facing down (0), while some of them are facing up (1). Is it possible for given fixed K to turn all the cards face-up by turning over any K consecutive cards? If it's possible what's the minimum number of steps?

For example:

```<code>N=6; K=3;
1 0 0 1 0 0
</code>```

It is possible to make all the cards facing up, by first turning over cards 2-3-4 and then turning over cards 4-5-6. And the minimum number of steps is 2.

My idea was to iterate through the sequence and when I'll find a 0 then I flip the next K cards (if it's possible), including the 0. But it seems that this idea doesn't work always. For example:

```<code>N=56; K=5
0 0 1 0 0 1 1 1 0 0 0 1 0 0 1 0 0 1 0 1 0 0 0 1 0 1 1 1 0 1 0 0 1 1 0 0 1 1 1 1 1 1 1 0 0 1 0 1 0 0 0 1 0 1 0 0
</code>```

is one counter-example. Since after I perform the above-mentioned algorithm I end up with all the cards faced up, except for the last one.

This is a contest problem, so one of the test cases is:

```<code>1000 25
0 0 1 0 0 1 0 0 1 1 1 1 1 1 0 1 0 0 1 0 1 0 1 1 0 0 0 0 1 0 0 0 0 1 0 1 0 1 0 0 1 0 1 0 0 0 1 1 0 1 1 1 0 0 0 0 1 0 1 0 1 0 1 0 1 1 1 0 0 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 1 0 1 1 1 0 0 0 1 1 1 1 0 0 0 1 0 0 0 0 1 1 1 0 0 0 1 0 0 1 1 0 1 1 0 0 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 1 0 1 0 1 1 0 1 1 0 1 1 0 0 1 0 1 0 1 0 0 0 1 0 0 1 0 0 1 0 0 0 1 0 1 1 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 1 1 1 0 1 0 1 1 1 0 0 1 0 0 1 1 1 1 1 1 0 1 1 0 1 0 0 1 1 1 0 0 0 0 0 1 1 1 0 1 0 1 0 0 1 1 1 0 0 0 0 1 1 1 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 0 1 1 0 1 1 1 1 0 1 0 1 1 0 1 0 0 1 1 1 1 0 0 1 0 1 0 0 0 1 0 0 1 0 1 0 0 1 0 0 1 1 0 1 1 1 0 0 1 0 0 0 0 0 0 1 0 1 1 1 1 1 1 1 0 0 1 0 0 1 1 1 1 1 0 1 0 1 0 0 1 1 0 1 1 1 0 1 1 1 1 0 0 0 1 1 1 0 1 1 0 0 0 0 1 1 0 0 1 1 1 0 0 0 1 0 0 0 0 1 0 1 0 1 1 0 0 1 1 0 1 0 0 1 0 1 1 0 0 1 0 0 1 0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1 0 1 1 0 1 1 0 1 0 1 0 0 0 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 0 0 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 1 0 0 1 0 1 1 0 1 1 0 0 1 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 1 1 1 1 1 1 0 1 0 1 1 1 0 0 0 1 1 0 0 1 1 1 0 1 0 0 1 1 1 1 0 1 1 0 0 1 1 1 0 1 1 0 1 1 1 0 1 0 1 0 0 1 1 0 1 1 0 0 0 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 0 1 0 1 0 1 0 1 1 0 0 0 1 1 0 0 1 0 1 0 1 0 0 0 1 1 1 0 1 0 1 0 1 0 1 1 1 0 0 1 1 1 0 1 0 0 0 0 0 1 1 0 1 0 1 0 0 0 0 0 0 0 1 1 0 0 1 1 1 1 1 0 0 1 0 0 0 0 0 0 1 0 1 0 1 1 0 0 0 0 0 0 1 1 1 0 0 1 1 0 0 0 1 0 1 1 0 1 0 1 1 0 1 0 0 0 0 1 1 0 0 1 1 1 0 1 0 1 0 0 1 1 1 0 1 1 0 0 0 1 1 0 1 0 0 1 0 0 1 0 1 1 1 0 0 1 0 1 0 0 0 0 1 1 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 1 0 1 0 1 1 0 1 0 1 1 1 0 0 1 0 0 0 1 0 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 0 0 1 1 0 1 1 0 1 0 0 0 1 1 1 0 1 0 0 0 1 0 1 0 1 1 1 0 0 1 1 1 0 1 0 0 0 0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 1 1 1 1 0 1 1 1 1 1 0 0 1 1 1 0 1 0 0 1 0 1 0 0 0 1 1 1 1 0 1 1 1 0 0 1 0 0 1 1 0 0 0 1 0 0 0
</code>```

The supposed right answer is 441, while my algorithm says is 443.

答:
First, there is high possibility that combination of parameters and starting cards might be unsolvable. For example

```<code>N=3; K=2
1 0 1
</code>```

Is unsolvable.

Your algorithm doesn't find minimum number of steps, because your example configuration cannot be solved at all.

Now the question is whenever given algorithm does indeed guarantee that it can always find solution if it exists. I don't have rigid proof, but I do believe yes.

The reason for my belief are the edge cards. The moment the edge cards become 1, you cannot apply "flip" function on them and K-1 area next to them. If you did, you would have to apply it again, completely reverting previous flip. They are invariant to flip function. So if you manage to flip an edge card to be 1, you can ignore it, remove it from the list of cards and continue with reduced list. If there is 0 on the edge, you flip it along with K-1 other cards, which gives you 1 which you can then ignore. You are doing exactly that with your algorithm. At end of this algorithm, you end up with list of cards whose length is EndN <= K.

Given that, figuring out whenever the configuration is solvable is easy. The configuration is only solvable if EndN = K and if remaining cards are either up or down.

Body:
First, there is high possibility that combination of parameters and starting cards might be unsolvable. For example

N=3; K=2
1 0 1

Is unsolvable.

Your algorithm doesn't find minimum number of steps, because your example configuration cannot be solved at all.

Now the question is whenever given algorithm does indeed guarantee that it can always find solution if it exists. I don't have rigid proof, but I do believe yes.

The reason for my belief are the edge cards. The moment the edge cards become 1, you cannot apply "flip" function on them and K-1 area next to them. If you did, you would have to apply it again, completely reverting previous flip. They are invariant to flip function. So if you manage to flip an edge card to be 1, you can ignore it, remove it from the list of cards and continue with reduced list. If there is 0 on the edge, you flip it along with K-1 other cards, which gives you 1 which you can then ignore. You are doing exactly that with your algorithm. At end of this algorithm, you end up with list of cards whose length is EndN <= K.

Given that, figuring out whenever the configuration is solvable is easy. The configuration is only solvable if EndN = K and if remaining cards are either up or down.


问:
Which events to store with event-sourcing?
I'm planning out the events that my application will be creating, but am running into problems with my design.  I believe I'm not applying the event-sourcing concepts correctly.

Take the bank account example.  My application receives a command to deposit cash, accepts it, and then creates the event CashDeposited.  Based on the business logic, the higher account balance triggers the interest rate to be increased, so I create the event InterestRateChanged.

Now if I record both of these events to my event store, upon restart, both events will be replayed.  But because the CashDeposited event triggers the InterestRateChanged event, won't the InterestRateChanged be replayed twice: once from the event store and once as a result of CashDeposited being replayed?

答:
You have two choices

Only store trigger/first/external events in the event store
In this case your "CashDeposited" event. So when you replay the
this all the subsequent events will be triggered as per normal processing.

Store all events but check an "isReplay" flag before triggering a subsequent event.

I like the first option best. If you are replaying because an error occurred (say you set the threshold for an increase in interest rate too low) then the system will replay correctly with the fixed parameter.
Plus you really don't want to complicate your code and testing with all those extra paths for "isReplay".


问:
Incrementing version - During development? or after release?
I have what I believe is a largely subjective question, but I'm interested in how people handle the situation described below. There are many similar questions on programmer stack exchange but none which touch on this precise issue of whether to update a version number to the proposed release before or after the development (that I could find).

I have a system which is live, lets call it version 1.0.x.x I'm using Major.Minor.Build.Revision Microsoft style versioning.

I get a customer request for some new features, and we decide that this package of work will be the 1.1.x.x release.

When would you update your version number, in development? As you begin work? or as you finish it?

I can see two approaches, neither of which I'm 100% happy with.

Increment the minor version as the development starts, leading to the eventual released software being probably something like 1.1.5562.12589

Keep the version at 1.0.x.x during development, leading to the tested version being something like 1.0.5562.12589 and then when I need to update the version of the assembly (which we'd do manually for a major or minor release) to 1.1.x.x strictly speaking that version of the code (as I'd have to had rebuilt it to increment the assembly number) hasn't been tested.

What's the preferred approach here?

EDIT:

In terms of pros and cons:

Option 1.

Pros - The version which is released is already 1.1.x.x so the minor number is accurate, and that build/revision represent tested code

Cons - The released version won't be version 1.1.0.0 which to the customer or developer, may look like work has been done post a 1.1.0.0 release, such as bug fixes.

Option 2.

Pros - The version doesn't reach 1.1.0.0 until the development is complete & tested. Meaning there is a clean logical cutoff between work being made on the stable 1.0.x.x version and the deployment of the tested 1.1.0.0 version.

Cons - The version has to be manually adjusted from 1.0.x.x to 1.1.0.0 somewhere after testing but before release. Potentially including untested code if someone has mistakenly checked in the wrong area.

At the moment I'm not sure which is the lesser of two evils as I can see pros to both, as well as cons to both. I'm hoping someone might help me tip the balance or spot something I've missed.

答:
If your issue is that the customer might think 1.1.2475.54387 means "something has changed after 1.1" - forget it. In my experience, virtually all customers either don't care what the lower-order components in a version mean, or they do care and understand that they are build numbers and VC revisions, which by definition can never be 0.

Slightly more general: Looking good is a valid goal, but in a business context it only matters what the person who makes the purchase decision thinks. Those people almost always fall squarely into category (a) above. I can think of no scenario where having a non-pristine build number would negatively affect the business success of a product.


答:
The type of unit testing you need to do to find bugs in existing mostly-working code is very different from the type used as a scaffold while creating or modifying the code. Only the latter is TDD/BDD. And, as it is somewhat newer, it tends to be the one that gets discussed in articles and blogs. Sometimes to the point where people get the impression that it's 'what you need to do', as opposed to 'what you need to do in order to...'.

The underlying justification for TDD, as opposed to other design approaches, is that some of the design scaffolding sticks around and becomes useful tests. Whether or not you buy into that, erecting scaffolding after you have finished development is pretty much never going to be useful.

Some tools, like JUnit and mockito, are common to both approaches (although over-use of mocks will quickly lead to tests that are worthless as anything other than scaffolding). Others tools, like quickcheck and tcases are worthless as scaffolding, and excellent at bugfinding.

Whether or not you use unit testing during TDD, any unit testing you do after the code is complete should be oriented towards bug-finding. Depending on the reliabaility/cost tradeoffs involved, it is sometimes perfectly rational to selectively replace scaffolding tests created during development with bugfinding tests.

Title: Why are my unit tests so expensive?


答:
One big advantage of option 1 is that as soon as your software passes all the unit tests and acceptance tests against the new set of requirements, you can ship it.

If you delay incrementing the version number, then you will have to do another build with the correct version you want to ship.  Having re-built it all, you really should re-do all the tests again.

Title: Incrementing version - During development? or after release?

Body:
I have what I believe is a largely subjective question, but I'm interested in how people handle the situation described below. There are many similar questions on programmer stack exchange but none which touch on this precise issue of whether to update a version number to the proposed release before or after the development (that I could find).

I have a system which is live, lets call it version 1.0.x.x I'm using Major.Minor.Build.Revision Microsoft style versioning.

I get a customer request for some new features, and we decide that this package of work will be the 1.1.x.x release.

When would you update your version number, in development? As you begin work? or as you finish it?

I can see two approaches, neither of which I'm 100% happy with.

Increment the minor version as the development starts, leading to the eventual released software being probably something like 1.1.5562.12589

Keep the version at 1.0.x.x during development, leading to the tested version being something like 1.0.5562.12589 and then when I need to update the version of the assembly (which we'd do manually for a major or minor release) to 1.1.x.x strictly speaking that version of the code (as I'd have to had rebuilt it to increment the assembly number) hasn't been tested.

What's the preferred approach here?

EDIT:

In terms of pros and cons:

Option 1.

Pros - The version which is released is already 1.1.x.x so the minor number is accurate, and that build/revision represent tested code

Cons - The released version won't be version 1.1.0.0 which to the customer or developer, may look like work has been done post a 1.1.0.0 release, such as bug fixes.

Option 2.

Pros - The version doesn't reach 1.1.0.0 until the development is complete & tested. Meaning there is a clean logical cutoff between work being made on the stable 1.0.x.x version and the deployment of the tested 1.1.0.0 version.

Cons - The version has to be manually adjusted from 1.0.x.x to 1.1.0.0 somewhere after testing but before release. Potentially including untested code if someone has mistakenly checked in the wrong area.

At the moment I'm not sure which is the lesser of two evils as I can see pros to both, as well as cons to both. I'm hoping someone might help me tip the balance or spot something I've missed.


问:
Creating an auto-patching system for Spring Hibernate Application
I have this question for few months now.

We have a web application which has monthly changes and weekly bug fixes if any.

Usually we just build the new war, undeploy the old ones and redeploy new ones, and restart server if necessary.

I want to build a patching system which can create a patch which can easily be applied for the current war itself.

I googled a lot but didn't find any.

My doubts are:

Is it okay to create such an application ? (Specifically for this WAR application)

Which language to use ? (I was thinking of Go or JAVA but open to suggestions.

Please point me any documentations of blogs.
Thanks in advance :)

答:
Yes. It is possible to patch a JAR file using jar -u. It is also possible to patch a WAR file the same way.

But I would NOT recommend it. The JAR or WAR file should be the unit of deployment / management. If you start patching JAR / WAR files on production servers, it is hard to track what is actually being used where. If you are not careful, chaos and confusion will reign.

The only situation where patching is unavoidable is where you have a 3rd-party library or something that you can't build from source, but you need to modify nevertheless. But even in that case it is best to modify the JAR / WAR on your build platform and deploy the modified JAR / WAR. Trying to patch JARs, WARs or deployed webapps on the production platform is a bad idea.


问:
Does Microsoft still have C++ container limitations when passing to DLLs?
Microsoft has had a fair amount of trouble in the past when passing STL containers like string and vector pointers and references to DLLs. See, for example, You may experience an access violation when you access an STL object through a pointer or reference in a different DLL or EXE.

Question: Are those types of problems still present today in Visual Studio 2010 and 2013?

I know the question is a bit open-ended. I am asking because I've experienced them in the past, I'm working on a new design, the design could include a plugin architecture, and I would like to to pass a string or vector reference to a plugin DLL. If the problems still plague Microsoft, then I have to change the design (or come up with a workaround to avoid the crash).

Related, Did C++11 address concerns passing std lib objects between dynamic/shared library boundaries? is similar (thanks for the link). But it does not really answer the question, though it does seem to acknowledge the same problem.

Also, Microsoft's KB Q168958, How to export an instantiation of a Standard Template Library (STL) class and a class that contains a data member that is an STL object, implies it can be done. But that's around the time I recall having the problems, so I am curious if it still applies (and if it actually works now in Visual Studio 2010 or 2013).

The problem I am running into was highlighted by Robert and Doc: I can test for the presence of bugs, but not the absence of them. So I might not be able to trigger problems during testing, but the problems may really exists (and surface at the worse time).

答:
Export a C interface.

Not only does that solve the DLL problem, but it allows for plugins in languages other than C++.

Then write a C++ wrapper for the C API as a header only library.

You can't use C++ non-standard-layout objects in the API because there is no standard ABI for them, so you would be requiring the library and users to all be compiled with the same compiler and libraries.  This is particularly bad for plugins -- it is less of an issue for libraries as the library user can statically link the library with the executable, or at least bundle the two in a single installer.

Note that a non-POD object can still be standard layout, starting with C++11.


问:
Large Scale Application Development in Android
Since, I am fairly new to large scale app development in Android and Java, I thought I would ask for advice.

My team is faced with developing a prototype of a fairly complex medical software. Although it is only a prototype, I think it might be a good opportunity to learn a new platform and get into some good habits.

Our design requirements are fairly simple: a set of common files: themes, styles, objects, static methods for database etc. and then a set of smaller "apps" like: digital tests, games etc. Each one is fairly unique.

Our initial thought is to create a set of smaller applications that will be launched from "the main screen". Each application would be a separate project in Eclipse and then we would modify the build path to include the "common files". This way: each developer can work on their own projects without bothering others.

The problems that I find with this approach:

Deploying the application (having a bunch of applications instead of one big one)

Testing the application

Use of strings to launch another application i.e. worrying whether the application has been installed

Silly human errors e.g. modifying common files and forgetting to commit changes

Another solution would be to create one big application/project with each developer working on a separate package which would represent each app. However, this introduces common resources (e.g. unique string names) etc.

What's your advice about the best way to tackle this problem? Which approach is better in the long run? Are there any other approaches that are more sensible?

答:
If the apps are distinct in terms of data, and purpose, I think modularizing them - making a number of smaller, separate pieces is better. If they do not share data, and if they do not have strong coupling in terms of how the user uses them, I would strive to keep them separate and small.

It all depends on the coupling between the fairly unique apps. If each is isolated and not dependent on lots of other things, it will be easier to test at a higher level. It will be easier to isolate bugs. Easier to upgrade.

You can use package manager functionality (e.g. queryIntentActivities) to find and help launch the other activities to get around problems of launching other apps.

The problems of forgetting to commit changes and other problems of that nature aren't coding or system design issues, those are practices and process problems.


问:
How to approach refactoring an existing web application?
I've been reading and thinking a lot lately, and I've come to the conclusion that I maybe I should rethink my web development strategy. I'm doing a lot of on-the-fly programming, and in the 2 years I've been working on a PHP web application, what might have begun as a little tool became quite the big project. But there is a ton of legacy code from me and my predecessor, snippet of code that might have make sense at the time, but now I'm questioning the usefulness of said code in the form it is actually. Furthermore so such things like unit testing and Test-Driven Development wasn't in my scope until quite recently.

So how would you approach refactoring the web application? What would be the things I should look for and in which order? What about browser game versus functional web app? Would there be then difference in the approach?

答:
Before doing anything, it is best to have your project in source control. This way, you can rollback changes, or work on major changes on a seperate branch, as well as tag milestones.

Next, write tests for any code you plan to change. You don't need to go all out all at once, writing tests for everything. Just what you plan to be immediately working on. The theory goes that given enough time, most of the code base will be covered by tests. Note that some refactorings are "safe" to do without tests - these are documented in the Legacy Code book mentioned earlier, and doubtless elsewhere.

With tests in place for a section of code, change the code. Do whatever you need to, as long as the tests still pass.

Even with legacy code, you can do TDD if making additions or changes. Just write tests first for your anticipated changes, see them fail, and then make the changes.

Some tools may be useful here. NDepend can point out highly coupled code and other smells. NCover tracks your code coverage levels. FxCop is essentially a code correctness checker, beyond what the compiler does. These are all useful tools to have handy for a project of any real size, especially the legacy variety.

Ultimately, it's a multi-step process. Don't try to do it all at once, just take it a bit at a time.


答:
Yes, it is quite possible, and I have done such myself.

The situation I was in was deployment of a large .war file. The web application part of it was not that big - but it also contained within it a Java Web Start application. The combined size of all of this was a few hundred megabytes. This posed a problem for deployment - when pushing all of this down the pipe to all the sites that needed it (about 300), we could thoroughly saturate the network all night which meant that other updates were not happening (that was a bad thing).

The solution to this was two part. First, we did an exploded deployment of all code we used (third party .jars were still a .jar). Secondly, as part of our CI server we had a special build script that could take two builds identify the delta of the class files and other resources (whole file delta, not sub file patches) and then with that, it would build the deployment package (a .tar file and shell script that stopped the server, deployed itself, and restarted the server - the JWS then did its own deployment when the clients started up) that would patch a production environment from one build to another.

A thing to take away from all this is that there were several constraints here - a very large application and network utilization. This made an incremental deployment necessary.

For a situation where you have a few servers, I would be looking at another approach.

First off, version the .war file. You don't deploy "FooApp", you deploy "FooApp_1_0_1".  This also means you have both "FooApp_1_0_0" and "FooApp_1_0_1" on the server at the same time.

Secondly, you have the forward proxy or load balancer have its configuration point "FooApp" to "FooApp_1_0_0" and then switch that configuration when you want to flip the switch. This would typically be done after you have verified that the new deployment is completely working.

The deployment can be done via your CI server (and if you don't have one running, that would be a good thing to work on).  Jenkins has deployment plugins for all the major EE servers.  Maven also has deployment plugins - I am sure gradle and ant do too.  You could also write your own using JMX for some app servers. If you really wanted, you could probably write another app that runs on the app server to deploy the other app. I would be hesitant to have an app update itself in running code. That just sounds like a nightmare if something breaks part way through.

The biggest advantages with versioned deployment and a load balancer / forward proxy switch over is that you can do this deployment with zero down time and verify the deployment before it goes live.  At no time are you updating running code or even restarting the application server as part of this. The switch for which code to run is another system entirely.  This situation also allows for instant rollbacks and special client switching ("you have been selected to try our new look and feel, click this to go to the new version of the application and provide feedback").

Title: Creating an auto-patching system for Spring Hibernate Application

Body:
I have this question for few months now.

We have a web application which has monthly changes and weekly bug fixes if any.

Usually we just build the new war, undeploy the old ones and redeploy new ones, and restart server if necessary.

I want to build a patching system which can create a patch which can easily be applied for the current war itself.

I googled a lot but didn't find any.

My doubts are:

Is it okay to create such an application ? (Specifically for this WAR application)

Which language to use ? (I was thinking of Go or JAVA but open to suggestions.

Please point me any documentations of blogs.
Thanks in advance :)


问:
Many small requests vs. few large requests (API Design)
I'm currently working on a project with an organization as follows:

Client - Gets data from the main server via REST api.

Server - Requests data from various other servers via third-party APIs

Third-party APIs - Services out of my control that provide data to the server (Reddit, Hackernews, Quora, etc.)

For the sake of argument, let's say the client first needs a list of items from each of the third-party APIs. From this list, an item will be chosen at which point the client needs to see the full content of the item as well as responses (i.e. comments) to the item. I'm trying to decide between three options:

A la Carte

In this approach, I would have 3 separate endpoints on my server: one to get the list of items, one to get the main content for an item, and one to get the responses of the item.

Pros: I never make more requests than I need to, requests should be small so generally they should be faster.

Cons: I have to make a lot of requests. After choosing an item from the list, the user may have to wait before seeing the main content and then wait even longer to see the responses

Server-side cache

In this request, I would make a single call to my server to "fetch" all the data for all sources. The data would then be cached on the server. The client would then have the same REST endpoints as before, except there wouldn't be much waiting between calls since my server already has the data and just has to feed it to the client.

Pros: Still easy to implement on the client side, but without the latency issues

Cons: A bit more involved server side, and the first call could take really really long.

Client-side cache

This scenario is similar to the previous one except the client only ever makes one request to the server: give me all of the data. From here it's the client's responsibility to save the data and use it appropriately.

Pros: Easy server implementation, very speedy after the first call

Cons: First call will be very slow, more complicated client-side implementation

I'm not sure which is the best approach, or if maybe I'm missing the obvious solution. Any advice would be greatly appreciated!

答:
One thing to keep in mind is the expected network latency (i.e. ping time) between your clients and your server.  In a high-latency situation with otherwise good bandwidth, many small requests will perform significantly worse than one large one.

I've recently been collaborating on a multi-team database-backed web application project in which one of the teams is in India (the rest are in the US). We have a single database instance hosted in our US office to which developers connect our local webserver instances. My desk is maybe fifty feet and two LAN hops away from the database instance, and performance is fine.

When we first got things started with the developers in India, they were experiencing enormous wait times starting up the application and navigating page-to-page.  We're talking ten minute wait times here. It turns out that this was because the ~200ms ping time from their desks to our dev database server was getting multiplied by many, many brief queries to the database.  My local 0.5ms ping was so trivial that the chattiness between webserver and database server never mattered.  This was the first time that we had geographic separation between webserver and database server.

The solution in our case was to clone the database server and stand the copy up in India, but the point here is to keep in mind that if your client and server are far apart, network latency will be multiplied by the number of communications across the wire.  Bandwidth once the connection is established is typically much less of a concern.


问:
Secure Rest api from authenticated user
Let's say that my Rest api is secured using OAuth 2. Let's say my client is a mobile App. Let's say that i have an Api call:

```<code>@Post /increasePoints host:https://www.example.com/increasePoints  amout=10
</code>```

Now Using this api call, one should have a valid Access Token. from my app i have control when to call this function so there is no problem. but Let's say the authenticated user get a hold of the access token. how can i stop him from posting to this api using his access token?

Few options that i thought of:

sign each call with a special header.

use client_authentication with scope points - i've just read about this type of authentication but the user can get the access token with same ease for what i understand.

答:
You simply don't give the user access to that API. For example, we have several web apps which uses access tokens and bill the user for certain actions. The billing system is centralised, and there's an app used by our customer services to add credits to the bills.

But there's no reason why the access token the end user gets to perform the actions on the app they are using should give access to the billing system, as that would mean they could add credits whenever they liked. The user's id is checked against a database of actions they can perform, and trying to add credits isn't one that's allowed. It seems you're in a similar situation, but haven't separated administrator actions from the end user's actions.

e.g. if you checkout in a online shop, then the action exposed is to checkout. There aren't separate 'send these items to me' and 'charge my paypal' in the api, though both happen on the server; the user can't do one without the other. The actions are located in the user's frame of reference.

Don't rely on your app to be the gatekeeper and increase points. Implement whatever action the user does to increase the points on the server instead, and it doesn't have to expose the sensitive action in the API. If you have some reason to expose the action for admin use then check that the user the token belongs to is an admin.

Title: Secure Rest api from authenticated user


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Something like this

```<code>x.y.z.a[b].c
</code>```

This smells like bio-hazard. This much member referencing is never ever a good sign.And yes this is a typical expression in the code I am working with.

Body:
Something like this

x.y.z.a[b].c

This smells like bio-hazard. This much member referencing is never ever a good sign.And yes this is a typical expression in the code I am working with.


问:
Samba/git Workflow too complicated
I'm a lead developer for a small company and I've recently came across a way to implement version control (git) on our workflow because the company is growing. In terms of infrastructure we have a couple of "production" servers, a development(accessible over the internet) server and an internal development server with internet access but blocked by a hardware firewall. Our current workflow consists of:

init a repo inside the production server with the proper .gitignore for that project and do the initial commit

push that commit to a bare repo inside the development server

clone the repo from the development server to the internal development server

make a network share on samba on the internal developlemt server so other network computers (we are all running windows) can connect to it.

I know for sure that this is a bit too complicated, but we want to try out git and make the workflow as easy as possible.

I've been reading about git-flow and stuff but so far I've been unable to get the workflow just right, I think that having the two development servers adds some redundancy.

Can someone share any tips on how to improve this workflow?

答:
While I have not used this method in production I have been looking at using git to deploy code to our prod server.  The basics is that you set up a bare git repo on any server you want to deploy to and then add that as a remote to another repository.  When you are ready to deploy you just push your code to the remote repository.  From my research I am looking at setting up a git repository on a server for developers to push to and then using git hooks on master and develop to push to my prod and dev servers (based on the branch).

The key to understand is that the "Basic" workflows for git are more targeted to developers than to deployment since git is primarily an SCM system.

The process I am working on uses a central git server with a post-receive hook to push to remotes on each dev or prod server.  Then on the prod server I use a post-receive hook to checkout the newest code into the proper directory.

For more information and some detailed directions https://www.digitalocean.com/community/tutorials/how-to-use-git-hooks-to-automate-development-and-deployment-tasks has been rather helpful for setting up the dev and prod servers as well as good information on post-receive hooks (which are simple bash scripts executed after a push is complete).

EDIT:  Expansion for the comments.  In the above I am not pushing from the dev server to production.  I have a central git server that all my developers push to.  On that git server I have a git hook to push to my dev servers (remotes set up only on the central server) when a push to my development branch is made and production servers when a push to master (production branch) is made.

For development we use the git-flow workflow and all devs have a local (on their development machine) instance of the web server software we use.  Any changes they make are only on their feature branches and are not merged and pushed to develop (our development branch) until the change is complete.  Initial testing is done on their local machine to ensure the code is ready and then depending on the change on the code reviewers machine after a test merge with develop (make a new branch from develop and merge the feature branch in.  If there are no issues then merge the new integration branch into develop and push to the server)

Title: Samba/git Workflow too complicated


问:
Should one use Dependency Injection even if the class is used only once?
During a code review I have started having a bit of a dilemma as to whether use dependency injection or not. I would like to hear your thoughts, because this is kind of an ongoing theme and would help in the future code reviews as well.

Before I start I want to say that from my knowledge DI is mostly used for dependency management and better, much easier unit testing (correct me if I am wrong please).

Now here is the scenario:

This is the class that will be used as a dependency only once and probably for good. Meaning it will stay that way for a while and no other class will be using it.

Reason being is because it is a refactoring of some legacy code and there was not much to be done but to separate it into another class, at least as a first good step, for following the SRP.

Also, another thing is that the hypothetical doSomethingImportant() hits the database.

```<code>public SomeClass
{
   public Object doSomethingImportant()
   {
      ...
   }
}
</code>```

Based on that information do you think it is okay to new up the dependency in the other class as opposed to using DI since:

Dependency management argument kind of falls off since it is only going to be used once.

&

Unit testing also falls off since I would rather do an integration or acceptance test to see how the method is interacting with the database in a real-life application.

```<code>public SomeOtherClass
{
   private readonly SomeClass _someClass = new SomeClass();

   public Object doSomethingImportantUsingDependency()
   {
      ...
   }
}
</code>```

I was personally inclined towards doing DI because it is considered good practice, but for a second there it felt like I was blindingly following the rules and not thinking it over since there are always exceptions to the rule.

What are your thoughts on this? I would love to hear.

PS: I don't think this is a generic "when should I use DI" question because it is very specific to this particular situation when unit tests are of no use and the class is going to be used only once so there is no need to centralize it for dependency management (even though it is good practice in general).

答:
In C# it is trivial to provide optional dependency injection without coupling yourself to your dependency too tightly:

```<code>public class SomeOtherClass {
    private readonly ISomeClass _someClass;

    public SomeOtherClass(ISomeClass dependency = null) {
        _someClass = dependency ?? new SomeClass();
    }
}
</code>```

(or you can make the constructors explicit if your company dislikes default params)

In my experience, "oh we'll never need another one" is naive. Business changes. Technology changes. Make dependencies flexible.

And this sort of thing strikes the right balance between usability (yes, you'll almost always use the common/default one) and flexibility (but the ctor is there if you need it) - all with a nice simple line of code, while also providing some semblance of error correcting robustness. It's so trivial and clearly beneficial, there's no reason not to do it for the simple/straight-forward case.

Body:
In C# it is trivial to provide optional dependency injection without coupling yourself to your dependency too tightly:

public class SomeOtherClass {
    private readonly ISomeClass _someClass;

    public SomeOtherClass(ISomeClass dependency = null) {
        _someClass = dependency ?? new SomeClass();
    }
}

(or you can make the constructors explicit if your company dislikes default params)

In my experience, "oh we'll never need another one" is naive. Business changes. Technology changes. Make dependencies flexible.

And this sort of thing strikes the right balance between usability (yes, you'll almost always use the common/default one) and flexibility (but the ctor is there if you need it) - all with a nice simple line of code, while also providing some semblance of error correcting robustness. It's so trivial and clearly beneficial, there's no reason not to do it for the simple/straight-forward case.


答:
The answer like most things is "it depends".

If you want to unit-test the functionality in doSomethingImportantUsingDependency, then you will need to be able to inject the dependency.

However, if all that doSomethingImportantUsingDependency does is some property mapping from the result of your database call, then it would be pragmatic to not bother.

If some other class depends on SomeOtherClass then you can always inject that class instead.

Title: Should one use Dependency Injection even if the class is used only once?

Body:
During a code review I have started having a bit of a dilemma as to whether use dependency injection or not. I would like to hear your thoughts, because this is kind of an ongoing theme and would help in the future code reviews as well.

Before I start I want to say that from my knowledge DI is mostly used for dependency management and better, much easier unit testing (correct me if I am wrong please).

Now here is the scenario:

This is the class that will be used as a dependency only once and probably for good. Meaning it will stay that way for a while and no other class will be using it.

Reason being is because it is a refactoring of some legacy code and there was not much to be done but to separate it into another class, at least as a first good step, for following the SRP.

Also, another thing is that the hypothetical doSomethingImportant() hits the database.

```<code>public SomeClass
{
   public Object doSomethingImportant()
   {
      ...
   }
}
</code>```

Based on that information do you think it is okay to new up the dependency in the other class as opposed to using DI since:

Dependency management argument kind of falls off since it is only going to be used once.

&

Unit testing also falls off since I would rather do an integration or acceptance test to see how the method is interacting with the database in a real-life application.

```<code>public SomeOtherClass
{
   private readonly SomeClass _someClass = new SomeClass();

   public Object doSomethingImportantUsingDependency()
   {
      ...
   }
}
</code>```

I was personally inclined towards doing DI because it is considered good practice, but for a second there it felt like I was blindingly following the rules and not thinking it over since there are always exceptions to the rule.

What are your thoughts on this? I would love to hear.

PS: I don't think this is a generic "when should I use DI" question because it is very specific to this particular situation when unit tests are of no use and the class is going to be used only once so there is no need to centralize it for dependency management (even though it is good practice in general).


答:
There's a development principle along the lines of DRY and SOLID called YAGNI that is designed to help streamline your development efforts in getting things done and not getting paralysed with indecision over what to do.

If you later find that you need to enhance your class, then you will. YAGNI says not to worry so much over it now 'cos you probably won't need to spend that extra effort. Get it done, come back to it if you really need to.

Some say its the opposite of SOLID but really its all about trading off all the factors involved in development, you don't have infinite time or resources (and 'perfect' code never is IMHO).

So here, you say it doesn't need DI complexity... so there's your answer. Don't put it in. Move on to all the other things you have to do.