问:
Has there been recent research on Fred Brooks's model of the "Surgical Software Team"?
I'm reading through The Mythical Man Month for the first time. In it, Fred Brooks* proposes a model of software development based on how a surgical team works. There is a "surgeon" (a senior developer) who does almost all the design and implementation work, a "copilot" who discusses these ideas with the surgeon and occasionally does some minor coding, a "toolsmith" (dev ops), a language expert, and some other administrative workers.

I can't but help be struck by the fact that, despite the great fame of The Mythical Man Month, I have never seen or even heard of an office that actually operates on that model. This is despite the meteoric rise of the tech industry and the cult of the "rockstar programmer" that fashionable among startups today.

And so I was wondering if this is because the surgical model has become obsolete in any way. After all, we now have advances like version control (making one of his administrative roles obsolete), optimizing compilers (possibly making the language expert obsolete), and agile development (which may not make anything obsolete, but seems substantially different from the waterfall method that people used in those days).

The question, then: Has there been any research on the efficacy of Brooks' "surgical team" model in the era of modern software development, with agile processes and modern tools? What does today's research say is the most effective team structure?

*Credit where credit is due: technically, Brooks is summarizing earlier research by Harlan Mills and F.T. Baker. I am using Brooks' name only because his name is more recognizable.

答:
The reason you don't see those surgical software teams that much is explained by the way developers are hired and assigned to teams.

Two preliminary conditions for such team are:

That there should be, within a company, developers who have different levels with an important gap between the most and the lest experienced ones,

And that they are ready to work together.

Let's talk about the first condition. When you look at different companies, developers they hire have similar skill level, experience level and culture. Would you find a talented and experienced developer in a small company which makes PHP websites for local shops? Probably not. You will rather encounter programmers who weren't particularly good at college, and who are not particularly interested by their job. If you do find a junior talented guy, you may be sure that he will leave this company as soon as he finds a better place—and he will find a better place, because lots of companies are looking for talented developers.

Now, would you find a lot of demotivated, inexperienced developers who work just for money at Fog Creek or Valve Software? I don't think so, not only because they won't be hired, but because they won't even try having an interview there.

This means that inside the same company, there will be junior developers and developers with dozens of years of professional experience, but all will still share the same culture and try to work the best they can in some companies, or just work for money in others.

Inside the company, you'll once again notice that the most talented ones want and are encouraged to work together. If there is a challenging project which is crucial for the company, you can be sure that you'll find the best developers there. A boring project which has nothing crucial will instead be given to developers who are slightly less talented. This is a natural way things are done, and this is what will happen if persons themselves decide on which project they will work next, without being formally assigned by the management.

While there is a possibility for the management to force a surgical software team by mixing talented developers with less talented ones, one should note that persons may not get along with each other well. The risk is that since they know that they were put together intentionally by the management, the most experienced person may start to behave like a jerk with his pairs; in turn, less experienced developers may try to avoid confronting the more experienced one. Compare that to a team of people who decided to work together and who respect each other, and you can see why surgical software teams are not a common practice...

In my opinion, surgical software teams may work. In some rare cases, and with persons who know what they are doing and who are ready to work with less or more talented colleagues. This being said, the last decade the trend was rather towards Agile teams of self-organizing persons who have similar culture and similar experience, but specializing themselves in different domains in order to be complementary.


问:
How safe is it to compile a piece of source code from a random stranger?
Suppose I'm reviewing code that job applicants send to prove their skills. Clearly I don't want to run executables they send. Not so clearly I'd rather not run the result of compilation of their code (just for example, Java allows to hide runnable code in comments).

What about compiling their code? I want compiler warnings if any but what if their code contains some clever character sequences which exploit my compiler and my compiler compromises my machine?

When I Google for "compiler vulnerabilities" the hits I get are all about compiler optimizations and code emission and whether emitted code is as secure as original source code was intended to be.

Are compilers typically validated to ensure they won't compromise the user machine when compiling some clever piece of code? How safe is it to compile a piece of code from a stranger?

答:
If the possibility worries you, take an older machine (don't most of us have a few sitting around?), install current version of Linux and compiler &c, copy the source code to it, unplug the network cable (or turn off WiFi), and do the compiles.  If anything nasty does happen, it won't* affect anything else.

And for malware in the Makefile, run it with the -n flag (IIRC, RTMF) to see what it will do without actually doing it.

*Unless of course your programmer coded the malware so that it waits for a reconnection, but in that case you a) wipe the machine; and b) forward the guy's resume to the NSA, 'cause he's wasted in the commercial world :-)

ContentLicense: CC BY-SA 3.0


问:
Communication between state machine and GUI
I am writing a finite state machine in C++, designed as a library.
Furthermore, I have a GUI implemented as a separate project which needs to update the user interface according to state changes happening in the library.

The way I implement the communication now, is that the GUI is calling a library function which returns a struct containing information about the state of the finite state machine (and other necessary information).

But I find this a rather ad-hoc solution and since it seems like a frequent situation, I am curious to know if there is a design pattern / text book way of handling this.

答:
I think Observer Pattern is a simple and clean solution to update your GUI.

It is a behaviour pattern that allows you to implement an event like system. It will keep your GUI nicely decoupled from your library.

I normally use it in conjunction with an Adapter pattern in other to decouple the concrete "update" implementation from my main Entity. This way I can mix and match different update behaviours without having to inherit from IObserver

https://en.wikipedia.org/?title=Observer_pattern

The advantage over the "callback" implementation would be that:

it is possible to have multiple of observers that get notified, each responding in a different way

the class that started the operation can be different from the class that reacts, thus implementing the model-view-controller paradigm.

You can implement different lists for different events allowing the
Observers to pick to what to react too

You can for example, use it to update your GUI, log to a file and something else, all of these in separated threads


问:
How should one modularly implement related objects?
I tried to make the question title as generally applicable as possible, but I'm not certain I worded it so well. It was brought about by a very specific problem I'm having, and for the remainder of this question I'll just try to describe that.

I'm attempting to write a small game engine with graphics, physics, and collisions*. I am trying to implement each of these things separately; it is perfectly conceivable that I have a graphically displayed, physically moving object that can't collide (fire effects?) or a collision object that isn't rendered or governed by physics (invisible barrier). However, a large number of objects will need all three.

I'm pretty darn sure that I can isolate the three pieces almost completely in their own classes, with the one exception that they all need to reference the same position and angular orientation of their object.

Initially, I thought that I'd put each thing into its own class and just build each actual game object with multiple inheritance, but in light of the fact that they all need to share data I wasn't so sure that that would work.

Next option was having each object initialized with pointers to the appropriate position and orientation data, but I felt weird treating those like special members . . . I would like each class to act as ignorant as possible of the others, and I would never do the pointers if I were designing each class independently.

I could also let each class live with its own position data and have the combination class (via either friendship or getters/setters) force them all to coincide, but that also just didn't feel right.

I tried searching Google for information on what's typically done, but most everything I found was focussed on a specific part of the system and didn't say a lot about integrating everything. Am I just being too philosophical, or is there a better way to do this?

If it's important, I'm using C++.

Thanks.

* I know that implementing it myself is pointless, but it's all just for fun.

答:
Services, not Superclasses

These things are not related objects, they are behavioral aspects of game objects that may come and go as the state of the game objects change; think about them as services, not superclasses. They're not well-suited to purely compositional elements either, as the in-game behavior will likely be strongly dependent on the state of the game objects over time.

Example

A 'ghost' object may be visible and in motion but can pass through solid objects but may not be able to pass through a magical barrier and also may inflict damage when it collides with living tissue. It can only be damaged by magical weapons.

Sorry

