问:
How to fulfill requirements of AGPL on my web service?
We want a simple tool to parse PDF forms, retrieving just the associated field names and user values.  PDFSharp would be a good option for us, as it is under the MIT license, but it is a few versions of Acrobat behind - so not going to work.  The most popular library (from what my searches have revealed) seems to be iTextSharp.  Thus I am introduced to the intricacies of the AGPL.

Now, for the structure of our app.  We want something simple and re-usable among any apps we may want to use later that require the same functionality.  My plan was to design a simple web service, that takes in the PDF file, and simply returns the Fields and Values in a list of key-value pairs.

It looks like, as long as this is an intranet service, there is no concern from the AGPL, as described in this question:  Can I safely use an open source library in an internal closed-source project?

That is our most likely scenario, but I wanted to be aware ahead of time in case we need to expose our service externally (such as for some of our Silverlight clients, for example).  If the service were exposed externally, then, under AGPL, would we simply need to provide the source for the service itself?  Or, would the source of any consumer of the service also need to be provided?

So, I am looking for 1) confirmation that in the intranet scenario there are no further considerations, and 2) what is necessary if the web service is publicly visible?

答:
In general, as long as you are not "conveying" the work, copyleft does not apply.  FSF doesn't consider "internal use" a form of conveyance.

If you later expose your service as an external API on the Internet, that is considered conveyance under the AGPL.  To comply with AGPL terms, you would have to open-source any other software that you also intend to convey which depends on that API for its proper functioning.

The usual disclaimers apply; if you want tractable advice, seek the counsel of an attorney that specializes in software licensing.


问:
Aren't decorators easily breaking the ISP?
"The Interface-Segregation Principle (ISP) states that no client should be forced to depend on methods it does not use."

The decorator pattern is a design pattern to decorate a method of a class. For this, the decorator implements the same interface as the decorated object, so it can take its place.

But doesn't this mean that it has to implement all of the methods in the interface, when it uses only one of them, the one it decorates? So I guess it violates the ISP. The only case it doesn't it is when the decorated interface only contains the method that needs to be decorated, but I see it as a rather rare case.

An example would be that there are pages in a book. Some pages have footnotes, other pages have titles at the top. So we implement these extras as decorators of a method, let's say draw(). But a page has other methods as well, let's say: fold() and tear() and other methods can come in later. But if we want to use decorated versions of pages inserted in a book, and working the same way, we end up implementing in every decorator every method of a page, where the only thing happening is that the decorator passes the call to the page it's containing.

```<code>interface IPage {
    public ITearResult tear();
    public void draw();
}

class FooterDecorator implements IPage {
    private IPage page;

    public FooterDecorator(IPage page) {
        this.page = page; //the object it decorates
    }

    //violates the ISP, because it has to implement it, but it's not using it,
    //just passes the operation
    public ITearResult tear() {
        return page.tear();
    }

    //decorated method
    public void draw() {
        page.draw();
        ... draw footer - the decoration
    }
}
</code>```

Am I not understanding the decorator pattern or the ISP correctly? Is it an acceptable violation or do these two really contradict each other?

答:
```<code>//violates the ISP, because it has to implement it, but it's not using it,
//just passes the operation
public ITearResult tear() {
    return page.tear();
}
</code>```

This is not correct. The decorator is using the tear method; it's implemented it according to its contract, even if the implementation is as simple as delegating that job to someone else. From the point of view that the decorator is the client of the original interface, there's no problem; the whole point of the decorator is to implement the original interface and more, so by definition it has a dependency on the interface.

The user of a decorator also has a dependency on the original interface and whatever augmentation the decorator provides; otherwise, he wouldn't need a decorator and could instead rely on an interface that provides only the new features.

Am I not understanding the decorator pattern or the ISP correctly, it's an acceptable violation or these two really contradict each other?

You're not understanding ISP correctly.

Consider a system with various types of doors. Doors implement an interface Door that contains methods open and close. The client code calls these methods and all is well.

Later on you need to implement a TimedDoor that closes on its own after a certain amount of time (but can still be closed through the close method before the time elapses.) Some client code out there needs to be able to set the timeout on these doors. What the Interface Segregation Principle tell us is that you shouldn't go add a setTimeout method to the Door interface; instead, we should define a new interface (say, TimedObject) that provides those facilities.

Consider what would happen if you added setTimeout to Door - now every door in the system has to implement that method. What should they do? Treat it as a no-op? Throw an exception? Both are violations of the setTimeout method's contract (i.e violations of Liskov's Subtitution Principle.) The only other option is to weaken the contract by saying that objects may or may not implement setTimeout, which is tantamount to saying that something may or may not be a TimedObject. You'd be fighting the type system and robbing yourself of the guarantees it's meant to buy you.

Another (much less important but still unfortunate) side effect is that modifying the Door interface would generally trigger a recompile of all code that relied on it even though that code has no use for the setTimeout method.

With that in mind, note that using a decorator doesn't modify the original interface it wraps.

ContentLicense: CC BY-SA 3.0

Body:
//violates the ISP, because it has to implement it, but it's not using it,
//just passes the operation
public ITearResult tear() {
    return page.tear();
}

This is not correct. The decorator is using the tear method; it's implemented it according to its contract, even if the implementation is as simple as delegating that job to someone else. From the point of view that the decorator is the client of the original interface, there's no problem; the whole point of the decorator is to implement the original interface and more, so by definition it has a dependency on the interface.

The user of a decorator also has a dependency on the original interface and whatever augmentation the decorator provides; otherwise, he wouldn't need a decorator and could instead rely on an interface that provides only the new features.

Am I not understanding the decorator pattern or the ISP correctly, it's an acceptable violation or these two really contradict each other?

You're not understanding ISP correctly.

Consider a system with various types of doors. Doors implement an interface Door that contains methods open and close. The client code calls these methods and all is well.

Later on you need to implement a TimedDoor that closes on its own after a certain amount of time (but can still be closed through the close method before the time elapses.) Some client code out there needs to be able to set the timeout on these doors. What the Interface Segregation Principle tell us is that you shouldn't go add a setTimeout method to the Door interface; instead, we should define a new interface (say, TimedObject) that provides those facilities.

Consider what would happen if you added setTimeout to Door - now every door in the system has to implement that method. What should they do? Treat it as a no-op? Throw an exception? Both are violations of the setTimeout method's contract (i.e violations of Liskov's Subtitution Principle.) The only other option is to weaken the contract by saying that objects may or may not implement setTimeout, which is tantamount to saying that something may or may not be a TimedObject. You'd be fighting the type system and robbing yourself of the guarantees it's meant to buy you.

Another (much less important but still unfortunate) side effect is that modifying the Door interface would generally trigger a recompile of all code that relied on it even though that code has no use for the setTimeout method.

With that in mind, note that using a decorator doesn't modify the original interface it wraps.


问:
Learning to investigate bugs
I'm not even sure how to define this difficulty. It reminds me of the test a couple of prospective employees did on me before I got a job. They would pick an object in the room and then I'd be allowed to ask questions to help myself determine what that object is (much like 20 questions). I was ridiculously good at this (no, I never got high points for humility), so I'd assumed that I'd be really good at troubleshooting bugs...

But here's the thing I figured out recently. I'm really good in that situation because it's really easy to see everything that's in the room, thus I can approach my problem with some concept of it's component parts. In essence I "know what I don't know". But with programming I run into a lot of situations where the problem is a complete unknown to me. I know it's broken, but I have no concept of how it might be broken. I've followed all the instructions, I know the technology fairly well...

If I'm honest, I feel like I'm just having a hard time imagining things that could be wrong so I can test them and, hopefully, find a solution.

How do I go about developing that skill? What do I need to do to help my, apparently, limited imagination come up with ways that my project could possibly be broken? Are there exercises (puzzles perhaps?) that can make me better at this? I'm aware that probably the biggest cure is just experience...but I'm hoping to help accelerate the process if I can. Staring at my computer screen blankly for a few hours at a time is not even kind of fun...

答:
Every defect in software is ultimately due to a discrepancy between assumptions and reality. Insidious bugs are simply discrepancies between particularly deep-seated assumptions and reality. The ability to diagnose bugs depends on your capability to question your own assumptions, and that does indeed require an awareness that you don't know certain things, you just assumed them and used to be right until now.

Obviously the tools of the trade, log files, debuggers etc. are helpful in uncovering such assumptions and re-aligning your world model with the actual system. But until you are ready to question the crucial assumption, e.g. "It can't be bad input because we have comprehensive input checking", you will spend your entire time checking the wrong parts of the system, or simply not knowing where else to look in the first place.

Title: Learning to investigate bugs


答:
What do I need to do to help my, apparently, limited imagination come up with ways that my project could possibly be broken?

In most cases, I'd say absolutely nothing. You shouldn't be trying to dream up things that might be causing the program to break. You should be systematically determining what is causing it to break.

You should be going into the debugging process with the following pieces of information:

the steps that were taken and the values that were entered to produce the bug;

what the program should be doing when given those steps and inputs;

what the program is doing when given those steps and inputs.

If there's an error message, get all the information you can about it. If the error message itself isn't clear, and you don't know what it means in practice (some error messages aren't always particularly useful), then use Google, or StackOverflow, or any other online resource to find information about it.

If there isn't an error message displayed on the front end, check any logs the application writes to for error messages during the time period you reproduced the bug. The code may have executed to completion, but encountered an exception that's being handled along the way which is throwing off the end result and producing an entry in the logs. Look for those, do the same above and identify exactly what they mean.

If there are stacktraces provided with exceptions thrown by your code (and there should be), look at the lines of code mentioned. The line itself may not be the one that's actually producing the issue. If you get a NullPointerException in a piece of Java code, the stacktrace will tell you where you tried to use something that was null when you expected it not to be. That doesn't exactly point you to the line causing the problem, but it generally does tell you what variable doesn't have the value you expect it to, so you can look at any references/assignments to that variable to determine that the value isn't being set or that the value is being set incorrectly.

If none of that has helped, fire up your debugger. If you've narrowed it down to a section of the code that you know is causing the issue - but you don't know exactly which line(s) - then step through that. If not, just step through the entire thing. This is where you need to know exactly what the program should be doing with given inputs, because you need to look at each value after each line and determine exactly where it's deviating from what you're expecting it to do.

Still don't have a clue what the problem is? Ask somebody for help. A co-worker, a friend, an online community. Show them all that work you just did. Show them the error messages, the stacktraces, explain what the program does in general terms (if they don't already know), what it should be doing in this particular instance (e.g. returning the value 4), what it's actually doing (e.g. returning the value 5). If you've narrowed it down to a few lines of code in the debugger, say "I know the issue is caused by these lines in the code, it's setting the value to X when it should be Y, but I can't see why that's happening".

Spending a few hours staring blankly at your screen definitely isn't fun, but there's no reason you should be doing that. If there's a problem with your code then you need to be reading or stepping through the code.

Title: Learning to investigate bugs

Body:
I'm not even sure how to define this difficulty. It reminds me of the test a couple of prospective employees did on me before I got a job. They would pick an object in the room and then I'd be allowed to ask questions to help myself determine what that object is (much like 20 questions). I was ridiculously good at this (no, I never got high points for humility), so I'd assumed that I'd be really good at troubleshooting bugs...

But here's the thing I figured out recently. I'm really good in that situation because it's really easy to see everything that's in the room, thus I can approach my problem with some concept of it's component parts. In essence I "know what I don't know". But with programming I run into a lot of situations where the problem is a complete unknown to me. I know it's broken, but I have no concept of how it might be broken. I've followed all the instructions, I know the technology fairly well...

If I'm honest, I feel like I'm just having a hard time imagining things that could be wrong so I can test them and, hopefully, find a solution.

How do I go about developing that skill? What do I need to do to help my, apparently, limited imagination come up with ways that my project could possibly be broken? Are there exercises (puzzles perhaps?) that can make me better at this? I'm aware that probably the biggest cure is just experience...but I'm hoping to help accelerate the process if I can. Staring at my computer screen blankly for a few hours at a time is not even kind of fun...


问:
Easiest way to use objects as filters for queries
I'm just starting on a new little pet project of mine. I started the project using a familiar pattern for using objects as "filters" in SQL Queries. I've never been much happy about its easy of use, but eventually more or less accepted it after having it drilled into my head by colleagues.

The example below hopefully highlights my concern. Especially in regards of sheer size. However that being said, I also see the strengths of this pattern which may put it in favor of continued use.

I'm looking for some opinions if I should continue as I always have or if there indeed is an easier way to do this. Either by using a different pattern or somehow "automate" the process.

Please note that the below is only an example and isn't in use.

```<code>public static User getUser(User filter) throws UserControllerException {
    String sql, sqlFilter = "";
    User user = null;

    try {
        Connection con = DataSource.getInstance().getConnection();

        if (filter.getCorp() != null) sqlFilter += " AND corp_id = ?";
        if (!filter.isNew()) sqlFilter += " AND user_id = ?";
        if (filter.getUsername() != null) sqlFilter += " AND username = ?";
        if (filter.getPasswordHash() != null) sqlFilter += " AND password_hash = ?";
        if (filter.getFirstName() != null) sqlFilter += " AND first_name = ?";
        if (filter.getLastName() != null) sqlFilter += " AND last_name = ?";
        if (filter.getPhoneNumber() > 0) sqlFilter += " AND phone_number = ?";

        sql = "SELECT * FROM users WHERE 1 = 1 " + sqlFilter;

        PreparedStatement ps = con.prepareStatement(sql);
        int psPos = 0;

        if (filter.getCorp() != null) ps.setLong(++psPos, filter.getCorp().getCorpId());;
        if (!filter.isNew()) ps.setLong(++psPos, filter.getUserId());
        if (filter.getUsername() != null) ps.setString(++psPos, filter.getUsername());
        if (filter.getPasswordHash() != null) ps.setString(++psPos, filter.getPasswordHash());
        if (filter.getFirstName() != null) ps.setString(++psPos, filter.getFirstName());
        if (filter.getLastName() != null) ps.setString(++psPos, filter.getLastName());
        if (filter.getPhoneNumber() > 0) ps.setLong(++psPos, filter.getPhoneNumber());

        ResultSet rs = ps.executeQuery();

        if (rs.next()) {
            user = new User(
                    rs.getLong("user_id"),
                    new Corporation(rs.getLong("corp_id"), null),
                    rs.getString("username"),
                    rs.getString("password_hash"),
                    rs.getString("first_name"),
                    rs.getString("last_name"),
                    rs.getLong("phone_number")
            );
        }

    } catch (IOException e) {
        throw new UserControllerException(e.getMessage(), e);
    } catch (SQLException e) {
        throw new UserControllerException(e.getMessage(), e);
    }
    return user;
}
</code>```

答: I'd start by building your filter SQL String within the filter object itself (i.e. writing a GetSqlFilter() method on the Filter class), so that you have access to Filter's internal members, without having to call all those member functions.


问:
What does bootstrapping mean in the context of Laravel?
I see 'the bootstrap process' mentioned in Dayle Rees Laravel tutorial "Code Bright" but no explanation of what it actually means. The Wikipedia definitions on Bootstrapping in computing don't seem to have any particular relevance.</p>

答:
The bootstrap process is responsible to pickup all the different pieces that combine Laravel framework together before you start to process the request and return result. This could be further explained and analysed by looking at bootstrap files. There is folder bootstrap in  root directory containing these files:

autoload.php - includes composer's autoloader, defines a few Laravel specific constants, initializes UTF-8 handling library etc. It is also responsible for loading any packages in workbench.

paths.php - this is just configuration array of relative paths. It allows you to move folders around or specify custom values. This is used so application knows where to look for various parts of framework.

start.php - this is the actual bootstrap part. It initializes Illuminate\Foundation\Application class, detects environment, loads path configuration from paths.php and starts the Framework so further processing of the request can continue (routing etc.).

I hope this helped you to understand a bit more of what bootstrap is in Laravel framework. Feel free to have a look at these files as they are very well commented and will allow you have a more in-depth review yourself. If you still feel that you have any questions feel free to comment.


问:
Full production build in source control for easy rollbacks?
I want a quick way to roll back our production build in the event of any mishaps - a one-click solution, if you will. My gut is telling me that this is important - and I believe that my gut is correct, but I want implementation advice.

My current thought is to start a local repository on our production server, and simply commit the entire production build to the repo - binaries, web assets, everything. When we make an update to the production site, we can commit the changes to the repo. This way, if anything breaks for any reason and we need a quick rollback - it's simply a case of checking out the previous commit.

What better methods are available for this type of rollback? I know that there are multiple backup solutions, but a VCS is familiar to work with and provides similar benefits. Am I stepping into a trap?

答:
If you use continuous deployment, then the easiest solution may be to rollback the last commit and let the system do the deployment stuff.

Otherwise, it depends on both your current workflow and the acceptable duration of the rollback. For example, if you don't rely on in-process sessions and you need the fastest possible rollback, you:

Create virtual machines during the original deployment,

Deploy the new version of the product on them,

Transfer your users from the old virtual machines to the new ones,

Keep the old virtual machines active, up and running.

Then, if you detect something wrong happening, all you have to do is to transfer the users back to the old virtual machines, which can happen nearly instantaneously.

In all cases, you'll rely either on:

swapping of servers (virtual machines or instances of IIS sites),

or a backup,