Game programming is hard, at this level mostly due modeling complexity. Hack around to get your own ideas (if just having fun) and/or study existing game engines to see what others have done (e.g. Unreal Engine's source code)


问:
How to write tests that make sense for visualization software?
I have a fairly large piece of software which takes certain file types and visualizes them / creates a host of buttons for manipulation of the image plotted. I feel like I'm finding bugs / pieces of code that don't actually work once a week, but I'm struggling with understanding how can I write tests for this software?

I understand how tests are important for projects like libraries and API's, you simply write tests that use these functions.

But what about visualization software? It seems to require a different approach due to the visual element(s) involved.

Do I need to write a test program or test harness which runs and manually calls every operation provided that I can use on the data?

What approach should I use in order to start writing tests in order to validate that I fixed the bugs and to alert me if the code breaks again?

There is a related but not duplicate question regarding when you should unit test.  Since I'm discovering bugs, I want to write tests in order to help prevent the software from regressing again.

答:
There are a couple of things you can do to make testing software like that easier.  First, try to abstract as much as you can into layers that aren't visual.  That will let you just write standard unit tests on those lower layers.  For example, if you have a button that performs a certain calculation, make sure you have a way to perform that calculation in a unit test with a regular function call.

The other suggestion for testing graphics-heavy programs is to create some output that a tester can easily manually verify.  A minecraft example is:

I've also worked on projects that had a bunch of tests that rendered something on the screen, then prompted the tester to manually verify it matched the description.  This makes sure you don't forget test cases later.

Testing is often extremely difficult if you didn't originally design with testing in mind.  Just work on putting your most fragile code under test first.  When you find a bug, make a test that will catch that bug if it happens again.  That often prompts writing related tests while you're at it.


答:
Start with a known file that produces an expected image. Check every pixel. Each should have an expected value for a known, hand-crafted test-file. You should have an expected output-image to compare it against. Anything that's "off" signifies a bug in your code.

Expand your test-file so the output image changes and hits every feature of your software.

Scripting would be handy for that sort of black-box testing. A simple script that executes the latest build of your software for the known input and expected output.

Unit Testing on the other hand, should be white-box testing where you take the smallest possible chunk of software, typically a function or whatever, and see if it behaves like you expect. You could see what pixel color it returns, or whatever. In this case your code behaves just like a library, with APIs to all the other sections of your code.

If it's all tucked into one .c file with all the functionality shoved into main(), then you've got bigger issues then how to test.

Title: How to write tests that make sense for visualization software?

Body:
I have a fairly large piece of software which takes certain file types and visualizes them / creates a host of buttons for manipulation of the image plotted. I feel like I'm finding bugs / pieces of code that don't actually work once a week, but I'm struggling with understanding how can I write tests for this software?

I understand how tests are important for projects like libraries and API's, you simply write tests that use these functions.

But what about visualization software? It seems to require a different approach due to the visual element(s) involved.

Do I need to write a test program or test harness which runs and manually calls every operation provided that I can use on the data?

What approach should I use in order to start writing tests in order to validate that I fixed the bugs and to alert me if the code breaks again?

There is a related but not duplicate question regarding when you should unit test.  Since I'm discovering bugs, I want to write tests in order to help prevent the software from regressing again.


问:
Design Pattern for retry and error handling
I'm trying to find a good design pattern, or perhaps series of patterns, for injecting error handling and retry handling when getting data from a webservice.

For instance, I have:

```<code>do {
    //get the data here
    data = Datagetter.getMyData(request)

    if(data.hasError())
    {
        //handle error
    }
} while(shouldRetry());
</code>```

And I am trying to figure out a way to inject the mechanism the discovers and deals with any error, as well as the mechanism that handles how retrying works (should I wait? have I retried enough? should I modify a request parameter? etc).

I would guess I am not the first person faced with this, and there is a way to do this I just haven't discovered yet.

I have looked into chain-of-responsibility and strategy as possible solutions, but I can't seem to quite finagle them to work.

答:
Have you looked into Aspect oriented programming ?

https://en.wikipedia.org/wiki/Aspect-oriented_programming

Maybe it helps ?

An other idea would be to use an abstract factory to return the concrete implementation that you need to handle the error on runtime.


答:
Everything has an interface. When I put my testing hat on, I use a specific world-view to write a test:

If something exists, it can be measured.

If it can't be measured, it doesn't matter. If it does matter, I just haven't found a way to measure it yet.

Requirements prescribe measurable properties, or they are useless.

A system fulfils a requirement when it transitions from a not-expected state to the expected state prescribed by the requirement.

A system consists of interacting components, which may be subsystems. A system is correct when all components are correct and the interaction between components is correct.

In your case, your system has three main parts:

some kind of data or images, which can be initialized from files

a mechanism to display the data

a mechanism to modify the data

Incidentally, that sounds very much like the original Model-View-Controller architecture to me. Ideally, these three elements exhibit loose coupling – that is, you define clear boundaries between them with well-defined (and thus well-testable) interfaces.

A complex interaction with the software can be translated into small steps that can be phrased in terms of the elements of the system we are testing. For example:

I load a file with some data. It displays a graph. When I drag a slider in the UI, the graph becomes all wobbly.

This seems to be easy to test manually and difficult to test automated. But let's translate that story into our system:

The UI provides a mechanism to open a file: the Controller is correct.

When I open a file, the Controller issues an appropriate command to the Model: the Controller–Model interaction is correct.

Given a test file, the model parses this into the expected data structure: the Model is correct.

Given a test data structure, the View renders the expected output: the View is correct. Some test data structures will be normal graphs, others will be wobbly graphs.

The interaction View–Model is correct

The UI provides a slider to make the graph wobbly: the Controller is correct.

When the slider is set to a specific value, the Controller issues the expected command to the Model: the Controller–Model interaction is correct.

When receiving a test command regarding wobbliness, the Model transforms a test data structure to the expected result data structure.

Grouped by component, we end up with the following properties to test:

Model:

parses files

responds to file-open command

provides access to data

responds to make-wobbly command

View:

renders data

Controller:

provides file-open workflow

issues file-open command

provides make-wobbly workflow

issues make-wobbly command

whole system:

the connection between the components is correct.

If we do not decompose the problem of testing into smaller subtests, testing becomes really difficult, and really fragile. The above story could also be implemented as “when I load a specific file and set the slider to a specific value, a specific image is rendered”. This is fragile since it breaks when any element in the system changes.

It breaks when I change the controls for wobbliness (e.g. handles on the graph instead of a slider in a control panel).

It breaks when I change the output format (e.g. the rendered bitmap is different because I changed the default colour of the graph, or because I added anti-aliasing to make the graph look smoother. Note that in both of these cases).

Granular tests also have the really big advantage that they allow me to evolve the system without fear of breaking any feature. Since all required behaviour is measured by a complete test suite, the tests will notify me should anything break. Since they are granular, they will point me to the problem area. E.g. if I accidentally change the interface of any component, only the tests of that interface will fail and not any other test that happens to indirectly use that interface.

If testing is supposed to be easy, this requires a suitable design. For example, it is problematic when I hard-wire components in a system: if I want to test the interaction of a component with other components in a system, I need to replace those other components with test stubs that let me log, verify, and choreograph that interaction. In other words, I need some dependency injection mechanism, and static dependencies should be avoided. When testing an UI, it's a great help when this UI is scriptable.

Of course, most of that is just a fantasy of an ideal world where everything is decoupled and easily testable and flying unicorns spread love and peace ;-) While anything is fundamentally testable, it is often prohibitively difficult to do so, and you have better uses of your time. However, systems can be engineered for testability, and typically even testing-agnostic systems feature internal APIs or contracts that can be tested (if not, I bet your architecture is crap and you have written a big ball of mud). In my experience, even small amounts of (automated) testing effect a noticeable increase of quality.


问:
(Spring) AOP Design of Transactions
In our application we have several transactions, where each step is extensively logged.

Pseudocode:

```<code>@Component
public class OurServiceImpl implements OurService {

...
    @Transactional
    public void doComplexTransaction(...){
      String transactionId = generateTransactionId(userid, date)
      log.info("==========================Start Transaction" + transactionId);

      log.info("Doing A");
      doA(..., transcationId);

      log.info("Doing B");
      doB(..., transcationId);

      log.info("Doing C");
      doC(... transcationId);

      log.info("==========================End Transaction" + transactionId);
    }

...

    public void doA(..., transactionId){

      ...

      log.info("Doing SubA "+transactionId);
      doSubA();
    }

}
</code>```

Because the logging is distracting, we decided to use AOP for that.
The method doComplexTransaction(..) could be covered with @Around(execution(FQN.doComplexTransaction(..)))

The calls doA(), doB() and doC() could be refactored out to another class, so they could be covered with @Around likewise.

But then the following problem occurs:

How to pass the transcationId (generated in one advice) between different advices?

Or more general:

How to design "transactional logging (with identifier)" across several methodcalls and objects?

Could this be done with Spring-AOP?

My goal is to discern the different concurrent transactions in my log, that would make it easy queryable via elasticsearch et al.

Bruteforce-solution:

(similar to Steve Park's)

One idea, which I had, was generating the transactionId in the first advice and "inject" it for further calls in proceedingJoinPoint.proceed(..., transactionId). In any further advice, I could extract thetransactionIdvia.getArgs()and inject it in theproceed()`-call.

But this has two downsides:

1) It is aesthetically non pleasant, or just: awkward. It's a hack, though a working one.

2) This violates several design principles, first: the principle of least astonishment. If a reviewer looks at the POJO and sees a variable passed but never "used" - thanks to AOP - he would be at least astonished.

So, yes, that is one solution, but I am looking for a better one.

答:
I'm not sure whether I fully understand your intention or not, but you don't need to pass transactionId between advices if you just want to get the transactionId on new advice, since you can get it from JoinPoint object. If I assume you setup new Around advice to cover the join points (doA, doB and doC on new service), all the input arguments on those join points (doA, doB and doC) are available from the JoinPoint object by getArgs() method like below.
So, you just need to iterate input arguments with checking instance type or order of input argument to find the string type transactionId. I just refactor doA, doB and doC on AnotherSerivce to use Around advice.

OurService

```<code>@Service("ourService")
public class OurServiceImpl implements OurService {
    static Logger log = Logger.getLogger(OurServiceImpl.class.getName());

    @Autowired
    private AnotherService anotherService;

    @Override
    public void doComplexTransaction() {
        String transactionId = generateTransactionId(userid, date);
        anotherService.doA(transactionId);
        anotherService.doB(transactionId);
        anotherService.doC(transactionId);
    }
</code>```

Service contains doA, doB and doC methods

```<code>@Service("anotherService")
public class AnotherServiceImpl implements AnotherService {
    static Logger log = Logger.getLogger(AnotherServiceImpl.class.getName());

    @Override
    public void doA(String transactionId) {
        // TODO Auto-generated method stub
        log.info("test inside of doA");
    }

    @Override
    public void doB(String transactionId) {
        // TODO Auto-generated method stub
        log.info("test inside of doB");
    }

    @Override
    public void doC(String transactionIds) {
        // TODO Auto-generated method stub
        log.info("test inside of doC");
    }
}
</code>```

Aspect to track doA, doB and doC

```<code>@Aspect
@Component
public class TransactionTracker {

    static Logger log = Logger.getLogger(TransactionTracker.class.getName());

    @Around(value="execution(* com.my.AnotherServiceImpl.do*(..)) " )
    public void aroundProcess(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        for(Object arg: args) {
            if(arg instanceof String) {
                log.info("Get string type input argument: ".concat(arg.toString()));
            }
        }
        try {
            joinPoint.proceed(args);
        } catch(Exception e) {
            log.error(e.getMessage());
            throw e;
        }
    }

    @Around(value="execution(* com.my.OurServiceImpl.do*(..)) " )
    public void aroundProcessForOurService(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        log.info("start transaction");

        try {
            joinPoint.proceed(args);
        } catch(Exception e) {
            log.error(e.getMessage());
            throw e;
        }
        log.info("end transaction");
    }
}
</code>```

app config file

```<code>@Configuration
@EnableAutoConfiguration
@EnableAspectJAutoProxy
@ComponentScan("com.my")
public class AppConfig {

}
</code>```

Title: (Spring) AOP Design of Transactions

Body:
I'm not sure whether I fully understand your intention or not, but you don't need to pass transactionId between advices if you just want to get the transactionId on new advice, since you can get it from JoinPoint object. If I assume you setup new Around advice to cover the join points (doA, doB and doC on new service), all the input arguments on those join points (doA, doB and doC) are available from the JoinPoint object by getArgs() method like below.
So, you just need to iterate input arguments with checking instance type or order of input argument to find the string type transactionId. I just refactor doA, doB and doC on AnotherSerivce to use Around advice.

OurService

@Service("ourService")
public class OurServiceImpl implements OurService {
    static Logger log = Logger.getLogger(OurServiceImpl.class.getName());

    @Autowired
    private AnotherService anotherService;

    @Override
    public void doComplexTransaction() {
        String transactionId = generateTransactionId(userid, date);
        anotherService.doA(transactionId);
        anotherService.doB(transactionId);
        anotherService.doC(transactionId);
    }

Service contains doA, doB and doC methods

@Service("anotherService")
public class AnotherServiceImpl implements AnotherService {
    static Logger log = Logger.getLogger(AnotherServiceImpl.class.getName());

    @Override
    public void doA(String transactionId) {
        // TODO Auto-generated method stub
        log.info("test inside of doA");
    }

    @Override
    public void doB(String transactionId) {
        // TODO Auto-generated method stub
        log.info("test inside of doB");
    }

    @Override
    public void doC(String transactionIds) {
        // TODO Auto-generated method stub
        log.info("test inside of doC");
    }
}

Aspect to track doA, doB and doC

@Aspect
@Component
public class TransactionTracker {

    static Logger log = Logger.getLogger(TransactionTracker.class.getName());

    @Around(value="execution(* com.my.AnotherServiceImpl.do*(..)) " )
    public void aroundProcess(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        for(Object arg: args) {
            if(arg instanceof String) {
                log.info("Get string type input argument: ".concat(arg.toString()));
            }
        }
        try {
            joinPoint.proceed(args);
        } catch(Exception e) {
            log.error(e.getMessage());
            throw e;
        }
    }

    @Around(value="execution(* com.my.OurServiceImpl.do*(..)) " )
    public void aroundProcessForOurService(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        log.info("start transaction");

        try {
            joinPoint.proceed(args);
        } catch(Exception e) {
            log.error(e.getMessage());
            throw e;
        }
        log.info("end transaction");
    }
}

app config file

@Configuration
@EnableAutoConfiguration
@EnableAspectJAutoProxy
@ComponentScan("com.my")
public class AppConfig {

}


问:
Abstracton layer to control services access to denormalized db entity
Our db is optimized for minimum join count (partially denormalized). E.g. our User entity contains account data (nickname, facebook id, etc), user numerical statistics (total games played, total wins, etc), guild related user information (guild id, membership type, etc) and so on - everything in the same table.

We use ORM - NHibernate. The user table is mapped (with all the fields) to User class.

Now I'm refactoring a model class AccountManagementService that provides a possibility to do some actions on an enclosed User. The model has the two dependencies: NHibernate and the User entity. The model logic is strictly tied to ORM methods (performs selects, does updates).

I think it's bad that the model knows about so many fields which it's not going to use. It doesn't need User.GuildId, statistics, etc. But since the model already should use ORM it's logical that it should know about entity classes.

I'm also worried that some operations with User should be done only through special services but other services theoretically can access and change any of the User's fields. E.g. AccountManagementService should not change User.Money directly but use UserMoneyService instead. But from a compiler viewpoint such change is perfectly valid.

Should I introduce other abstraction layers between services and entities to control an access and how can I do it? Can you see any other possibilities to improve the situation?

答:
In the bigger view, this sounds like an Anemic domain model (Martin Fowler - https://en.wikipedia.org/wiki/Anemic_domain_model)

These Data Access Objects are a direct mapping to the database and do not reflect your business logic.

The way to go would probably be a CQRS (https://en.wikipedia.org/wiki/Command–query_separation) model, but it would probably force you to redo the full system.

You should probably read: Patterns of enterprise application architecture. I think you will find it a good resource. Its main topic is database mapping patterns.

There is really no escape from a middle layer here. I would do a class to represent each business domain and then map it to the DAOs. There will be no escape from spagetti


答:
I think you're worried about one of two flavors:

sophisticated, exploit-driven malware: unlikely, especially because these are targeted at very specific hardware and/or software and [based on your question] your attacker probably doesn't have that level of system knowledge.

things that screw with your environment: malicious prank directives (e.g. deleting your home directory) or inconsiderate/incompetent directives which change your system behavior (e.g. rewriting PATH or LIBRARY environment variables)

Some people have suggested virtual machines or old systems, but I offer a much easier solution: Compile as a different user with reduced/different permissions. Much easier than setting up a virtual machine or a dedicated computer.

If in the unlikely even that your system gets pwned by compile-time exploits, restore from backups (you have those, right?).

Title: How safe is it to compile a piece of source code from a random stranger?

Body:
Suppose I'm reviewing code that job applicants send to prove their skills. Clearly I don't want to run executables they send. Not so clearly I'd rather not run the result of compilation of their code (just for example, Java allows to hide runnable code in comments).

What about compiling their code? I want compiler warnings if any but what if their code contains some clever character sequences which exploit my compiler and my compiler compromises my machine?

When I Google for "compiler vulnerabilities" the hits I get are all about compiler optimizations and code emission and whether emitted code is as secure as original source code was intended to be.

Are compilers typically validated to ensure they won't compromise the user machine when compiling some clever piece of code? How safe is it to compile a piece of code from a stranger?


问:
Is serving a single document from a server to a browser slower than serving multiple documents?
I was looking into how to optimize web pages and the biggest way (code-wise) to optimize a website is to reduce the number of requests a browser has to make to your web server to get the full page.

The most obvious ways of doing this are:

Sprite sheets instead of individual images

Put all your css into one file

Put all your javascript into one file

But what if I got it down to one file total? By:

Converting all images into base64 encoded strings, embedded inline

Put all css inline

Put all javascript inline

Resulting in a very large html file, but no other requests.

I've loaded large HTML files from servers before (because they contained lots of information in a table or what not), and it actually choked the browser a bit loading the file. Is it advantageous to still segment out some files (such as large images, a single css and js file, etc) or would you get best performance out of a single document with all resources embedded?

答:
Combining resources is one way to potentially improve performance for a web site. Let's look, though, at what happens when we take this to the extreme hypothetical you pose.

Size Savings?

We can Base64 encode images and put them directly into an HTML document. The first problem, though, is that Base64 encoding a binary object increases its size by a factor of 33%. By doing this, we actually produce larger files to download, which can easily outweigh any savings from eliminating requests.

Independent caching

If we put everything into a single file, we've coupled together any changes to that file. That means that if the HTML file changes, that file and all of the assets in it will also need to be downloaded again. The same is true for changes to any of the other assets. If the files are separate, they get cached separately, and only the files that change need to be downloaded again. (HTTP provides all the necessary mechanisms for this.)

Reuse

Putting everything into a single file prevents reusing cached resources on other pages. Say we have a home page and an about page with the same stylesheet. With multiple resources, that stylesheet need only be downloaded when we visit one, then the cached version can be used when we visit the other. If everything is embedded directly into every file, the same CSS gets downloaded over and over again for each page.

Parallel downloads and pipelining

In HTTP/1.0, browser developers realized that downloading all assets serially would cause page load to be slow as assets would only load one after the other. In response, browser developers wrote in features to allow multiple connections so that assets could be downloaded in parallel, then all rendered together. This provided some speed up.

HTTP 1.1 introduced many new tools for optimizing performance. Among them was the introduction of pipelining. Instead of waiting for a response to finish, then sending the next request, browsers could take advantage of the full-duplex nature of TCP connections and send the next request as soon as it realized it had to. This allowed assets to be downloaded without delays between, speeding up performance as well.

With your single-page model, browsers would not be able to take advantage of parallel connections to download different assets at once. This could make your page load slower. With the introduction of pipelining, HTTP allows us to offer a similar effect as downloading a single file without interruption.

While combining some files does make sense when measured in real-life situations, combining every file could actually backfire.


答:
Instead of speculating, I actually bothered to do some research on this topic before answering, going to the most authoritative resource I could think of (CVE Details). This comprehensive list of publicly disclosed security exploits is probably the best that one could do to assess the threat levels of various types of software.

I didn't take time to read all of the available material, of course, but I selected a few "primary" compilers, IDEs, and text editors to come up with a sample threat assessment. If you're serious about running any software at all, you should at least see what threats are out there. Also note that older software is generally buggier than newer software, so running the latest of whatever you're running is ideal.

First, we can take a look at various text editors. It seems the best editors are the most simple. Vi if you're using a Linux shell, or Notepad if you're in Windows. Something with no formatting capabilities, no parsing, just straight-forward viewing of data and automatic termination of parsing if a single character is outside of the current encoding scheme. Even Notepad++ has had a handful of vulnerabilities. Avoid anything complex when viewing untrusted files.

Second, we can look at IDEs. If you choose to open the file in an IDE, you should be aware that some IDEs have had reported bugs. Apparently Visual Studio has had exploits available through the extensions mechanism, so opening a solution might be problematic. Avoiding IDEs avoids an entire class of problems between you and the untrusted code. Sticking with VI seems a lot safer.

Third, we can look at actual compilers. I browsed a few, including Adobe, Microsoft, Java, and GNU's C/C++, and found that generally speaking, compiling code (and even building, assuming no custom make-file) is relatively safe, but each of those compilers do or did have security exploits that could arise from actually running the compiled binaries. In other words, they couldn't take your system over simply by compiling, but they could by running code.

So, in conclusion, assuming the delivery method didn't already hijack your system (e.g. your email client got hacked, or the USB drive it came on was infected...), reading the source code and compiling the source code is probably safe. By researching your specific software, you could make it even safer by, say, validating the file is in the correct code page, etc. Running the code should only be done on hardware you simply don't care about. Not a VM, but an entire physically different computer with no network access and no sensitive files or external devices. Even if you think you understand the code, simple research shows that even compilers have bugs which might allow a hidden buffer overflow exploit to sneak up from behind and execute arbitrary code, but only if you choose to run or debug the program. Actual compilation should be safe.


问:
Source control branch design for deployed environments
I currently work with a young team of developers using ASP.NET, TeamCity and Octopus Deploy. One of our developers thinks that our system is flawed and introduces the inability to test production hotfixes. What is the best solution to this problem?

We have three environments: development, staging and production. Basically, our workflow only goes forward.

Git push to master -> TeamCity Build -> Octopus Deploy (Dev) -> Promote to Staging -> Promote to Prod

His solution is to have three branches: master (development), staging (staging) and prod (production). We do all active development in our master branch, do any QA in staging and merge from staging to prod when we need to perform a release. When a bug occurs in production, we make the change in staging, and then remerge into production, leaving our development branch alone. We eventually merge all development changes into the production branch once we are ready to release new features.

I don't think this is necessarily right however. My solution is to have the latest production version in the master branch. All development occurs in feature branches. When we've tested a feature branch, we merge back to production. Simple.

So what is the best solution to this problem? Also, some follow-up questions:

Should we improve our QA process? Should we be doing QA on feature branches or on full releases?

How should we set up our continuous integration? Should we have servers deployed for every version?

I'd love to hear some examples or suggestions you guys may have regarding this scenario. Thanks!

答:
It is good practice to building your code only once and not per environment or branch.

Your GIT branches should not be directly connected to your environment stages.

The pipeline should be as follows:

develop > merge to baseline > build > upload to repo > deploy on dev > test > deploy to Staging > test > approve > deploy to 1 Prod > test > to n Prod.

Always using the same Artifact between promotions. All environments should be mirrors, with environment depend configurations being injected and minimised.

"promotion" is done by the deployment tool and not via GIT branch merging.

I also apply the QA to the full product and not to feature branches.

Testing branches in a vacuum will lead to integration or merging errors not being found and a false sense of security about the quality of the code. It can also create confusion with the Product Owner "I thought it was done and tested ? Why do we get errors now ?"

If you are not applying continuous integration, branching makes sense to split your hotfix from your already developed newer code. As such, simply feed the hotfix into the start pipeline and deploy it over the newest version.

Problems may arise if there are environment or data changes that are not backward compatible between the newest version and the hotfix.

In this case, one normally also includes all the environment and data configurations as a part of the "version" thus rebuilding the full environment every deployment.

This can be easily achieved if the servers are virtual or if they are provisioned via a configuration management tool.

Pratical example: vagrant file for each version. When you rollback from version 1.4.5 to version 0.5.6 you also rollback the vagrant configuration and thus the environment configuration.

While not my initial reference, here is an MSDN Team foundation Server best pratices and patterns: https://msdn.microsoft.com/en-us/library/dn449951.aspx
I also advice the reading of the Addison-Wesley signature series books, Continuous Integration and Continuous Delivery


问:
Has-A or Is-A or some strategy pattern?
I am developing a web based application which is about tracking Fleet units.

Actually i have already developed the system but in the last six years things changed a bit. Ordinary the software specification was about monitoring vehicles in real time and then doing various reports.

How ever during the years we got so many clients in Europe that some of them wanted custom behaviour like inputing the date when various licenses were bought and the date when they expirse so they get a notification for each vehicle when it's time to buy new licence, vignette, insurance and so on..

All seemed to be very good until the time some clients decided that they will buy only 100 GPS devices but they still want to have the rest of 27 (for example) vehicles entered into the system so they get notifications about the vignette, insurance and licence expiration dates. So I had to add new variable like

```<code>boolean hasGps;
</code>```

Things got even worse. Some clients wanted to attach GPS devices to the trailers of the vehicles so they can monitor them to. So the only way to make this possible is to register the trailers as Vehicles and use the same class where i had to add a new field variable like:

```<code>boolean isTrailer;
</code>```

Well... again things got really ugly when a company liked the flow meter system that we attach to the vehicles and keep track of the spent fuel so they wanted to have a GPS device and a flow meter device integrated in their GAS station. Again i had to add a new variable like:

```<code>boolean isGasTank;
</code>```

These days the boss decided that the company will start selling personal tracking devices for security guards and dogs.

So... I decided to re-write the business logic and have the code more clean. However in a real world scenario it seems really difficult to make a good OOP design.

Lets say we have the following fleet units types where a gps device can be attached:

Vehicle, Trailer, GasStationTank, Ship, Person, Animal

All of this units have no behaviour. They only has a state and definition fields.

The only exception where a gps device may not be attached is the Vehicle object because as i mentioned we enter some ghost vehicles where the only tracking is about the expiration dates of various licences, vignette and insurance.

The Vehicle class has most fields where as the other classes have only id and alias fields. Some of the vehicle's fields are:

maxSpeed, fuelPer100, revolutions, flowMeter, fuelNorms. tanks, digitalEvents, analogEvents, parkingDefinition, workingDefinition,

Here is what I have made so far:

```<code>public enum FleetUnitType {

    VEHICLE, TRAILER, NONE_GPS_UNIT, GAS_STATTION_TANK, MOVING_NON_VEHICLE_UNIT

}
</code>```

Abstract class

```<code>public abstract class FleetUnit {

    private final String id;

    private String alias;

    private String group;

    private Optional<GpsDevice> gpsDevice;

    private long dateTimeAddedToSystem;

    private FleetUnit linkedFleetUnit;

    public FleetUnit(String id, String alias, String group) {

        if(id == null) throw new NullPointerException();
        else
        {
            this.id = id;
        }

        this.alias = (alias == null ? id : alias);
        this.group = group;

    }

    public abstract FleetUnitType getType();

}
</code>```

Vehicle class that implements FleetUnit class

```<code>public class Vehicle extends FleetUnit {

    public static final double VBAT_CONST = 0.175;

    private int maxSpeed;

    private double urbanFuel100;
    private double suburbanFuel100;
    private double fuelPerHour;

    double maxAccumulatorValueForZeroRevolution;

    private Optional<Revolutions> revolutions;

    private Optional<FlowMeter> flowMeter;

    private Optional<FuelNorm> fuelNorm;

    private final Map<Integer, FuelTank> fuelTanks;

    private final Map<Integer, DigitalEvent> digitalEvents;

    private ParkingDefinition parkingStartDefinition;

    private WorkingDefinition workingStartDefinition;

    public Vehicle(String id, String alias, String group, VehicleMetaData vMetaData) {
        super(id, alias, group);

        this.fuelTanks = new HashMap<>();
        this.digitalEvents = new HashMap<>();

        parkingStartDefinition = ParkingDefinition.ENGINE_OFF;
        workingStartDefinition = WorkingDefinition.ENGINE_ON;
    }

    @Override
    public FleetUnitType getType() {

        if(super.getGpsDevice().isPresent()) return FleetUnitType.VEHICLE;

        return FleetUnitType.NONE_GPS_DEVICE;
    }

    public static enum EngineState
    {
        MOVING, PARKED, STOPPED, WORKING, CONTACT, UNKNOWN
    }

    public static enum ParkingDefinition
    {
        ENGINE_OFF, TACHOGRAPH
    }

    public static enum WorkingDefinition
    {
        ENGINE_ON, MIN_DISTANCE_TRAVELED
    }

    public static enum MotoHoursCalculation
    {
        ACCUMULATOR, KANSHINA
    }

}
</code>```

As you can see these objects has no behaviour but simply a state which is useful for various reports like how much distance is traveled today or what is the spent fuel and so on...

So finally the question is, should I keep this design and then make the rest of the concrete classes to implement FleetUnit class or I should do something completely different?

答:
Maybe i missunderstood the problem, but it looks like these are actually separated entities.

I would personally not use inherence but favor composition.

I would create different classes for each entity implementing an ITrackable interface and simply define the GPS as an object in these entities.

Using an Interface

An IReportable interface can also be defined and implemented to add a method to pass the reporting class. something as simple as

```<code>.report(reportbuilder r)
    { r.report(this) }
</code>```

A visitor pattern should be kept in mind in case different reporters are required later on

Title: Has-A or Is-A or some strategy pattern?

Body:
Maybe i missunderstood the problem, but it looks like these are actually separated entities.

I would personally not use inherence but favor composition.

I would create different classes for each entity implementing an ITrackable interface and simply define the GPS as an object in these entities.

Using an Interface

An IReportable interface can also be defined and implemented to add a method to pass the reporting class. something as simple as

.report(reportbuilder r)
    { r.report(this) }

A visitor pattern should be kept in mind in case different reporters are required later on


问:
Merits of Namepsaces/Packages
Some programming languages (e.g. Java and C++) have language features called "packages" or "namespaces".  How useful is it really to have namespaces?  It is possible to mark functions and classes as belonging to some particular library without using such a language feature, like the SDL does (e.g. SDL_BlitSurface()).  Are namespaces not helpful enough to be worth having?  Are they useful in libraries but not in applications?  Are they useful everywhere except for in small projects?  Thoughts?

答:
Most (all?) languages with namespaces tend to be object oriented.  Many times a human readable name for a type is appropriate, even though there are multiple incompatible implementations.  (this brings up other issues on object oriented reuse, but that's not what this question is about).  For instance, in Java you have a Timer that is used for background UI tasks, and a Timer that is used for background application (not tied to AWT/Swing) tasks.  The namespace allows you to have these same-named objects living in different sub-APIs.

The reason that namespaces came into existence had to do with the unreasonable task of anticipating what other developers will name their objects.  C++ introduced the concept (or at least was the first language I was exposed to with the concept), and it was helpful even though there were no guidelines on best use practices.  Java adapted the concept and added some "best practices" that included your company name in the namespace.  That way you only had to worry about your own company.

Prefixing can become pretty messy.  When do you apply it?  When do you not apply it?  Do structures/classes/global methods get the prefix?  What about methods?  What about properties in the struct.  I've seen all of these things in code, although thankfully not all at once.  Namespaces provides some predictability to all of these questions, and makes it a language feature rather than a personal "best practice".

ContentLicense: CC BY-SA 2.5

Title: Merits of Namepsaces/Packages


问:
One method to search and create if not found, or two methods
Lets say i am writing a web app that accesses user accounts in a database. If the account exist use that data. But if the account doesn't exist create a new one.

Should this be done with two or one methods.

One method would search by name and if found get the account, but it would have a try catch block and if the query returned empty it would create the account with the name passed in.

Two methods would simply search and the create.

The benefits of one method would benefit from simplicity and code reuse but then that method is doing multiple things. And I have been told that is a bad thing. Where as two methods would would be separated well but it would have no code reuse.

答:
Definitely 2 methods.

If you have 2 methods, you can stack and arrange them, thus reuse them either in different sequence or even separate from each other.

If you have 1 method with both functionalities, you can only use it for whatever you designed to use it, hence no code reuse.

Also, these are different functionalities, thus they are better off being their own methods.

You can provide a wrapper method around these 2 to first do search, then add if search returned no results.


答:
The bottom line is that there is risk. The risk is fairly small as other answers note, but there is a risk. That means you need to ask two questions:

What can I do to mitigate the risk?

Is the risk high enough that I should care?

The second is what you've posited here in this question, but it's the wrong focus for this particular case. The answer to mitigating the risk is clear and readily available: don't compile the code on your machine. You have two obvious ways of compiling it without using your machine:

Use a virtual machine (as @FlorianMargaine pointed out immediately in the comments). You simply snapshot it before compiling and then restore the snapshot when you're done.

Use a hosted service (such as an online compiler).

These ways of mitigating your risk are so obvious, cheap, and easily accessible that it's not worth spending a lot of time trying to analyze how big the risk is. Just do one of them and be done with it.


问:
Can I use a closed source JS file in my GPL webapp?
Note: When I say "open source", I am talking about GPL. Substitute with "free" if you prefer. When I say "closed source", I mean "not GPL or MIT, etc".

We have an open source (GPLv3) webapp that we develop and sell support and hosting for
(similar model to redhat).
Note, this isn't a website that we host that happens to be open source. It's a website that our clients host (or pay us to host). Each client makes their own instance of the webapp. The entire webapp is under GPL.

A particular script that we use (FullCalendar) is licensed under MIT. But the author has added a new add-on feature that will not be open sourced (maybe, it's undecided). The exact details of this license are not available yet.

Can I purchase this new add-on script and use it in my webapp (distribute it with the website's gpl code)? I have a feeling, that distributing the script that I bought would be illegal since my clients haven't bought it. Could I work around this? Could I host the script on our servers and leave it out of the distributed source? Only distribute a minified version?

What are the rules for using closed source JS in a GPL based project?

And I'm not looking for legal advice. We're not paranoid about legal issues, we just want to make sure we aren't doing something that is obviously illegal/unethical and to understand exactly how you apply GPL to JS files. Also, I'd like to give the author of the script some feedback.

答:
The simple answer is: "it depends on what the license you get says"

If the commercial license says that you can relicense so that it may be used in an open source product, then thats what the license says.  I tend to doubt that this would be the case because it would essentially mean that it would lose nearly all of its power of actually being able to monetize the work.

If the license does not allow relicensing, you fall firmly into the area covered by the FAQ item What legal issues come up if I use GPL-incompatible libraries with GPL software? .  This says that you can provide an exception to your software that it may be used in combination with non-free libraries.

Note that you are not distributing the non-free software as part of the your product. Again, the license that you get will tell you what you can and cannot do.  I do not suspect that it will allow redistribution of the software under another license.

I want to emphasize that the redistribution of third party software is determined by the license on the software. It doesn't matter if you are building this as GPL, BSD, or closed source yourself. The license of the software says if you can or cannot redistribute it (or if it is intended for a single deployment).

You may find yourself filling out a form such as the one or iText (which is AGPL) for the commercial licensing which has a quote request that includes the number of servers (production and development), number of desktops (production and non-production), number of android devices, and numbers of PDFs generated per month as part of the necessary information. You provide that information and then they give you a quote.  You say you want to freely distribute it and I suspect that quote will be rather large.

It should also be emphasized that the FSF does not consider minified javascript to be open because it does not allow the practical modification of the code. This means that even if you are allowed to put the minified javascript in your software and release it under a free license, you would be doing so against the spirit of the GPL.


答:
"Update or create if doesn't exist" can be considered a single operation: upsert. The real thing to be concerned about when it comes to "doing multiple things" (also known as the Single Responsibility Principle: a class should only have 1 reason to change) is what's managing the interaction between the DB and programming objects. Whatever it is should be separated out into a Data Access Layer (DAL). The specific class that handles user-DB mapping should only declare the specific schema for users; another class (possibly an ancestor) would be responsible for creating/retrieving and running queries (which may include upsert, along with the basic CRUD operations of create, read, update and delete).

If possible, find and use an existing DAL library/framework for the platform. If you can't find something suitable, there are various DAL patterns, such as Data Mapper.

Title: One method to search and create if not found, or two methods

Body:
Lets say i am writing a web app that accesses user accounts in a database. If the account exist use that data. But if the account doesn't exist create a new one.

Should this be done with two or one methods.

One method would search by name and if found get the account, but it would have a try catch block and if the query returned empty it would create the account with the name passed in.

Two methods would simply search and the create.

The benefits of one method would benefit from simplicity and code reuse but then that method is doing multiple things. And I have been told that is a bad thing. Where as two methods would would be separated well but it would have no code reuse.


问:
Where to initialize objects
I have an BallEntity class that is part of a game that uses a Entity Component System architecture.

This class have 'components' that are like the attributes of that class.

I create and initialize this components in getComponents method. To build this components I need others objects, like a Sprite (that is the image represents that ball) for SpriteComponent, a Body for BodyComponent, a camera for CameraFollowerComponent.

Those objets come to the class through arguments to the constructor.

I instantiate the BallEntity this way:

```<code>        BallEntity ballEntity = new BallEntity(new Sprite(atlas.findRegion("ball")),rubeSceneHelper.getBody("ball"), camera, rubeSceneHelper);
</code>```

My question is Whether these objects (or which) must be initialized in the constructor of BallEntity or Within the class that instantiates BallEntity?

```<code>public class BallEntity extends UserEntity {
    public static final float SCALE = 0.78f;
    private final RubeSceneHelper rubeSceneHelper;
    private ScaledSprite ballSprite;
    private Body ballBody;
    private Camera camera;

    public BallEntity(Sprite sprite, Body ballBody, Camera camera, RubeSceneHelper rubeSceneHelper) {
        this.ballSprite = ScaledSprite.create(sprite, SCALE / sprite.getHeight());
        this.ballBody = ballBody;
        this.camera = camera;
        this.rubeSceneHelper = rubeSceneHelper;
    }

    @Override
    public Array<Component> getComponents() {
        Array<Component> components = new Array<Component>();
        components.add(PositionComponent.newInstance());
        components.add(CameraFollowerComponent.newInstance(camera));
        components.add(SpriteComponent.newInstance(ballSprite.getSprite()));
        components.add(BodyComponent.newInstance(ballBody));
        components.add(BallContextComponent.newInstance());
        return components;
    }

    @Override
    public void init(Entity entity) {
        BodyComponent bodyComponent = entity.getComponent(BodyComponent.class);
        bodyComponent.setPosition(Vector2.Zero);

        Fixture ballFixture = rubeSceneHelper.getFixture(bodyComponent.getBody(), "ball");
        ballFixture.setUserData(new FixtureUserData(FixtureType.BALL, entity));
    }
}
</code>```

答:
The way you're showing it now ("I instantiate the BallEntity this way"), it is being done by the implementation (code) that calls the constructor to create BallEntity.

To be clear, the point is that the way you're showing it, everywhere that you create a BallEntity (whether in separate classes or multiple places within the same class), you're re-specifying how to create new component objects.  In other words, you are saying that it is the caller's job (creator of BallEntity) to identify and create the appropriate components, wherever these BallEntitys are created.

If there is only one place where BallEntity is created, I wouldn't worry about it too much.

If it turns out that there are multiple places in the code where a BallEntity is created, you should look to see if they are each doing it conceptually differently or conceptually the same way.

For as much of the components that are being created conceptually the same way, then you should apply DRY (Don't Repeat Yourself) principles and find a place to put this code.

There are two alternatives that come to mind.

(1) As you suggest, in BallEntity, by putting an additional higher level constructor in BallEntity, that takes the atlas, rubeSceneHelper, and camera as parameters and then calls the other constructor using code as you suggest for the instantiation above.  (Maybe make the original constructor private, too, or remove it and just have the one.)

(2) Use the Factory design pattern, which says you put this same common code in some other factory class.  Usually you'd use a factory pattern if you also have additional reasons beyond what you're showing here for decoupling the request for a (creation of) BallEntity and what and how is actually created.

For example, with the factory pattern you can return a subclass of BallEntity even, or, you could return a Singleton (the design pattern), or, you could manage a pool of BallEntitys, and hand them out based on any kind of criteria.  Whereas with a constructor you can only return a brand new BallEntity each time.

(Lastly, if it turns out that several classes each instantiate BallEntity, and each class instantiates the BallEntity in multiple places, yet each class does it conceptually the same internally to itself, but it is done conceptually differently between the classes, then your other suggestion is appropriate, to gather that code perhaps once in each of those other classes.  This is sort of a mix and match alternative, which is just applying DRY more than once as needed.)

Title: Where to initialize objects


问:
Unit Testing for mapping int to string
How should one unit test a function which (among other things) maps an integer to a string?

If the function were to map 0 => string0, 1 => string1, 2 => string2, should I test for each of 0, 1, and 2? Or should I just test one of these cases?

答:
I suggest you have one unit test for each linearly independent path through the function. In practice, this means one test, plus an additional test for each branch.

To learn more, I suggest you read about Cyclomatic complexity (https://en.wikipedia.org/wiki/Cyclomatic_complexity)

Title: Unit Testing for mapping int to string


答:
Visual Studio actually warns you if you open a project from an untrusted location (e,g, downloaded or network share).

One example how this could be exploited would be with a WPF project: You can reference .NET classes from XAML, and to provide IntelliSense, VS loads and executes the referenced classes at design time.

That means an attacker can drop a malicious .dll into the bin directory, replace the source code with non-malicious one, and at design time, the DLL is executed. After your first build, every trace of the malicious binary is gone.

So even though all provided code is "clean", the compiler is bug-free and you, of course, never manually execute any provided .EXE, malicious code could still be executed in the background. (To be safe from that specific attack, you can just make sure that there are NO binaries in the directory tree before opening the solution. VS will then prompt you to build the solution before providing IntelliSense at design-time.)

Similar vectors probably exist with other languages / OSes.


问:
Testing a Conversion class
I have a class that is responsible for performing conversions from/to twenty-something types. Let's call this class ConvertUtils.

For C# programmers out there - this class expands .Net's Convert class.

It looks something like this:

```<code>public static class ConvertUtils {
    public static object ChangeType(object obj, Type newType) {
        if (conversionSupportedByFramework)
            return Convert.ChangeType(obj, newType);
        else
            ConvertSpecialCases(obj, newType);
    }
}
</code>```

How would you go about testing it? I'm assuming we do need to black-box test this code.

The two ways we thought about, are:

Writing 400+ unit tests - cover all to/from combinations that we can think of.

Write tests only for the new conversions - the ones not supported by the Convert class - actually testing only the ConvertSpecialCases() function [which isn't our goal, as stated above]

The con of the first possibility is to have too many tests - which prolongs the build time, involves maintaining more code, etc.

The con of the second possibility is to not fully check the responsibility of the class -
what if a certain if statement decides to implement (wrong) custom logic, instead of letting Convert do it's job? e.g. just before if (conversionSupportedByFramework) someone decides to call some custom logic?

What do you think about this issue?

答:
Firstly, determine whether your changes will impact other public methods from the Convert class. If they will, find out which ones are impacted. Now you are better equipped to make a decision.

In case there is no impact in other public methods and functionalities, then only focus on new things you add or the ones you change.

If the change affects other areas of the Converter class, start testing what you have added or changed, then test methods your modifications have impacted.

Another advice is, if your changes affect existing features, when testing existing features give priority to the ones you are already using. Probably they will not be a big number.

Something else to consider is the following. For methods that have not changed, use the original Converter class. Use your new one only for the changing elements. When you are sure that your new Converter class is working, then make all modifications. Even if you use a lot of these Converter methods, making the change will not be too hard because the method signatures will not change and since you are confident the new Converter is working, your software should have no impact.

Title: Testing a Conversion class


问:
Should I create thumbnail for uploaded images?
I am working on a Website and trying to decide if I should create separate thumbnail image for each image user uploads. Or just set a smaller width/height when displaying thumbnails.

I am planning to set a limit of image size to 2MB.

Any suggestion?

答: found this from W3Cschools: Tip: Downsizing a large image with the height and width attributes forces a user to download the large image (even if it looks small on the page). To avoid this, rescale the image with a program before using it on a page. I guess I've already known the answer - create separate thumbnial for each image uploaded. </p>


问:
Are there more efficient ways to search for help/documentation than Google/SO/...?
Google sometimes come up with irrelevant links, not everything is available on SO, there are cases where the local documentation is also annoying to look through... Are there other efficient ways you use to search?</p>

答:
Practise your Google-fu. Google is pretty awesome, but it's not magic. Sometimes you'll need to use search operators to get better answers, especially on some code phrases that can be difficult to search. Check out the Google Guide, for example.

If I know where the answer is, I might use the site: operator, or if I need something citable I often use inurl:edu. Google Code is handy for finding examples, and I use it to search for APIs sometimes.


答: In addition to the answer above, I'd also recommend testing out edge cases - so e.g. -1, 0, and then a large number. You could also test that passing something other than an integer makes the method behave the way it is supposed to behave.</p>

Title: Unit Testing for mapping int to string

Body:
How should one unit test a function which (among other things) maps an integer to a string?

If the function were to map 0 => string0, 1 => string1, 2 => string2, should I test for each of 0, 1, and 2? Or should I just test one of these cases?


问:
Is external merge sort a divide-and-conquer algorithm?
Today I was corrected for mentioning "External Merge Sort" as an example of a divide-and-conquer (D&C) algorithm and after doing a lot of research online and in the most prominent books on algorithms, I started to realize that External Merge Sort is usually placed in their own separate categories and never referred to as a D&C algorithm.

Given that Merge Sort is one of the most famous examples of a D&C algorithm, how come that  External Merge Sort is not considered D&C algorithms in most books?

答:
Personally I don't know the reasoning behind those books and I don't claim to have any unique insight on this issue.

However, external merge sort can be implemented in exactly two stages, and neither stage contain recursive subdivision. In other words, in both stages, there is only one level of subdivision.

Choose number of subdivision N.

Stage 1: Arbitrarily partition input data into N subdivisions. Sort within each subdivision.

Stage 2: Create N FIFO queues, each feeding from the corresponding subdivision in the sorted order. Perform N-way mergesort (binary heap or selection sort) by peeking each queue's head and removing the smallest element, sending it to the output FIFO queue. Whenever an FIFO queue become empty it will feed from the remaining data from the corresponding subdivision. The sizes of FIFO queues are chosen according to available memory, but the algorithm still works correctly even if all FIFO queue has size 1.

As explained above, there is no recursive subdivision of the problem.

This is just an observation. I don't know whether book authors regard recursive subdivision as a key part of D&C.

There are many external merge sort schemes. The one described above is only one example. Those other schemes might make use of recursive subdivision. I don't know much about those so I won't be able to comment.


答:
At least w3schools is right on this. It is indeed wiser to have a downsized image, or even several downsized images if you site needs it. Note that you may even want to have the "full size" image smaller than the user uploaded image.

You will have guessed that these images being user uploads, you'll need some kind of script to generate the thumbnails on the fly though. Finding an existing script to perform that shouldn't be an issue no matter which language you're using.

Title: Should I create thumbnail for uploaded images?

Body:
I am working on a Website and trying to decide if I should create separate thumbnail image for each image user uploads. Or just set a smaller width/height when displaying thumbnails.

I am planning to set a limit of image size to 2MB.

Any suggestion?


问:
DB Schema design : single table with more columns vs multiple tables with fewer colomns
What would be better DB design for a social network website.
A single table with more columns and less rows or multiple table with fewer columns but more rows.

For example:
User can post an update on their wall or in a group.

Two DB designs that I could think of are:

1)
UserPosts: id, userId, post, datetime
UserGroupPost: id, groupId, userId, post, datetime

Potentail problem : Might require joins, which can (in future) be a slow query.

2)
Posts: id, userId, groupId, post, datetime
(where groupid would be null if user posts on their wall)

Potential Problem : Looping over large dataset could take a (long)time.

Where can I get better performance when data increases?
Is there any other(better) way?

答:
Joins are not slow. They are incredible fast if you join to a primary key or indexed column. You should not make design decision from the assumption that joining is a problem.

Now, there may be particular cases e.g. with very large datasets or distributed databases, where joining may be a performance problem, and there are various ways to mitigate that (indexed views, denormalization, caching), but since you don't mention that you have these specific issues, I would guess it would be premature optimization to think about.

Unless you have very specific issues, you should design your data normalized, and then use indexes etc. to avoid performance problems.


问:
Does the Composite design pattern implement recursive behavior?
The Composite design pattern allows us to call an operation() on a 'composite' node in a tree structure, and this operation() will be called on all of the children, subchildren and so on.

When an element's operation() is invoked, it is it's responsibility to call operation() on all of it's children, and so on. Each child responsible to invoke the operation on it's own direct children.

I understand why this has a recursive nature. When we learn of this design, the word 'recursion' is inside our heads all the time.

But can this be considered 'recursive behavior' in the strict sense of the word?

I always thought that recursion simply means a process where 'a function calls itself'. ('function' or 'method' or 'procedure' etc).

However, in the Composite design pattern, no method calls itself. A method calls the identically-named method in the objects composed with it (serving as it's 'children') - but it never calls itself (aka void operation(){ this.operation(); } never happens).

So, does the Composite design pattern create recursive behavior? Or does it create behavior resembling the nature of recursion? Is my definition of recursion wrong because it's too strict? If so, how would you define recursion?

答:
I rather like to think of the Composite element as the aggregator, rather than the recursively defined element.

The point is that contained elements do not have to behave the same way as the composite. They don't even have to expose the same feature. For example, composite element may sum up the results from the contained elements. Contained elements can simply return a fixed value.

The fact that composite allows us to imagine it as a tree-like structure doesn't mean that it is strictly a recursion.

Example from this article looks more like a recursion: Composite Design Pattern. But example from this article looks more like an aggregation: Working With Collections.


问:
How safe is it to compile a piece of source code from a random stranger?
Suppose I'm reviewing code that job applicants send to prove their skills. Clearly I don't want to run executables they send. Not so clearly I'd rather not run the result of compilation of their code (just for example, Java allows to hide runnable code in comments).

What about compiling their code? I want compiler warnings if any but what if their code contains some clever character sequences which exploit my compiler and my compiler compromises my machine?

When I Google for "compiler vulnerabilities" the hits I get are all about compiler optimizations and code emission and whether emitted code is as secure as original source code was intended to be.

Are compilers typically validated to ensure they won't compromise the user machine when compiling some clever piece of code? How safe is it to compile a piece of code from a stranger?

答:
Although this is generally a concern, I think the issue is non-existent due to the setup.

The applicant sent you some source code. How or why did that happen?

Well obviously there are only three possibilities:

You gave the applicant an assignment to solve a particular (well-defined) problem to assess his skills.

The applicant wants to show off something cool he wrote.

The applicant is a jerk or a spy or an otherwise malicious person and not actually interested in being hired. All he hopes for is you being stupid enough to run his code.

About 2) and 3)

The main risk is distinguishing between 2) and 3). Chances are high that if whatever he wrote is worth looking at, it's something that you can either get the source code for online (from a "neutral" source) and that you may even be familiar with already, or it's something that you actually don't want to look at because you would infringe a competitor's (former employer's) intellectual property. The latter would mean that you wouldn't want to hire that person anyway.

If you can get the source online, do so. If you can verify the applicant's contribution to a well-known software (including proprietary software) by his name somewhere in the credits, do so.

In every other case, simply ignore whatever he sent you. It's either not worth looking at, or illegal, or high risk.

About 1)

The applicant sent you something because you gave him an assignment. If you have any competence (which I assume you do!), then for a typical programming assignment (...that you even chose yourself!), you will be able to tell whether it's a plausible solution that looks as if it might work by looking at the source code for less than 30 seconds (more likely 10 seconds).

If you cannot tell that the program will probably work (or what it's doing at all) within 30 seconds, the one who wrote it not the kind of person you want to hire, fullstop. You want people who write code that other humans can understand and maintain. You do not want someone who is trying to get smart at you, nor someone who regularly wins the obfuscated C contest. It doesn't even matter whether the program works. As soon as another person cannot understand the code, it never "works".

If the program looks like it will probably work, but you find anything that looks "weird" (say, Java unicode escape sequences, C++ raw string literals, stuff that looks like trigraphs, whatever), treat the assignment as "fail", move on to the next applicant. It's not necessary to include anything the like in 99% of all programs (and, sure enough, not in your assignment -- I should hope). So if you find anything "weird" like that, the applicant is not someone you will want to hire.

If the code passes that first triage, you may want to spend another 2-3 minutes looking at it more thoroughly. If you are still pleased with what you see after that, you may run it through a static analyzer and compile it in a virtual machine at a high warning level.

That should bring up issues that you may have missed while reading the source (such as invoking undefined behavior or narrowing conversion).

Compiling will first and foremost tell you whether the applicant has the necessary diligence and attention to detail, not so much whether he has programming skill. Much like writing the employer's name correctly on your application and spellchecking your CV before handing it in, it is best practice that you make sure whatever source code you hand in compiles without errors (and preferrably without warnings). If someone fails to do that, you do not want to hire him.

The risk of evil things happening at this point (exploiting the compiler and breaking out of the VM) is neglegible, seeing how you have already run a plausibility check over the code. Not going to happen.


问:
What is the advantage of implementing a composite design pattern?
Apparently, a composite design pattern represents individual entities and collective entities in the same manner.

What is the advantage to this? For instance, if I subclass a class, why would I want to treat objects of both classes in the same way?

For instance, if 'tuna' is a subclass of 'fish', why would I want to have the same implementations for methods of objects in both classes?

答:
You don't apply Composite to treat Tuna and Fish the same way. To do that, you simply use Fish, because every Tuna is Fish.

Composite is useful when multiple items expose the same interface as each of them separate. But there is the twist. Composite element is then responsible to iterate through the collection (like in this article: Working With Collections) and to aggregate multiple results into a single result (like in this article: Composite Design Pattern).

Actually, Composite enforces Single Responsibility Principle in that it separates the aggregation step from actual feature, which is then enclosed in the simple element.


问:
Class with navigation property and with or without foreign key
Let's say I have the following classes, auto generated by Entity Framework, that have an association:

```<code>public class Parent()
{
    public int ParentID { get; set; } // PK
    public int ChildID { get; set; } // FK
    public string Description { get; set; }
    public Child Child { get; set; } // Navigation property
}

public class Child()
{
    public int ChildID { get; set; } // PK
    public Parent Parent { get; set; } // Navigation property
}
</code>```

As you can see, the Parent class contains a foreign key property to the Child class.

Now, let's say I want to retrieve some data from my database with LINQ. What I would do is create a custom class (model) so that I don't have to work with the auto generated classes (I can easily add more properties, methods,...).

```<code>public class ChildModel()
{
    public int ChildID { get; set; }
    // More properties/methods
}
</code>```

When creating the ParentModel class, I have two ways of creating this class:

A class with both the property ChildID and a navigation property Child.

```<code>public class ParentModel()
{
    public int ParentID { get; set; }
    public int ChildID { get; set; }
    public ChildModel Child { get; set; }
}
</code>```

Or a class with only a navigation property Child and no ChildID property.

```<code>public class ParentModel()
{
    public int ParentID { get; set; }
    public ChildModel Child { get; set; }
}
</code>```

With the second method, I always have to create an extra class when I only need the ChildID, with the second method I don't have to. But when I do create the ChildModel, I have to initialize both ChildIDs so that I don't run into any problems later.

What would be the best way to create my model classes? With or without the foreign key? Are there any advantages/disadvantages when using one of the two methods described above?

答:
Using both childId and Child property seems to be the worst option because of potential mistakes / inconsistencies.

Having only the Navigation property seems best option for several reasons:

If the relationship is optional you have a clear indication that there is no child by setting the property to null. In case you have only childId, you need to set it to some magic number like -1 or 0,  which is less elegant I suppose, or make it int? type which isn't a better solution either.

With Navigation property you can implement several features like automatic lazy loading.

Your objects stay abstract to the actual storage and relationship implementation.


问:
How should I refactor a singleton (to be used by a container) when the refactored class requires initialization and takes a dependency?
I'm refactoring an old app to use dependency injection.n  I'm pretty new to DI.

I have a class that used to be a singleton.  I'm refactoring it into a non-singleton class and using the container to manage its lifetime (as a single instance).  It has some initialization that used to be done in the constructor but it seems that this is generally frowned-on in the DI world:  SRP says methods should just do one thing and so constructors are just for dependencies, I read somewhere.

If the class had no dependencies, I could just create the instance, call .Initialize() and register the instance with the container as a singleton.  But the class has a dependency which I'd prefer to resolve using the container.

Am I going about this the wrong way?  Am I missing some pattern?

答:
Not sure what language you are using, so I'm using pseudo-C# as example.

You can create an IInitializes interface, which you then call after the instances are created.

```<code>public interface IInitializes
{
   void Initialize();
}

public class PreviousSingleton : IPreviousSingleton, IInitializes
{
    IDependency dep;

    public PreviousSingleton(IDependency dep)
    {
        this.dep = dep;
    }

    public void Initialize() {
        // do whatever with dep
    }
}
</code>```

Then when you register and create it using IoC :

```<code>IoC ioc;
ioc.RegisterAsSingleton<PreviousSingleton>(); // make sure IoC recognizes it as both having IPreviousSingleton and IInitializes interfaces

// do rest of the registrations

// and after registrations are done, run initialization
var instancesToInitialize = ioc.GetAllInstances<IInitializes>();
foreach(var inst in instancesToInitialize)
{
    inst.Initalize();
}

var noLongerSingleton = ioc.GetInstance<IPreviousSingleton>(); // should be initialized now
</code>```

This works, because only one instance will be kept inside IoC, which means same instance will be initialized as one that will be passed to other objects. Also works if you have multiple different classes implementing IInitializes.

Body:
Not sure what language you are using, so I'm using pseudo-C# as example.

You can create an IInitializes interface, which you then call after the instances are created.

public interface IInitializes
{
   void Initialize();
}

public class PreviousSingleton : IPreviousSingleton, IInitializes
{
    IDependency dep;

    public PreviousSingleton(IDependency dep)
    {
        this.dep = dep;
    }

    public void Initialize() {
        // do whatever with dep
    }
}

Then when you register and create it using IoC :

IoC ioc;
ioc.RegisterAsSingleton<PreviousSingleton>(); // make sure IoC recognizes it as both having IPreviousSingleton and IInitializes interfaces

// do rest of the registrations

// and after registrations are done, run initialization
var instancesToInitialize = ioc.GetAllInstances<IInitializes>();
foreach(var inst in instancesToInitialize)
{
    inst.Initalize();
}

var noLongerSingleton = ioc.GetInstance<IPreviousSingleton>(); // should be initialized now

This works, because only one instance will be kept inside IoC, which means same instance will be initialized as one that will be passed to other objects. Also works if you have multiple different classes implementing IInitializes.


答:
This depends on how your conversion class looks like. If it looks like this:

```<code>  class MyConvert
  {
       public static Foo1 ToFoo1(Bar1 bar){...}
       public static Foo2 ToFoo2(Bar1 bar){...}
       public static Foo3 ToFoo3(Bar1 bar){...}
       // ...
       public static Foo1 ToFoo1(Bar2 bar){...}
       public static Foo2 ToFoo2(Bar2 bar){...}
       // ...
       public static Foo20 ToFoo20(Bar20 bar){...}
  }
</code>```

you should implement at least one test (better two or three) for each method. And if you have 400 methods, you need a small multiple of 400 tests.

If, however, your class looks different, and you have something like an "internal representation class" for all of your Bar objects, you can reduce the number of tests. Assume something like this:

```<code>  class MyConvert
  {
       public static Foo1 ToFoo1(object bar)
       {
           MyInternalObj myObj = new MyInternalObj(bar);
           return myObj.ToFoo1();
       }
       public static Foo2 ToFoo2(object bar)
       {
           MyInternalObj myObj = new MyInternalObj(bar);
           return myObj.ToFoo2();
       }
      // ...
  }
</code>```

you will only have to write tests for the constructor of MyInternalObj for all allowed type of objects (at least 20), and additional tests for the methods ToFoo1, ToFoo2,..., of MyInternalObj  (also at least 20, or a small multiple of those).

Knowing your implementation looks like this, but you do not want to access MyInternalObj directly, you can also apply the same tests by calling MyConvert.ToFoo1 with 20 different Bar types, and MyConvert.ToFooXYZ in all 20 variations using the same "Bar" type.

Or more general: make sure you get a good code and branch coverage of all the code you have written.

Title: Testing a Conversion class

Body:
I have a class that is responsible for performing conversions from/to twenty-something types. Let's call this class ConvertUtils.

For C# programmers out there - this class expands .Net's Convert class.

It looks something like this:

```<code>public static class ConvertUtils {
    public static object ChangeType(object obj, Type newType) {
        if (conversionSupportedByFramework)
            return Convert.ChangeType(obj, newType);
        else
            ConvertSpecialCases(obj, newType);
    }
}
</code>```

How would you go about testing it? I'm assuming we do need to black-box test this code.

The two ways we thought about, are:

Writing 400+ unit tests - cover all to/from combinations that we can think of.

Write tests only for the new conversions - the ones not supported by the Convert class - actually testing only the ConvertSpecialCases() function [which isn't our goal, as stated above]

The con of the first possibility is to have too many tests - which prolongs the build time, involves maintaining more code, etc.

The con of the second possibility is to not fully check the responsibility of the class -
what if a certain if statement decides to implement (wrong) custom logic, instead of letting Convert do it's job? e.g. just before if (conversionSupportedByFramework) someone decides to call some custom logic?

What do you think about this issue?

Body:
This depends on how your conversion class looks like. If it looks like this:

  class MyConvert
  {
       public static Foo1 ToFoo1(Bar1 bar){...}
       public static Foo2 ToFoo2(Bar1 bar){...}
       public static Foo3 ToFoo3(Bar1 bar){...}
       // ...
       public static Foo1 ToFoo1(Bar2 bar){...}
       public static Foo2 ToFoo2(Bar2 bar){...}
       // ...
       public static Foo20 ToFoo20(Bar20 bar){...}
  }

you should implement at least one test (better two or three) for each method. And if you have 400 methods, you need a small multiple of 400 tests.

If, however, your class looks different, and you have something like an "internal representation class" for all of your Bar objects, you can reduce the number of tests. Assume something like this:

  class MyConvert
  {
       public static Foo1 ToFoo1(object bar)
       {
           MyInternalObj myObj = new MyInternalObj(bar);
           return myObj.ToFoo1();
       }
       public static Foo2 ToFoo2(object bar)
       {
           MyInternalObj myObj = new MyInternalObj(bar);
           return myObj.ToFoo2();
       }
      // ...
  }

you will only have to write tests for the constructor of MyInternalObj for all allowed type of objects (at least 20), and additional tests for the methods ToFoo1, ToFoo2,..., of MyInternalObj  (also at least 20, or a small multiple of those).

Knowing your implementation looks like this, but you do not want to access MyInternalObj directly, you can also apply the same tests by calling MyConvert.ToFoo1 with 20 different Bar types, and MyConvert.ToFooXYZ in all 20 variations using the same "Bar" type.

Or more general: make sure you get a good code and branch coverage of all the code you have written.


答:
"It has some initialization that used to be done in the constructor but it seems that this is generally frowned-on in the DI world" - that's not exactly true. DI is just about providing dependencies externally not creating them within an object.

So first thing fo you is to identify, within your singleton, what are it's dependencies and which are other object that it just uses to execute it's logic but they don't need to be created externally.

For example, say you have you OldSingletonClass which uses instances of C1 and C2 classes, that have their own dependencies. These should obviously be injected. But say that this class is supposed to make some HTTP calls and you implemented it with a some HttpClient and this HttpClient does not take any dependencies. I'd say that in this case you can safely create it in constructor (if it of course makes sense to keep single instance).

As for creating stuff in constructor vs Initialize() method - my experience is it is sometimes discouraged to do too much stuff in ctor because of different object inheritance issues, but other than that it's just a matter of style
Last thing, remember that DI does not require to use DI-container. It is often very helpful if you're working with tons of objects and some frameworks that "magically" create new instances (ASP.NET MVC controllers for example), but in case that you have, say, 20 objects, all created at application startup, I find it is often much cleaner to wire them together in code.

Title: How should I refactor a singleton (to be used by a container) when the refactored class requires initialization and takes a dependency?

Body:
I'm refactoring an old app to use dependency injection.n  I'm pretty new to DI.

I have a class that used to be a singleton.  I'm refactoring it into a non-singleton class and using the container to manage its lifetime (as a single instance).  It has some initialization that used to be done in the constructor but it seems that this is generally frowned-on in the DI world:  SRP says methods should just do one thing and so constructors are just for dependencies, I read somewhere.

If the class had no dependencies, I could just create the instance, call .Initialize() and register the instance with the container as a singleton.  But the class has a dependency which I'd prefer to resolve using the container.

Am I going about this the wrong way?  Am I missing some pattern?


答:
You don't have to test .NET Framework's code in your specific case, because:

You can't inherit from Convert class, since this class is static; even if you could do that, for example if Convert class weren't static:

The Convert class has no virtual methods,

There are no instance methods,

There are no abstract methods,

You cannot override static methods in a class,

You shouldn't hide methods by using new keyword anyway (and if you do, Code analysis will shout at you).

The only way you may be able to screw with existent functionality is through Reflection. If you use Reflection in order to play with the internals of the Convert class, then yes, you have to study and test the impact it may have.

Otherwise, you just have to test the new code you'll write in your custom class.

Title: Testing a Conversion class


答:
"SRP says methods should do just one thing". True. Constructors should do just one thing, and that is to put the object into a usable state. If just storing the dependencies doesn't put the object into a usable state, then the constructor isn't doing it's job. </p>

<p>Did you read anywhere that "constructors with dependency injection should only set the dependencies, and shouldn't do anything else"? I don't think so. </p>

Body:
"SRP says methods should do just one thing". True. Constructors should do just one thing, and that is to put the object into a usable state. If just storing the dependencies doesn't put the object into a usable state, then the constructor isn't doing it's job.

Did you read anywhere that "constructors with dependency injection should only set the dependencies, and shouldn't do anything else"? I don't think so.