or snapshots (I'm not sure if this is doable in Windows for ordinary files; it is with LVM in Linux). You have snapshots feature in SQL Server, on the other hand.


问:
What is the role of the lead developer in an agile team?
In a non-agile development team a lead developer generally:

Sets the standard (coding and otherwise)

Researches new technologies for the team

Sets the technical direction for the team

Has the final say on matters

Designs the architecture of a system

However an agile team works differently:

An agile team will rely on emergent design, rather than up front

An agile team designs together, rather than design being dictated by one person

An agile team decides on their own technical direction, which is best to deliver a project

Where does this leave a lead developer in an agile team? Is it possible to have a lead developer in an agile team? Does a agile team demand different responsibilities from a lead?

答:
The question begs a few other questions.  What do you think qualifies you to tell a team of fellow software engineers what to do?  Is it your experience?  Is it the funny little title your boss handed you?  Is it your ego?  Your tenure at the company?  Is it your "panache?"  Your "style?"  Your "leadership skills?"

Agile teams don't hand out badges or hats to one another that say "Congratulations, you're our super genius -- you're the only one allowed to do super secret double genius work."  Rather, the focus is THE WORK AT HAND.  If you're indeed more experienced, then that experience should SHOW in how well your designs push the work forward toward completion.  Your self-chosen assignments (cards) should reflect the areas you're most expert in.  On the other hand, if some kid right out of college has a better idea, and it fits the context better than something some 40 year veteran comes up with, why on earth would we go with the poorer design?  Our workplaces aren't therapy offices -- they're where we come to build great things.

That begs another question:  who gets to decide what "better" means?  The answer: the team of stakeholders.  That means the developers, requirements people, testers, business people, etc. who are the builders and users of the thing in question.  If you have a great idea, you better be able to demonstrate why it's better.  If you can't do that, then there is no reason for the team to believe that your idea is better.  Agile encourages meritocracy.

So, what happens to the "development team lead?" in agile?  Nothing -- they just better live up to that name -- they better ACTUALLY be able to produce better software than the other people on the team.  Otherwise, there's no reason to call them a "lead" -- it's just a little badge or funny hat, and it's meaningless.  Lots of people find this threatening.  They feel like they've been "working for" a badge or funny hat.  Good developers don't work for funny hats.  They work to build great software, and they plan to do it until they croak -- their goal is to get better at building software, every day.  If that's not you, maybe you might want to look into project management.  You'll probably be happier.


问:
How to provide a service with RESTful API?
Generally speaking, RESTful API's are very good for representing resources and collections of resources.

http://example.com/resources

http://example.com/resources/item17

And we are good, if we work with resource.

However, what should be done, when you need to expose API which does an action which doesn't create/update or delete a resource.

Couple of examples:

You have an algorithm (as example add two numbers)

You have an action which uses external system (as example send an email).

I saw two approaches:

Represent an action as a subresource

POST http://example.com/resource/item17/sendemail

On one hand, it's straightforward. On other hand, it start smelling SOAPy (read RPC calls).

Represent an action as a standalone resource

POST http://example.com/emailsender

This looks more RESTful. However, it doesn't feel right too (only one of CRUD actions is implemented). This resource actually doesn't have a representation.

I am not sure, may be there are other methods which I have missed.

The question is - "Is there a consensus on this subject? What is the preferred way to do it?"

答:
There is probably no consensus on solutions for such actions. Hey, from what I've read there's not even consensus on how to implement all required characteristics of a REST API.

For performing different actions then just storing resources the resource based URLS can be used. For example sending mail could be implemented as a POST request of a message resource to the collection of messages of a specific user:

```<code>http://example.com/users/me/messages
</code>```

The software handling this request can do additional work when storing this resource. In the case of email use a status field indicating if it is a draft or not, and if not a draft send the resource to the receivers described in the resource.

For things like a calculation service this may be more difficult.

In general I like to look at it this way: How would I exchange a resource with the HTML mime type over HTTP using a browser as client? That matches the largest RESTful API I know of.

Body:
There is probably no consensus on solutions for such actions. Hey, from what I've read there's not even consensus on how to implement all required characteristics of a REST API.

For performing different actions then just storing resources the resource based URLS can be used. For example sending mail could be implemented as a POST request of a message resource to the collection of messages of a specific user:

http://example.com/users/me/messages

The software handling this request can do additional work when storing this resource. In the case of email use a status field indicating if it is a draft or not, and if not a draft send the resource to the receivers described in the resource.

For things like a calculation service this may be more difficult.

In general I like to look at it this way: How would I exchange a resource with the HTML mime type over HTTP using a browser as client? That matches the largest RESTful API I know of.


问:
Checking for the presence of optional properties of an object
I'm designing a class that holds several types of data.  Some of the properties are optional.  For example, let's say I have a class that represents a person, and one of the properties is occupation.  I have another property, military rank, but this property is can only be retrieved if the person's occupation is military.  What's the best way to handle this?

Have getMilitaryRank() throw IllegalStateException if the occupation isn't military

Have getMilitaryRank() return an Optional<Rank>

Return null if the occupation is invalid (I don't like nulls)

Something else?

Idea 1 works because the user can check the occupation prior to calling this method, making sure they don't call it on an invalid person.

Idea 2 seems unnecessary, because you can infer whether the Optional is present by calling getOccupation().

However, let's say my Person class has another optional property, but its presence can't be inferred from the value of another property; for example, a middle name.  Obviously it's best for getMiddleName() to return an empty Optional or null if the person has no middle name, as the presence of a middle name can't really be inferred some other way.

Since I should probably be consistent in how I'm handling optional properties, it seems like I could do one of the following:

Use Optional for any property that may be absent, even if it can be inferred from another property.

Add methods like hasMiddleName() to resolve the discrepancies (this seems like a bad idea)

Not be consistent and let the properties whose presence can be determined externally throw an exception, while the ones that are independent be wrapped in an Optional.

Something else?

While nulls could simplify things, it causes a problem if an optional property is an int, which can't be nullable in Java.  I could use an Integer, but that seems like a bad idea.

What is the best way to handle these different types of optional properties?

答:
Why not create a sub-class which represents someone in the military and have it inherit from your parent class. That way, you can check the type of class the object is. If its the Military class, you can call getMilitaryRank().

You can then create additional classes for other situations similar to this.


答:
To some extent, it is like investigating an criminal case, or a mind-boggling puzzle.

First, you got the victim. After digging a while into the case, you identified a few suspects and you also developed a work hypothesis how exactly the victim might got murdered. You  continue investigating, looking out for more helpful information, getting you nearer and nearer to the real source of the problem.

It happens that from time to time you walk into a dead end (pun intended). That's part of it, and there's nothing wrong with it, as long as you manage to bring yourself back on track as quickly as possible. The key is, to always think about what piece of information you need next, that either supplies your hypothesis (and provides you with further information), or proves it wrong. Then find a way to get that information in an efficient manner, make your conclusions and move on, until you finally are able to convict the guilty.

And sometimes you realize, that all the facts and indications necessary to spot the culprit were already waiting in front of you half an hour ago. Albeit annoying, that's among the most interesting parts, because if you do a critical review of your actions and mistakes, you may be able to learn and get better. Ask yourself questions like:

How could I have avoided this waste of time?

What did I overlook in the first place, and why?

What unvalidated and/or wrong assumptions did I rely on?

This will train your abilities. It will also develop your gut instinct, so over time you learn to automatically notice all those minorish things that are too easily overlooked, leading you quicker to the right answer. At the end, it's all about deliberate practice.

Last not least always remember what Sherlock Holmes taught us: When you have eliminated the impossible, whatever remains, however improbable, must be the truth.

Title: Learning to investigate bugs


问:
Building a DBAL from scratch
I am considering building a DBAL from scratch with PHP to use within my projects and also to learn through the process.

I have noticed on SO and other reputable forums that whenever this is mentioned most users advise to use an established DBAL like Doctrine and to not "reinvent the wheel".

Why is it that with this specific piece people continuously recommend to use a pre-made one? Is it that hard/problematic to create and build as you go? If so what are the main problem points? I assume security is one.

In regards to the established DBALs like Doctrine, I have downloaded and inspected the contents and noticed its rather big, for those who have experience with this, is all of this really necessary? Do you use all of this functionality provided(and know whats happening in the backend)?

From what I inspected I am finding it hard to see how I would use more than 40% of the libary, along with this I have the feeling that I am not completely sure whats happening in the backend with such a big library. Perhaps this is a common feeling and you get over it?

答:
You have a need,

There is a library which fulfills your need,

The library is free, so the only cost is the time you'll spend learning how to use it,

And you might be using up to 40% of this library.

How long is to learn how to use something like Doctrine? I'd say ten minutes for most basic scenarios, and up to an hour for more advanced stuff.

How long is to reinvent the wheel, i.e. write a similar library (minus 60% of its features you don't need), which means:

Creating the architecture and the design,

Writing enough tests to be sure it works correctly,

Writing code,

Handling edge cases,

Writing documentation,

Refactoring the code in order to be able to maintain it later,

Having a long-term commitment of maintaining the library for several years?

If you're a really fast and smart developer and you're able to do the first six steps in ten minutes, go for it. Go for it as well if you want to learn how ORMs are built (although there may be better ways to learn about ORMs).

But if you should deliver working software on time and within budget, reinventing an ORM without a very good reason wouldn't be a wise choice.

Title: Building a DBAL from scratch


答:
I like DFord idea of inheritance...by extending the Person class...
here are some additional ideas to consider...

```<code>public class Person {

  private String middelName;
  private String occupation;

  public String getMiddleName() {
      if (middleName == null) {
         return ""; // or any default value
      } else {
         return middleName;
      }
  }

  public String getOccupation() {
     if (occupation == null) {
         return "Unknown";
     } else {
         return occupation;
     }
  }

  public class Military extends Person {
     String rank;
     public String getMilitaryRank() {
        return rank;
     }
  }
</code>```

....then in the code somewhere...

```<code>if (person instanceof Military) {
   String rank = person.getMilitaryRank();
}
</code>```

Another idea is to create an enum for Occupation and have it return the default value of the Occupation if nothing is set, instead of "unknown".  Sometimes checking for specific values like the text "unknown" can add extra complexity.

```<code> if (occupation == null) {
    return Occupation.UNKNOWN;
 } else {
    return occupation;
 }
</code>```

... a better option is to initialize all of the variables in the constructor

```<code>public class Person {
    public Person() {
       middleName = "";
       occupation = Occupation.UNKNOWN;
    }

    public Occupation getOccupation() {
       return occupation;
    }

    public String getMiddleName() {
       return middleName;
    }
</code>```

Title: Checking for the presence of optional properties of an object

Body:
I'm designing a class that holds several types of data.  Some of the properties are optional.  For example, let's say I have a class that represents a person, and one of the properties is occupation.  I have another property, military rank, but this property is can only be retrieved if the person's occupation is military.  What's the best way to handle this?

Have getMilitaryRank() throw IllegalStateException if the occupation isn't military

Have getMilitaryRank() return an Optional<Rank>

Return null if the occupation is invalid (I don't like nulls)

Something else?

Idea 1 works because the user can check the occupation prior to calling this method, making sure they don't call it on an invalid person.

Idea 2 seems unnecessary, because you can infer whether the Optional is present by calling getOccupation().

However, let's say my Person class has another optional property, but its presence can't be inferred from the value of another property; for example, a middle name.  Obviously it's best for getMiddleName() to return an empty Optional or null if the person has no middle name, as the presence of a middle name can't really be inferred some other way.

Since I should probably be consistent in how I'm handling optional properties, it seems like I could do one of the following:

Use Optional for any property that may be absent, even if it can be inferred from another property.

Add methods like hasMiddleName() to resolve the discrepancies (this seems like a bad idea)

Not be consistent and let the properties whose presence can be determined externally throw an exception, while the ones that are independent be wrapped in an Optional.

Something else?

While nulls could simplify things, it causes a problem if an optional property is an int, which can't be nullable in Java.  I could use an Integer, but that seems like a bad idea.

What is the best way to handle these different types of optional properties?

Body:
I like DFord idea of inheritance...by extending the Person class...
here are some additional ideas to consider...

public class Person {

  private String middelName;
  private String occupation;

  public String getMiddleName() {
      if (middleName == null) {
         return ""; // or any default value
      } else {
         return middleName;
      }
  }

  public String getOccupation() {
     if (occupation == null) {
         return "Unknown";
     } else {
         return occupation;
     }
  }

  public class Military extends Person {
     String rank;
     public String getMilitaryRank() {
        return rank;
     }
  }

....then in the code somewhere...

if (person instanceof Military) {
   String rank = person.getMilitaryRank();
}

Another idea is to create an enum for Occupation and have it return the default value of the Occupation if nothing is set, instead of "unknown".  Sometimes checking for specific values like the text "unknown" can add extra complexity.

 if (occupation == null) {
    return Occupation.UNKNOWN;
 } else {
    return occupation;
 }

... a better option is to initialize all of the variables in the constructor

public class Person {
    public Person() {
       middleName = "";
       occupation = Occupation.UNKNOWN;
    }

    public Occupation getOccupation() {
       return occupation;
    }

    public String getMiddleName() {
       return middleName;
    }


答:
So rather than trying to reproduce and fix a specific defect I believe you are asking about thinking up new tests that you could use to investigate the product to see if the product works under those circumstances for example: what happens if I enter special characters into our sign up page's password filed, or what happens if I forcefully close the program while it is writing to the database. These cases are indeed hard to think up.

Software development over the past 10 years (Agile / XP / TDD etc.) has come to value meeting the explicit requirements only and then declaring the feature finished, and not finding every possible way to break something (there are possible exceptions, if you are working for NASA or doing white hat security but even then there is a case to be made for calling such things out in the user story's acceptance criteria).

So if your features explicitly list as acceptance criteria what the systems needs do such as how to handle input, its performance characteristics, user workflow actions, etc. then you have a complete list of what the tests need to be checking for. Testing should be done to validate that requirements have been met, and the best way to do that is to explicitly list all of your requirements. Take a look at the Agile Test Quadrants.

Some people advocate for these tests to be the explicit declaration of the requirements, that need to be written before the code i.e. Test First ( or Test Driven Development).

However I appreciate that you do not sound like you are contemplating a new project where you can set your own development best practices before you start and are instead coming in after the software has been written and are being asked to 'test it'. This is indeed more challenging but the same principles apply, you can only test it once you know what it was supposed to do. If there is not a comprehensive list of requirements that were met by the development team for you to work from then asking questions is the best way forward. Depending on your team this may need to be done delicately as people who did not explicitly list their requirements before building a software system do not like to be reminded of what they missed but it is essential to performing this task well.

Once you find a requirement - it must be robust / it must be secure, then try to dig deeper and find out how secure it must be, or how much failure is acceptable, there is always a limit, not many people have an NSA proof level of security as a requirement for their application or would want to pay for that. The more you dig the clearer it should be as to what types of security attacks you need to be defending against or easy of use you are aiming for. Some domain knowledge is then useful, in security, in design, in performance etc. which is where you ask even more questions from the experts you can find in your team, or here on SE, or google / books.

Title: Learning to investigate bugs


问:
Commenting regular expressions
Are there any common practises for commenting the regular expressions: inline comments referring different part of RegEx or general comment for all expression?</p>

答:
Comments should add useful information that is not obvious from the code.

Make it easy to understand what the expression is supposed to do at a requirements level, either in the code itself or in a comment. What is the intent behind the expression, is it to validate email addresses or pick out Canadian phone numbers.

Make it easy to understand what the expression is actually doing, i.e. what the expression evaluates to. First try to make it clear by splitting up the expression, if you first check for all hyphens then remove all numbers then make that a two part expression with variables holding the intermediary values, it will make it much easier to read and the reader will be able to step through your logic one step at a time. (There is a famous answer to a question on SE where someone is trying to decipher some old code which involves bit manipulation '>>' and finding out if certain flags are set where the answer lays out not only what the code really does but how the question's authour should go about deconstructing this kind of code in the future which is exactly what I am trying to describe but I can't seem to find the question to link to)

There are few applications that need every last cycle, if you are pattern matching massive data sets then maybe there is a better way, maybe not, but for most things the extra execution time is not that big a deal.

And remember the next person to come across your code and fix a bug might be you in six months time and there is no way you are going to remember what it was supposed to do.

Title: Commenting regular expressions


答: You can use reflection to get the various properties and fields into a list, cycle through the list, and determine the correct output for your filter statement. Reflection is slow compared to directly retrieving a property, accessing the internal members of your class, or accessing fields.</p>

Title: Easiest way to use objects as filters for queries

Body:
I'm just starting on a new little pet project of mine. I started the project using a familiar pattern for using objects as "filters" in SQL Queries. I've never been much happy about its easy of use, but eventually more or less accepted it after having it drilled into my head by colleagues.

The example below hopefully highlights my concern. Especially in regards of sheer size. However that being said, I also see the strengths of this pattern which may put it in favor of continued use.

I'm looking for some opinions if I should continue as I always have or if there indeed is an easier way to do this. Either by using a different pattern or somehow "automate" the process.

Please note that the below is only an example and isn't in use.

```<code>public static User getUser(User filter) throws UserControllerException {
    String sql, sqlFilter = "";
    User user = null;

    try {
        Connection con = DataSource.getInstance().getConnection();

        if (filter.getCorp() != null) sqlFilter += " AND corp_id = ?";
        if (!filter.isNew()) sqlFilter += " AND user_id = ?";
        if (filter.getUsername() != null) sqlFilter += " AND username = ?";
        if (filter.getPasswordHash() != null) sqlFilter += " AND password_hash = ?";
        if (filter.getFirstName() != null) sqlFilter += " AND first_name = ?";
        if (filter.getLastName() != null) sqlFilter += " AND last_name = ?";
        if (filter.getPhoneNumber() > 0) sqlFilter += " AND phone_number = ?";

        sql = "SELECT * FROM users WHERE 1 = 1 " + sqlFilter;

        PreparedStatement ps = con.prepareStatement(sql);
        int psPos = 0;

        if (filter.getCorp() != null) ps.setLong(++psPos, filter.getCorp().getCorpId());;
        if (!filter.isNew()) ps.setLong(++psPos, filter.getUserId());
        if (filter.getUsername() != null) ps.setString(++psPos, filter.getUsername());
        if (filter.getPasswordHash() != null) ps.setString(++psPos, filter.getPasswordHash());
        if (filter.getFirstName() != null) ps.setString(++psPos, filter.getFirstName());
        if (filter.getLastName() != null) ps.setString(++psPos, filter.getLastName());
        if (filter.getPhoneNumber() > 0) ps.setLong(++psPos, filter.getPhoneNumber());

        ResultSet rs = ps.executeQuery();

        if (rs.next()) {
            user = new User(
                    rs.getLong("user_id"),
                    new Corporation(rs.getLong("corp_id"), null),
                    rs.getString("username"),
                    rs.getString("password_hash"),
                    rs.getString("first_name"),
                    rs.getString("last_name"),
                    rs.getLong("phone_number")
            );
        }

    } catch (IOException e) {
        throw new UserControllerException(e.getMessage(), e);
    } catch (SQLException e) {
        throw new UserControllerException(e.getMessage(), e);
    }
    return user;
}
</code>```


答:
I usually define a string constant whose name describes the overall purpose of the regular expression.

For example:

```<code>const string FloatingPointNumberPattern = @"[-+]?[0-9]*\.?[0-9]+";
</code>```

You could add a comment above this constant to give it a description, but usually the constant name itself should be enough.

Title: Commenting regular expressions

Body: Are there any common practises for commenting the regular expressions: inline comments referring different part of RegEx or general comment for all expression?</p>

Body:
I usually define a string constant whose name describes the overall purpose of the regular expression.

For example:

const string FloatingPointNumberPattern = @"[-+]?[0-9]*\.?[0-9]+";

You could add a comment above this constant to give it a description, but usually the constant name itself should be enough.


答:
There's two solutions, depending on the specifics of your problem. If these optional properties are only combined in a relatively small number of ways, you can use a sum type to distinguish between them. The advantage of this approach is that you can guarantee exhaustiveness - you can statically ensure that wherever a decision must be taken based on the particular kind of person, all of the kinds are handled somehow.

The other solution is to group the optional properties that always occur together into interfaces and then implement the interfaces you can support in each class. You can detect the particular interfaces a person supports by applying instanceof and then casting. This approach won't force you to update all the use sites when you add a new interface, but works better when the number of possible combinations of optional properties is very large. E.g. if there's 7 groups of optional properties, there's 127 ways to combine those groups into classes, and it'd be ridiculous to take a decision based on each possible combination. If you need to reuse the implementations of those interfaces, use composition.

That aside, do be careful about making assumptions about people's names.


问:
How do I deal with global variables in existing legacy code (or, what's better, global hell or pattern hell)?
So... We have this fairly complex project (~10k LOC, but there's duplicated code so it's hard to tell) with hundreds of global variables. The project has more dependencies on other projects, and many other projects depend on it too. I have mostly inherited the responsibility to refactor just a part of this project by myself, an "enclosed section" of modules. None of the original developers remain.

I have devised a way to structure the routines in classes (breaking up megamoths, forming some class hierarchies, a little Strategy here and there, nothing too fancy (I hope); the objective is to make it easier for other developers to add functionality and make it possible to add proper unit tests).

My new classes provide calculations applied to currently-global arrays of data that are updated, and the calculations themselves need to maintain a state (a sum, the last value of the last processed vector, etc). You could see them as functors.

I'm unsure on how to deal with globals, though. I don't think I will be able change all globals to non-global because of the dependencies to other modules, which I'm not going to refactor just now. Also, many of my new classes will need to share data. So, I can...

For the globals that are not shared between my new classes, leave them as they are. I was thinking of using a Registry, or at the very least use some #define's or other variables to limit scope and provide context wherever they're used.

For the globals that will be shared between my new classes, either make a base class with the references, or use a Singleton to pass them around, or a combination of both.

I'm not sure if using these patterns will do more harm than good.

So, my question is: what's better, live with existing global variables or aggressively tune them with patterns like Singleton or Registry? Do you have any suggestions to these schemes, or have a better scheme?

答:
Flag all the globals with [Obsolete] attribute (or whatever if your not using c#)

Setup the infrastructure wiring for Dependency Injection, like so:

```<code>using (var mainForm = factory.Get<MainForm>()) {
      Application.Run(mainForm);
}
</code>```

Then go about your business implementing features from backlog.  As you modify existing code, your IDE will point out bad actors (obsolete vars).  When they cross your path, try to get it from the dependency injection container instead.  You don't need to replace all instances in a great big sweeping change that is guaranteed to have unintended fallout.

As you go along, you'll get more and more confident of use cases for one or two of these evil doers.  Concurrently, you'll be building skilz with your DI container of choice.

Then, one day, when your DI container in wired through most of your code base, you take a smallish class, and stamp out all the [obsolete] vars in it.  You do this by stubbing out a test fixture with the simplest of tests, instantiation through your DI container.

```<code>    var factory = new NinjectFactory();
    var mainForm = factory.Get<MainForm>();
    Assert.That(mainForm, Is.Not.Null, "MainForm");
</code>```

Then find an global var, and pass it in through the constructor.  Your test will fail if you haven't configured DI for class of the global var.  Of course, that class will have dependencies that you'll have to unwind, but try unwind only as much as is necessary to get test (and hopefully App) running.

BTW - I'm in neck deep in a similar situation right now.  (much bigger project though, the main form alone was 3k lines of code!)  It's quite satisfying once you get the hang of it.

Body:
Flag all the globals with [Obsolete] attribute (or whatever if your not using c#)

Setup the infrastructure wiring for Dependency Injection, like so:

using (var mainForm = factory.Get<MainForm>()) {
      Application.Run(mainForm);
}

Then go about your business implementing features from backlog.  As you modify existing code, your IDE will point out bad actors (obsolete vars).  When they cross your path, try to get it from the dependency injection container instead.  You don't need to replace all instances in a great big sweeping change that is guaranteed to have unintended fallout.

As you go along, you'll get more and more confident of use cases for one or two of these evil doers.  Concurrently, you'll be building skilz with your DI container of choice.

Then, one day, when your DI container in wired through most of your code base, you take a smallish class, and stamp out all the [obsolete] vars in it.  You do this by stubbing out a test fixture with the simplest of tests, instantiation through your DI container.

    var factory = new NinjectFactory();
    var mainForm = factory.Get<MainForm>();
    Assert.That(mainForm, Is.Not.Null, "MainForm");

Then find an global var, and pass it in through the constructor.  Your test will fail if you haven't configured DI for class of the global var.  Of course, that class will have dependencies that you'll have to unwind, but try unwind only as much as is necessary to get test (and hopefully App) running.

BTW - I'm in neck deep in a similar situation right now.  (much bigger project though, the main form alone was 3k lines of code!)  It's quite satisfying once you get the hang of it.


问:
Sending emails from server side
I need to read some of your opinions. I'm developing a desktop app (.net/winform) to keep data in one place. This is used by several clients and the data is stored in MS SQL Server (client-server arch.)

One of the feature is to be able to send notifications via email when conditions met. I've never did something like this so I can't figure out the best way to implement this.

Mails are sent on a daily basis. They don't have attachments nor heavy content. Just plain text.

Send mails directly from SQL? Stored Procedure?

Make a separate app to handle this? (Running on serverside).

Use a schedule task? (Windows Server)

Use a 3rd party app?

Hope anyone know what is the best way to do this.

Thanks for you time & answers.

答:
Do you not have a server-side component running now?

I would avoid having the SQL Server send the Email itself.

If you just need code somewhere to wake up occasionally and check for specific conditions and take action, you could write a simple console app and use the Windows task scheduler on the server to run it every so often. If the conditions are right, send your Email messages, otherwise, just exit clean. Check again the next time the task scheduler fires up your console app.

Or you could write a Windows service to essentially do the same thing, except that you would use the task API or Windows timers to occasionally wake up and check for appropriate conditions. The service will be a bit trickier than scheduling a simple console app. There are service installation issues. You can't have your worker code blocking the primary thread where you're listening for important things like service control messages. Your worker code needs to be responsive to these events, as well. So if you get a shutdown message, you need to respond to it in a reasonable amount of time (a second or two, not a minute or two). You probably want to consider some kind of a queue-based design that can send half the messages, get shut down, wake back up and send the other half without losing it's place, and so on.

If you're not savvy about issues like service installation and the thread synchronization and service control events, I'd just do the simple console app and use the Windows Task Scheduler. "Low tech" can actually be kind of a beautiful thing.

But to reiterate, I definitely would not do this directly from SQL Server. Just because you can (.NET extended stored procedures) doesn't mean you should.  :-)

Title: Sending emails from server side


答:
You can send email directly from SQL Server, providing you have configured it for sending email. Based on your stated requirements, this may be the easiest method to use. It would also mean less development effort as you wouldn't need to create an application or service to do something that is already built into SQL Server.

If you have several processes that need to send email with some number of processes that are outside of SQL Server, then it might be in your best interest to create/buy an application/service that sends email. If you already have IIS set up on the server machine, you can use it to send your emails.

As for the scheduled task or 3rd party app, I wouldn't do that with what is already available.

Title: Sending emails from server side

Body:
I need to read some of your opinions. I'm developing a desktop app (.net/winform) to keep data in one place. This is used by several clients and the data is stored in MS SQL Server (client-server arch.)

One of the feature is to be able to send notifications via email when conditions met. I've never did something like this so I can't figure out the best way to implement this.

Mails are sent on a daily basis. They don't have attachments nor heavy content. Just plain text.

Send mails directly from SQL? Stored Procedure?

Make a separate app to handle this? (Running on serverside).

Use a schedule task? (Windows Server)

Use a 3rd party app?

Hope anyone know what is the best way to do this.

Thanks for you time & answers.


问:
Web app design: Local caching vs demanding
I'm writing a web application in javascript that will be served to the clients' browser. The intent is for the app to appear to the client as a monolithic application, not a series of interlinked refreshing web pages.

My question deals with common architecture. In order to relate the question I'll mention a specific feature of the web app is a "tour"; when the client clicks a button labeled "tour" the web app will load a div with a bit about the app itself, and what it can do for the user. There are two ways this could be handled, the client browser could fetch the tour markup from the server when the user clicks the button, or the server could download it (and all other such features) when the app is initially downloaded.

If I fetch the tour on demand, then I possibly save network bandwidth as not everyone will take the tour, the app will be smaller too. But this means that in order for someone to fully use the app there will be more network congestion as there will be another hit on the network for loading the tour.

If I just serve all the features initially, the app is larger, but there is less congestion on the network because, once downloaded, there is less need to access the network (unless a fresh copy of the app is required (ie if-modified-since).

This 'tour' feature isn't really the issue itself, it's just an example to explain my question. How to balance caching vs demanding in web app design?

答:
When you start discussing caching, there will be lots of opinions. No one outside your development team will be able to speak in certainties about your application. I would like to offer some guidelines to help you make your decision based on facts.

How to break down your application

You will have lots of different "containers" on any given web page. These could also be called views, segments, sections, or any number of other names. The information or actions performed in a container are where you want to start looking at breaking down a web page.

What to not cache

When you have a container (like your tour example) that will not be used frequently, you might not want to cache it as it will add to the page size and load time every time the page is loaded or reloaded. Even if this is a small size, it can add up over millions of page views to a size that might cause you distress. The reduced load on the server will make your web site perform better.

What to cache

A container that is used frequently is something you should cache. Suppose you have a survey to get information from your users. The questions of the survey will not change during a session under normal circumstances, so even if you change which questions are displayed in the container, caching the questions will save you bandwidth on the server. It will also help your page to appear to perform better.


问:
New and old technologies coexist in legacy system
New technologies can accomplish existing tasks in more efficient and powerful way. But sometimes old technologies cannot be discarded unfortunately, so  more numbers of technologies in one system make maintain difficult. Is it worth to introduce new technologies?

For instance, a legacy system uses SOAP internally and JSON is new technology to replace the SOAP. The problem is JSON can only replace some of SOAP, because the rest of SOAP is too complex to replace. As a result, the system will use both SOAP and JSON at same time. The maintain is even more difficult than before.

Is it reasonable to introduce new technologies to replace part of old ones?

答:
the problem is there already:

Personally, I don't consider increased maintenance difficulty to be that relevant in the light of modern projects, which already contain dozens of technology-buzzwords (polyglot programming, databases, what-have-you). At the same time, I would not expect anyone new to the project to be able to perform maintenance easily. They will not get around learning about these technologies anyways.

not everyone needs to know it all:

Now of course, the learning part could be reduced by not introducing yet another technology. However, it's not as bad as it sounds, because large legacy systems (and they are typically large, as they would simply be rewritten otherwise) are usually changed only in this part or that to fix a bug, or add a new feature. And you don't have to understand everything else for doing that either.

getting better is a must:

The point most strongly in favor of adding new technologies is that you simply cannot afford to stay with outdated technologies. If this legacy system is worth anything to your company, then it will most likely not go away in the next 5-10 years. What really makes maintenance extremely hard is to use only old technologies. It's not just that new ones make your life easier, but just imagine you had to maintain this whole system in Assembler. Now also consider that the lead engineer who knows it all may no longer be there (hit by bus, got better offer, whatever the reason) - can you still find people on the market who know this old thing X? Even just looking at today's market, you will find that especially new graduates (who are the easiest and cheapest to hire) will typically have at least some JSON experience, but only very few will have seen SOAP.

Additionally, the time that new technologies save is just as relevant, because time-to-market is key in most of today's markets. If you stick to old technologies and it simply takes that much more effort, you will need that much longer - which at some point reads as too late. At that point, you will have a legacy system, that you cannot do without, but that you also cannot improve and adapt fast enough - in other words: everything that depends on this system will slowly go down the drain.

define a roadmap:

Finally, it is important to have a sort of roadmap considering your system's technologies and that all team members are fully aware of it. If you decided that JSON replaces your SOAP, but you cannot do it yet, then at least make sure that everyone knows, that new stuff should be done with JSON and not SOAP. That way, depending on the size of features you're adding, you can incrementally replace more and more subsystems that used SOAP up to a point, where you can eventually define an ETA for how long it would take to remove SOAP completely from the system. Depending on the business-criticality of the system, you may also want to assign time solely for progressing on your technological roadmap. You will call it cleaning up the system's dark and dusty tech corners - to managers it will be known as ensuring the system's competitive basis and making it future-proof.


问:
Is the following example a strategy pattern?
In my problem I had lots of objects with slightly different behaviour, but identical attributes and methodes with identical interfaces. The objects variants were quite big in number, and I didn't want to create a class for each of them, with lots of repeting code.

I circumvented creating a lot of derived classed by the following construct (pseudocode for abbrevation)

```<code>#aTP = all the parameters
def _function_version_1(aTP):
    ...

...

def _function_version_BIG(aTP):
    ...

class BaseClass(object):
    _typesOfImplementation = {'ONE' : _function_version_1,
                               ...
                              'BIG' : _function_version_BIG,
                             }

    def __init__(self, type, ...)
        ...
        if type not in _typesOfImplementation:
            raise Exception('Unknown type')
        # respective function for this object
        self.function = lambda aTP:BaseClass._typesOfImplementation[type](self, aTP)
</code>```

Is this still an implementation of the strategy pattern, although I didn't use classes for the respective function version (which would have been an awful bunch of classes again)?

答: I would say no. One of the key points of strategy pattern is ability to add new types of strategies without having to change the base class. In your case, you would need to add new item into _typesOfImplementation, thus changing the base class. Also, with strategy pattern, you can change the strategy during the base class's lifetime. Your code has the strategy hard-wired during the base's construction.


答:
What do I need to do to help my, apparently, limited imagination come up with ways that my project could possibly be broken?

Let history be your guide. If your project is well managed then you should have a database of every bug that has ever been fixed in the product along with an analysis of how the bug was found, how it was reproduced, how it was analyzed, and how it was fixed.  That is not a write-only database. Read the database, and very soon bug taxonomies will begin to occur to you.

That will give you a good overview of the sorts of things that go wrong in your product. If you are interested more generally in what goes wrong in all kinds of software, particularly with an emphasis on security-impacting defects, I suggest that you read the CWE list: http://cwe.mitre.org/data/index.html

Title: Learning to investigate bugs


问:
'Save' button in our web app ( 20-30 textboxes), client is worried that users will forget to click it and lose their data
I am in a meeting with a client later on, regarding an ASP.NET web app we are creating for him. The app includes a lot of 'form' style screens with 20-30 textboxes, and of course a 'Save' button that posts back to the server and saves the data.

The client really does not like this as he is worried users will forget to click 'Save' and lose their data.

While I obviously understand that we can use AJAX to save as the user goes along, I believe this is beyond the scope of the project and is prone to error.

Has anyone dealt with clients like this?

答:
In this day and age of Google Docs auto-updating the server with data as you type, I don't think its unreasonable to have 30 textboxes being written to the server periodically (or even every time the user changes focus from one to another).

You could use ajax, but my preferred solution would be to open a websocket to the server and just send the relevant textbox data everytime the user enters text in one.

In dealing with the client - its not beyond the scope of the project as this is part of his requirements, hence it is in scope. Be glad you have a progressive-thinking client who wants to enhance the capabilities of web interaction like this and embrace the challenge.


答:
Why do you assume you're right and your customer is wrong?

Either you have enough knowledge in UX field; in this case, it won't be difficult for you to find the reason why, in the particular case of the app you're working on, having a Save button is a must-have, and how to explain that in non-technical terms to the customer.

For example, you may be in a case where the end user don't want his changes to be seen immediately online, and it can make sense to spend a good amount of time changing the content before pushing the Save button. It's exactly what happens right now: I'm editing my answer, and I while it's possible technically to make the changes visible to everyone in real-time (through WebSockets), Stack Exchange let me decide when I consider my answer is finished and should become visible to the public.

Or there is a technical constraint making it either difficult, or impossible to implement an AJAX solution. Here again, explain it to the customer, explain the additional cost, and let the person decide.

For example, adding AJAX to every form at this stage would have an additional cost of $20,000. While you consider that the ROI of this change is particularly low, your customer may have a very different opinion on the subject.

Don't plainly assume customers are wrong, especially if you need to ask on a Q&A website for arguments to support your point of view.

There are cases where customer' mistakes are obvious: in those cases, it may not be easy to find how to explain the error to the customer, but at least the arguments under their technical form are abundant and obvious. As a professional, it's up to you then to guide your customer to a better solution.

Example:

Customer: I was reading that in order to avoid issues with Unicode, data should be stored in Base64. Please, can you store everything in the database in Base64?

You: Base64 increases the size of the data with a ratio of 4:3. This means that for every 3 GB of data, you'll actually store waste 4 GB of space. Also, storing the data in this format will make it much more difficult to manipulate the data by hand during the debug and testing phase. Finally, I'm using Microsoft SQL Server and a C# application; both have a good support for Unicode. I also worked on this project and that one which used Unicode extensively, so I know pretty well how to handle Unicode and avoid the usual pitfalls.

There are also cases where your opinion differ from customer's one, and none is right or wrong. In such case, remember that:

Customer has the last word on the requirements.

You have the last word on the price.

Example:

Customer: Great. Finally, I want it to be done in PHP.

You: Frankly, I don't enjoy PHP too much. Ruby or Python can do the job too, and your server is fully compatible with both.

Customer: I know. But I still prefer you do it in PHP.

You: Is it because you have somebody in your company who knows PHP better?

Customer: No. But several programmers I know told me PHP is great.

You: Ok. But since I program mostly with Ruby and haven't used PHP for the last four years, I'll have to spend some time relearning stuff, and I would be a bit slower than if I were coding in Ruby. Is it ok for you to increase the cost of the project from $25,000 to $28,500, and move the deadline from August 10th to September 10th?

Title: 'Save' button in our web app ( 20-30 textboxes), client is worried that users will forget to click it and lose their data

Body:
I am in a meeting with a client later on, regarding an ASP.NET web app we are creating for him. The app includes a lot of 'form' style screens with 20-30 textboxes, and of course a 'Save' button that posts back to the server and saves the data.

The client really does not like this as he is worried users will forget to click 'Save' and lose their data.

While I obviously understand that we can use AJAX to save as the user goes along, I believe this is beyond the scope of the project and is prone to error.

Has anyone dealt with clients like this?


答:
I were in the same situation recently where the client didn't want to have the Save button, even tho the forms where pretty simple and were all fit into the screen with the Save and Cancel button.

I managed to make a simple form with auto-save feature and conduct a test with couple of their real-world users and the conclusion was more than 30% of times those people change their mind after editing the data -- want to cancel edits, and almost 80% of them didn't notice in the beginning that it is an Auto-save form.

So the main arguments here are:

You need an Undo feature, because people might change their mind or edit the wrong filed, etc.

You need a Cancel All Edits feature, for the same reason as above -- imagine if you have changed the profile data of another client and you realize it after you have edited couple of fields.

The final solution that we came up with was:

To have a small notification when anything saved on the server,

And an Undo button next to the notification,

Plus a Cancel Edits button which resets all the edits and loads the fresh version -- before any edits, however this is available only if you don't finish and leave the page. After that data is permanently updated and you won't be able to rollback at all.

As it was a Node.js app, I used Socket.io, but that's perfectly possible with Ajax as well. Also for the Cancel Edits I just simply kept a copy of form data in JSON format, so it's kind of a hard-copy of the form-data that won't be edited at all, so anytime the user changes their mind, they can simply rollback to the fresh data that were initially loaded into the form. As I said again, you will lose this data after you leave that form.


答:
This is a priorities thing.

There are two competing priorities.

Users losing their data, and either having to retype everything, or becoming frustrated and aborting the process. This is potentially a CRITICAL ISSUE in a sales app, because "aborting the process" in this case means not paying the client.

Errors creeping in due to saving unwanted data, and costs associated with server load. This may or may not be a critical issue, depending on the robustness of the system, the amount of load involved and the amount of money being thrown  around. (I would note that a Save button in no way protects you from either of these issues, as people generally save incorrect information and if you lose their data and they re-start, that's also server load)

The weight you give to these priorities is up to the client. If they simply don't realise that your solution will solve their problem to their satisfaction, it is your job to demonstrate to them that it will. If your solution treats their concern as "not a real problem", then you have misunderstood your job. Your job is to solve their their real-world problem ("Somebody has to supply us with 30 different items of data, and they'll throw their computer out the window if they fill in 29 items and then it gets lost when their browser crashes. And more importantly, they won't buy from us.") Unless you solve that problem, you're not doing your job.

The key thing to do here is prototype. If your preferred solution is easy to prototype, you prototype it and you can either show the client how you solve their issue, or they can show you how your solution doesn't solve their issue. If it isn't, you are "preferring" a solution that is difficult to code and doesn't necessarily do what the client wants. Don't prefer that, it is not preferable.


答:
In my experience of Agile, the development team as a whole is handed less responsibility than your examples imply, leaving the lead developer and architect to co-ordinate top level design choices, but handing down lower level design to the agile team as a whole.

So, the lead developer remains responsible for system architecture and technology choices. This is very important: although agile encourages emergent design and refactoring this should be happening at the level of code objects. The system as a whole needs to have greater level of pre-design and rigidity else the project risks becoming an uncoordinated mess.

In our project the lead developer mandated the technology choices, and designed how system components would interact with one another. Agile planning meetings focussed on how to design those components within his higher-level mandates. As a pleasant aside, this keeps a scope cap on otherwise tiresome planning meetings.

He also functioned as the point of last resort. When individual programmers ran into problems that they were unable to fix, they would go to the lead and the final responsibility for getting things fixed was his.

Title: What is the role of the lead developer in an agile team?

Body:
In a non-agile development team a lead developer generally:

Sets the standard (coding and otherwise)

Researches new technologies for the team

Sets the technical direction for the team

Has the final say on matters

Designs the architecture of a system

However an agile team works differently:

An agile team will rely on emergent design, rather than up front

An agile team designs together, rather than design being dictated by one person

An agile team decides on their own technical direction, which is best to deliver a project

Where does this leave a lead developer in an agile team? Is it possible to have a lead developer in an agile team? Does a agile team demand different responsibilities from a lead?


问:
Organizing uncommented, dirty code?
I would like to ask you some questions about dirty code. There are some beginners who coded on a medium project. The code is a very huge ball of mud. They are not advanced programmers. They just know how to use keyboard an a little about java. They just wrote code with 12 000 lines in their main class, though, 6 000 lines belongs to NetBeans itself.

My job is to analyze the code and suggest a good way to maintain the code. My idea is to scrap the project and start a new one with OOP methodology. Recently I collected some notes and ideas about the problem, from this site and some others.

Now, I have the followings questions:

Should we repair the code, and change it to a OOP? We are now debugging it.

The code has no comments, no documentation, no particular style of programming, and so forth. Changing it is really expensive and time consuming. What do we can do about this?

How can I teach them to follow all the rules (commenting, OOP, good code quality, etc.)?

The code is erroneous and error prone. What can we do? Testing? We almost write two or three A4 papers for correction, but it seems endless.

I should have to say that I am new with them. I think I have broken the rules about adding people too late to the project, as well. Do you think I have to leave them?

答:
I would re-write it completely. Sometimes it is impossible to repair such a code. Another option is to make it working, without adding any new features. To teach the team to write good code (well designed, documented, with tests) let them to fix the code you have now. Let everybody to fix bugs/review the code of other developers, not her/his part. After some attempts they will understand that it is almost impossible to review/fix such codes.

Adding people to late projects helps very rarely. Usually it breaks deadlines. You should do everything you can to finish the project successfully, and then think about leaving.

Title: Organizing uncommented, dirty code?

ContentLicense: CC BY-SA 2.5


问:
Responding to app feature requests I'm not going to implement
I'm a new app developer and after like 20 downloads of my app (free and ad-free) I already got two feature requests, and I'm not going to implement either.

Should I respond to these feature requests and if so, how? I'd prefer not responding at all because I'd rather spend the time to work on my app, but being a new developer, a couple of poor ratings in the app store could hurt my app.

答:
Any of this requests, even if you don't planed to implement this feature before is a signal directly send to you. It is annoying, and it is gold. Sometimes you have to wait before you take a decision : if you got only one person asking for something, you could certainly argue that your application shouldn't implement this feature, but if dozens of them ask for the same thing after some time, it could make you think about your own design (and you should).

So I believe an answer is always preferable, because you can't care of your product without caring this feedback. The simplest thing is only to answer that any suggestion is welcome and that it's precious for you, even if everything can't be implemented, it will not be ignored.

and I'm not going to implement either

You have to think about it, and decide which things you could maybe implement, even if you don't planed it before because it could be good ideas, or it could help you to make evolve your primary design.


问:
Is there a performance difference between ++x over x++?
Is there a performance difference between using ++x over x++ increment operators?

I've see developers use ++x in loops where I would normally write x++ out of habit.

For example;

```<code> for(int x=0; x < 10; ++x)
</code>```

There would be no difference in the results between ++x or x++. So I'm wondering if there is a reason some people do it this way.

Now I know the increment operator is handled internally differently depending on the language.  So if there is a difference in performance for PHP, Java, C#, C++ or JavaScript. I'd like to know which language.

答:
For simple integers; NO, any decent peephole optimizer will see the value isn't used and use the best option available.

For more complex (overloaded) types in C++ (like iterators); possibly, the pre and post increment expand to different methods which may be completely different. Typically the post increment need to make a copy of itself before incrementing.


答:
No, there is no consistent performance difference between these operators that holds true across a range of languages.

In most languages I would expect them to behave identically, down to the point of generating identical code. The reason is that each produces the identical outcome, and provided the compiler writer is on the job, it's relatively to perform peephole optimisation on this case with no risk of undesirable side-effects. There is simple no reason for one of them to be slower, if the compiler writer is up to scratch.

Having said that, some of those languages compile to intermediate code and it is possible that the two constructs target different intermediate code. In this case there might be a small difference in performance, but it would not be easy to predict which is faster.

If you really care, you will have to benchmark each construct on each target language. Even if you find there is a difference, I suggest you ignore it and simply write the code that feels natural and looks right. Any performance difference will be infinitesimal.

Title: Is there a performance difference between ++x over x++?

Body:
Is there a performance difference between using ++x over x++ increment operators?

I've see developers use ++x in loops where I would normally write x++ out of habit.

For example;

```<code> for(int x=0; x < 10; ++x)
</code>```

There would be no difference in the results between ++x or x++. So I'm wondering if there is a reason some people do it this way.

Now I know the increment operator is handled internally differently depending on the language.  So if there is a difference in performance for PHP, Java, C#, C++ or JavaScript. I'd like to know which language.


答:
In terms of the logical evaluation of the loop, there is of course no difference, so the question is: can you compile ++x into something more efficient than x++ ?

And yes, indeed you can if you look close enough. In order to perform the increment on the variable, you need to load its value onto the stack (or a register, or wherever - for the sake of simplicity, I'll just keep saying stack), then perform the increment operation. Your stack will then contain the incremented value at the top. That's the same for both ways though, so why is there a difference?

It does make a difference, once you start using these expressions in larger ones. Consider f(++x) and f(x++). In order to create code that performs the function call, you need to place its argument onto the stack. Now if the argument is x++, then you place x on the stack and call the method, which removes its arguments from the stack again. The problem is that after all of this, you need to again load x onto the stack in order to perform the increment operation.

That being said: while using ++x may give you a few CPU cycles of performance, this is absolutely not the sort of performance difference that you should even have on your radar.

In addition, as ratchet freak pointed out, the ++ operation itself can be overloaded in some languages, resulting in vastly more complex behaviors and even differing results. However, in these cases, I consider it a criminal act to inline these operations (or in case of different results to even define them as such). And once you consider the statement x++ or ++x in isolation, there's nothing interesting to be said about performance anymore anyways.


问:
How can I explain object-oriented programming to someone who's only coded in Fortran 77?
My mother did her college thesis in Fortran, and now (over a decade later) needs to learn c++ for fluids simulations. She is able to understand all of the procedural programming, but no matter how hard I try to explain objects to her, it doesn't stick. (I do a lot of work with Java, so I know how objects work) I think I might be explaining it in too high-level ways, so it isn't really making sense to someone who's never worked with them at all and grew up in the age of purely procedural programming.

Is there any simple way I can explain them to her that will help her understand?

答:
I would like to add my contribution as a reminder of the distinction between programming paradigms and programming languages that implement these paradigms.

So, in my opinion, the best way to explain object orientation with C++ to a F77 user, would be to proceed in a stepwise fashion:

First, introduce the user to the concept of object orientation in a familiar setting by showing her how to develop object-like structures in Fortran 77 - for instance, have a look at papers like B. Patton "Object-oriented Fortran 77 (a practitioner's view)" SIGPLAN Fortran Forum 12, 2 (1993), pp. 23-24, and references therein.

Then, establish a correspondence between those structures and C++ classes and methods.

Finally, discuss additional features that C++ can provide to facilitate OO programming.


答: Personally, I wouldn't start this project until I have a copy of Working Effectively with Legacy Code handy.  Seriously, it was written for exactly this type of thing.  It's full of strategies for dealing with tricky code, and goes into far more detail than I can give you here.</p>

Title: Organizing uncommented, dirty code?

Body:
I would like to ask you some questions about dirty code. There are some beginners who coded on a medium project. The code is a very huge ball of mud. They are not advanced programmers. They just know how to use keyboard an a little about java. They just wrote code with 12 000 lines in their main class, though, 6 000 lines belongs to NetBeans itself.

My job is to analyze the code and suggest a good way to maintain the code. My idea is to scrap the project and start a new one with OOP methodology. Recently I collected some notes and ideas about the problem, from this site and some others.

Now, I have the followings questions:

Should we repair the code, and change it to a OOP? We are now debugging it.

The code has no comments, no documentation, no particular style of programming, and so forth. Changing it is really expensive and time consuming. What do we can do about this?

How can I teach them to follow all the rules (commenting, OOP, good code quality, etc.)?

The code is erroneous and error prone. What can we do? Testing? We almost write two or three A4 papers for correction, but it seems endless.

I should have to say that I am new with them. I think I have broken the rules about adding people too late to the project, as well. Do you think I have to leave them?


问:
Implicit OAuth2 endpoint vs. cookies
I currently have an app which basically runs two halves of an API - a restful API for the web app, and a synchronisation API for the native clients (all over SSL).

The web app is completely javascript based and is quite similar to the native clients anyway - except it currently does not work offline.

What I'm hoping to do is merge the fragmented APIs into a single restful API. The web app currently authenticates by issuing a cookie to the client whereas the native clients work using a custom HMAC access token implementation. Obviously a public/private key scenario for a javascript app is a little pointless.

I think the best solution would be to create an OAuth2 endpoint on the API (like Instagram, for example http://instagram.com/developer/authentication/) which is used by both the native apps and the web app.

My question is, in terms of security how does an implicit OAuth2 flow compare (storing the access token in local storage) to "secure" cookies? Presumably although SSL solves man in the middle attacks, the user could theoretically grab the access token from local storage and copy it to another machine?

答:
The advantage of OAuth over a cookie is that it allows you to provide access to a third party service (like facebook does with their apps) without divulging the end user's credentials, and it allows the user to later revoke that access without needing to change their own credentials.  If third parties are not involved, there is no essential difference in security.

If you provide the user some sort of access token, be it OAuth or a cookie, you have to assume that anyone providing that token is authorized.  There's no way to stop a user from copying either one to another machine, and IP addresses change all the time on the same machine.

What you can do is limit the damage an attacker can do if they happen to intercept one of those tokens.  That means requiring they be periodically renewed, and tracking which tokens are currently valid in such a way that you can tell when a token has been maliciously copied, as in Improved Persistent Login Cookie Best Practice.

Title: Implicit OAuth2 endpoint vs. cookies


答: Not only is it reasonable, it is often unavoidable and indeed can be a useful 'foot in the door' to moving off legacy technologies completely. This is of course assuming that there is a cost benefit to moving off old technologies in the first place, which there may not be.</p>

Title: New and old technologies coexist in legacy system

Body:
New technologies can accomplish existing tasks in more efficient and powerful way. But sometimes old technologies cannot be discarded unfortunately, so  more numbers of technologies in one system make maintain difficult. Is it worth to introduce new technologies?

For instance, a legacy system uses SOAP internally and JSON is new technology to replace the SOAP. The problem is JSON can only replace some of SOAP, because the rest of SOAP is too complex to replace. As a result, the system will use both SOAP and JSON at same time. The maintain is even more difficult than before.

Is it reasonable to introduce new technologies to replace part of old ones?


问:
Session states in ajax callback
Someone told me Session or HttpContext.Current.User will return different value when we are working with ajax postback, in case of when the are so many user are live to site.

For example, suppose there are 1000 people are online in site, and from them 100 call ajax method/ wenmethod and on this we might get different value of Session or HttpContext.Current.User as per every user's Session or HttpContext.Current.User value are different.

But my concept says it will return specific person's (who requested) Session or HttpContext.Current.User value, and server will be clear whose value need to be return.

What you all guys says?

答:
The session ID is stored in a cookie (or in the query string if so configured). It's unique per browser session.

ASP.NET provides session-state management to enable you to store information associated with a unique browser session across multiple requests.

For each request, the session ID cookie is referenced and the session for that unique ID is populated.

Additional information can be found on the HttpSessionState Class Page under the Remarks section.

Title: Session states in ajax callback


问:
DDD - Domain Driven Design, which development order should be applied?
1 - Design my entities, ie (in python):

```<code>class Account:
    def __init__(name, author):
        self.name = name
        self.email = email
</code>```

2 - Design my repositories: (as interface)

```<code>class AccountRepository:
    def add(self, account):
        """ @type account Account """
        pass

    def find_by_name(self, name):
        pass

    def find_by_email(self, email):
        pass

    # remove, and others...
</code>```

Now, I can go two ways:

A: Design and implement my domain services:

```<code>class SignUpService:
    def __init__(self, account_repository):
        """ @type account_repository AccountRepository """
        self._account_repository = account_repository

    def create_account(self, username, email):
        account = Account(username, email)
        self._account_repository.add(account)

    # other methods that uses the account_repository
</code>```

B: Implement my Repositories Strategies:

```<code>class MongodbAccountRepository(AccountRepository):
    def __init__(self, mongodb_database):
        self._mongodb_database = mongodb_database

    def add(self, account):
        account_data = account.__dict__
        self._mongodb_database.accounts.insert(account_data)

    # and the other methods
</code>```

Which is the correct order? and why? 1, 2, A, B or 1, 2, B, A?

Thank you so much!

答:
On one level you've answered your own question. Your SignUpService is using an AccountRepository, so you'll need at least some repo implementation just to basic testing. On a practical level, though, you're likely to see more churn in your services as you come to grips with your domain, so that's where you'll probably need to spend more time.

So if you're looking for a rule of thumb, I'd say to first get a working repository implementation. It doesn't have to be your "production" version, but it should be able to drive the system. Then get your services and the rest of the domain correct. The domain model - not the storage layer - is where the value in DDD comes from, so get that right and let that inform your choice of storage backend, not the other way around.


答:
There are many variables that should be considered when deciding to add new technologies to a legacy application.

First, what is the long term plan for this application?  Is there a plan with money and a date to retire it?  If so, does the new technology being introduced relate to whatever is replacing the old app?  If so, great, go ahead.  If not, then why are you introducing this technology?  Old apps aren't playgrounds -- they're usually serving a critical purpose in an organization (they're often the first apps that were built at a company and consequently are critical to the company's financial health).

Second, what is the learning curve of the new technology?  Are your people ready for it?  For example, let's say you've got an old application written in COBOL/IMS/CICS.  It's rather unlikely that you'll be able to quickly transition the people who are working on that to say HTML5/CSS3/Javascript/JSON/REST/NoSQL in a short period of time.  So, what's your workforce strategy?  Do you have one?  It can't be "they'll learn it as they go".  That's irresponsible and likely to result in staff churn.

Third, do you know where this new technology is in its Diffusion of Innovation stage?  Probably the WORST thing you can do to a legacy application is burden it by grafting it with a "new" technology that's already at the late majority or laggard stage of adoption.  Why?  Because two years from now it'll have TWO old dying technologies under its umbrella, so you actually made it worse.  Try to restrict your technology introductions to things at the early adopter or early majority stage.

Fourth, how many people are HONESTLY contributing to the health and welfare of the new technology?  If you go to GitHub for example, how frequent are commits being made, and how substantial are those commits?  Again, don't burden a legacy app with a dying technology just because it's "new to you".

There are probably many other things to consider, but those are some that come to mind based on my years as an architect making those kinds of decisions.