答:
I do not think encrypting all the data in the database is a good idea, as it will be a major performance issue (especially when it comes to searching).

Instead I'd suggest to implement application level security for users, and encrypt the database files from the operating system level or store them in encrypted file container such as (veracrypt / truecrypt)

But if you are willing to accept reduced performance (and relatively complex logic),

```<code>say you have 2 records in the database (A,B) and 3 users (Admin,User1,User2)
A -> Admin and User1 can access
B -> Admin and User2 can access
</code>```

In this scenario, to access record A a key needs to be used which Admin and user1 has access to while for record B key needs to be shared among Admin and user2. The issue is now admin has 2 keys and when admin tries to access record A he needs to know which key to be used.

To solve this, system needs to keep list of keys and needs to record which key used to encrypt the record. This again is a security threat, as if someone managed to gain access to database it's easy enough to find keys and decrypt data.

So although not perfect solutio it looks like this,

```<code>EncryptionKey
{
int KeyId;
string Key;
}

User
{
int UserId;
List<EncryptionKey> EncryptionKeys;
}

SomeUserRecord
{
    //encryption and decryption can be done in both db and application level depending on   the algorithm used
    string EncryptedField1;
    string EncryptedField2;
    int EncryptionKeyId;
}
</code>```

Title: Encrypting stored data for multiple unique users to access information

Body:
Developing a database for many users, and thousands more "people" in the database, one section requires we encrypt the personal data - Youth's information, medical information, etc.

We have users who are able to access the personal data on people within their control, but we are thinking that we will need to also encrypt the data when it's stored on our server. I believe that if I use each user's salted passwords to encrypt the data, only that user can access the data (not good). If I have one master key, then it would need to be stored outside of the application to access the data.

Are there techniques that can encrypt the data in such a way that a data breach on the server won't show the data in the database in clear text, but that multiple users of certain permissions can decrypt the data they need?

Must encrypt the data in the database

Multiple users may need to access the same encrypted data, based on their permissions

Cannot be derived from the user's passwords (since some users may leave or change, requiring access to be removed/edited/added)

HTTPS is already getting used, and I understand encrypting data client-side is a Bad IdeaTM

If it matter: MySQL is the database system

Body:
I do not think encrypting all the data in the database is a good idea, as it will be a major performance issue (especially when it comes to searching).

Instead I'd suggest to implement application level security for users, and encrypt the database files from the operating system level or store them in encrypted file container such as (veracrypt / truecrypt)

But if you are willing to accept reduced performance (and relatively complex logic),

say you have 2 records in the database (A,B) and 3 users (Admin,User1,User2)
A -> Admin and User1 can access
B -> Admin and User2 can access

In this scenario, to access record A a key needs to be used which Admin and user1 has access to while for record B key needs to be shared among Admin and user2. The issue is now admin has 2 keys and when admin tries to access record A he needs to know which key to be used.

To solve this, system needs to keep list of keys and needs to record which key used to encrypt the record. This again is a security threat, as if someone managed to gain access to database it's easy enough to find keys and decrypt data.

So although not perfect solutio it looks like this,

EncryptionKey
{
int KeyId;
string Key;
}

User
{
int UserId;
List<EncryptionKey> EncryptionKeys;
}

SomeUserRecord
{
    //encryption and decryption can be done in both db and application level depending on   the algorithm used
    string EncryptedField1;
    string EncryptedField2;
    int EncryptionKeyId;
}


问:
What's the tradeoff for type inference?
It seems that all new programming languages or at least the ones that became popular use type inference. Even Javascript got types and type inference though various implementations (Acscript, typescript etc). It looks great to me but I'm wondering if there are any trade-offs or why let's say Java or the old good languages don't have type inference

When declaring a variable in Go without specifying its type (using var without a type or the := syntax), the variable's type is inferred from the value on the right hand side.

D allows writing large code fragments without redundantly specifying types, like dynamic languages do. On the other hand, static inference deduces types and other code properties, giving the best of both the static and the dynamic worlds.

The type inference engine in Rust is pretty smart. It does more than looking at the type of the r-value during an initialization. It also looks how the variable is used afterwards to infer its type.

Swift uses type inference to work out the appropriate type. Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide.

答:
In C#, type inference occurs at compile-time, so the runtime cost is zero.

As a matter of style, var is used for situations where it is either inconvenient or unnecessary to manually specify the type.  Linq is one such situation.  Another is:

```<code>var s = new SomeReallyLongTypeNameWith<Several, Type, Parameters>(andFormal, parameters);
</code>```

without which you would be repeating your really long type name (and the type parameters) rather than simply saying var.

Use the actual name of the type when being explicit improves code clarity.

There are some situations where type inference cannot be used, such as member variable declarations whose values are set at construction time, or where you really want intellisense to work properly (Hackerrank's IDE won't intellisense the variable's members unless you declare the type explicitly).

ContentLicense: CC BY-SA 3.0

Title: What's the tradeoff for type inference?

Body:
In C#, type inference occurs at compile-time, so the runtime cost is zero.

As a matter of style, var is used for situations where it is either inconvenient or unnecessary to manually specify the type.  Linq is one such situation.  Another is:

var s = new SomeReallyLongTypeNameWith<Several, Type, Parameters>(andFormal, parameters);

without which you would be repeating your really long type name (and the type parameters) rather than simply saying var.

Use the actual name of the type when being explicit improves code clarity.

There are some situations where type inference cannot be used, such as member variable declarations whose values are set at construction time, or where you really want intellisense to work properly (Hackerrank's IDE won't intellisense the variable's members unless you declare the type explicitly).


答:
Good question!

Since the type is not explicitly annotated, it can at times make the code harder to read - leading to more bugs. Properly used it of course makes the code cleaner and more readable. If you're a pessimist and think that most programmers are bad (or work where most programmers are bad), this will be a net loss.

While the type inference algorithm is relatively simple, it is not free. This sort of thing increases compile time slightly.

Since the type is not explicitly annotated, your IDE can't guess as well what you're trying to do, harming autocomplete and similar helpers during the declaration process.

Combined with function overloads, you can occasionally get into situations where the type inference algorithm can't decide which path to take, leading to uglier casting style annotations. (This happens quite a bit with C#'s anonymous function syntax for example).

And there are more esoteric languages that cannot do their weirdness without explicit type annotation. So far, there are none that I know of that are common/popular/promising enough to mention except in passing.

Title: What's the tradeoff for type inference?

Body:
It seems that all new programming languages or at least the ones that became popular use type inference. Even Javascript got types and type inference though various implementations (Acscript, typescript etc). It looks great to me but I'm wondering if there are any trade-offs or why let's say Java or the old good languages don't have type inference

When declaring a variable in Go without specifying its type (using var without a type or the := syntax), the variable's type is inferred from the value on the right hand side.

D allows writing large code fragments without redundantly specifying types, like dynamic languages do. On the other hand, static inference deduces types and other code properties, giving the best of both the static and the dynamic worlds.

The type inference engine in Rust is pretty smart. It does more than looking at the type of the r-value during an initialization. It also looks how the variable is used afterwards to infer its type.

Swift uses type inference to work out the appropriate type. Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide.


问:
How useful are IT headhunters/recruiters when looking for a new job?
Since they exist for several fields with varying degrees of usefulness, I'm curious as to the reputation of headhunters/recruiters that focus solely on IT professionals (e.g. programmers, software engineers, CIOs, etc) when it comes to finding a new job.

Are they actually useful or is it fairly hit or miss? Does the old adage of only working with a limited number apply or can you safely give you resume/CV to several of them?

答:
My experience from the last 23 years around San Francisco and Silicon Valley has been:

Very few recruiters have any idea about technology, or how to make a really good fit between you and an employer. They mostly look for buzzword matches between job listings and resumes.

Despite that, they're a great way to get in the door lots of places that would pay no attention if you sent your resume directly.

Most tech job openings are not advertised - maybe 80%. You can only find out about them through recruiters.

It's normal to give your resume to many headhunters around here. In fact, if you post it to sites like DICE or Monster, they'll get it anyway.

Companies often give the same opening to several headhunters. You need to insist they tell you who the company is before presenting your resume, because it can look bad if multiple recruiters submit you for the same opening.

The very best recruiters usually wind up getting hired away from the job shops to work in-house for places like Google or Apple.

I've found posting my resume to DICE, and a synopsis to LinkedIn, to be great ways to get recruiters to contact me with interesting opportunities. If you use DICE and you're actively looking, you want to make a little change to your resume every few weeks to get recruiters looking at it again. Some job shops will download your resume and retain it in their databases; I've gotten phone calls up to three years after deactivating my resume on DICE.

This world changes frequently, and old wisdom rapidly becomes out of date. About three years ago, a friend of mine wound up back in the job market after many years, and tried to do the 1990-style approach of sending his resume to one recruiter who would take a personal interest in getting him employed. After about six months of nothing, he finally took my suggestion to post his resume on DICE. He started a new job within two weeks and was having to fend off recruiters who kept calling him for other positions.

ContentLicense: CC BY-SA 2.5


问:
Potential abuse of observer pattern
I have a MeetingRoom object that contains a list of Employees, there is a function on each employee called SetMeetingDate, this method has to take into account the state of all other employees in the MeetingRoom in particicular the IsReadyForMeeting property.

An individual employee for example can only successfully call SetMeetingDate(Date date) when every employee in the ChatRoom has IsReadyForMeeting set to true.

I have thought about a couple of ways to implement this functionality, I can do something where the employee checks the state of the other employees by going via the MeetingRoom object like this:

```<code>    public void SetMeetingDate(DateTime date)
    {
        if (!MeetingRoom.AllEmployeesAreReady)
        {
            throw new ApplicationException("all employees are not ready");
        }

        MeetingDate = date;
    }
</code>```

which seems to me to have the responsibility in the wrong place.

A second approach that I can use is to set up an observer so that the Employee class will inform the MeetingRoom object that it has set a meeting date and the MeetingRoom class will raise the exception if MeetingRoom.AllEmployeesAreReady is false thus moving the responsibility to the MeetingRoom object and the code for the employee would look like this:

```<code>    public void SetMeetingDate(DateTime date)
    {
        MeetingDate = date;

        Observer.MeetingDateAdded();
    }
</code>```

And the Meeting Room would then have a method like this:

```<code>    public void MeetingDateAdded()
    {
        if (!AllEmployeesAreReady)
        {
            throw new ApplicationException("all employees are not ready");
        }
    }
</code>```

This use of the observer has been met with opposition from other developers in my team and  I can see why but I can't think of a better way to implement the requirement, is there an easy/different approach that can be used in this situation?

答:
This doesn't look like a reasonable place to apply the Observer Pattern.

What I do notice is that all of your examples reference local state, so I assume they are part of some sort of Meeting object.  Consequently, the code

```<code>public void SetMeetingDate(DateTime date)
{
    if (!MeetingRoom.AllEmployeesAreReady)
    {
        throw new ApplicationException("all employees are not ready");
    }

    MeetingDate = date;
}
</code>```

is perfectly valid, since MeetingRoom and MeetingDate are clearly local properties of your "Meeting" class.

If you prefer something a bit more self-contained, then do something like this:

```<code>public static MeetingDate SetMeetingDate(MeetingRoom room, DateTime date)
{
    if (!room.AllEmployeesAreReady)
        throw new InvalidOperationException("All employees are not ready");

    return new MeetingDate(date, room.Employees);
}
</code>```

or somesuch.

Title: Potential abuse of observer pattern

Body:
This doesn't look like a reasonable place to apply the Observer Pattern.

What I do notice is that all of your examples reference local state, so I assume they are part of some sort of Meeting object.  Consequently, the code

public void SetMeetingDate(DateTime date)
{
    if (!MeetingRoom.AllEmployeesAreReady)
    {
        throw new ApplicationException("all employees are not ready");
    }

    MeetingDate = date;
}

is perfectly valid, since MeetingRoom and MeetingDate are clearly local properties of your "Meeting" class.

If you prefer something a bit more self-contained, then do something like this:

public static MeetingDate SetMeetingDate(MeetingRoom room, DateTime date)
{
    if (!room.AllEmployeesAreReady)
        throw new InvalidOperationException("All employees are not ready");

    return new MeetingDate(date, room.Employees);
}

or somesuch.


问:
Which languages are used today for low-level programming?
When I hear low-level programming, such as for drivers, embedded systems, operating systems, etc., I immediately think about C and perhaps C++. But mainly C.

But what other languages are also used for these kind of tasks? Today, I mean, not what has been used.

答:
Ada is still used in safety/mission-critical systems, as it still offers relatively unparalleled safety features.

It was compulsory to use Ada up until the late nineties within the DoD, and some other areas, but is no longer, so is not as heavily used as it once was.  But it can still be found in highly critical uses, avionics, nuclear power, etc.

The modern versions have object orientation and good support for parallel processing, so is entirely useful still.


答:
Haskell's type system is fully inferrable (leaving aside polymorphic recursion, certain language extensions, and the dreaded monomorphism restriction), yet programmers still frequently provide type annotations in the source code even when they don't need to. Why?

Type annotations serve as documentation. This is especially true with types as expressive as Haskell's. Given a function's name and its type you can usually have a pretty good guess at what the function does, especially when the function is parametrically polymorphic.

Type annotations can drive development. Writing a type signature before you write the body of a function feels kind-of like test-driven development. In my experience, once you make a Haskell function compile it often works first time. (Of course, this does not obviate the need for automated tests!)

Explicit types can help you check your assumptions. When I'm trying to understand some code that already works, I frequently pepper it with what I believe to be the correct type annotations. If the code still compiles I know I've understood it. If it doesn't, I read the error message.

Type signatures let you specialise polymorphic functions. Very occasionally, an API is more expressive or useful if certain functions are not polymorphic. The compiler won't complain if you give a function a less general type than would be inferred. The classic example is map :: (a -> b) -> [a] -> [b]. Its more general form (fmap :: Functor f => (a -> b) -> f a -> f b) applies to all Functors, not just lists. But it was felt that map would be easier to understand for beginners, so it lives on alongside its bigger brother.

On the whole, the downsides of a statically-typed-but-inferrable system are much the same as the downsides of static typing in general, a well-worn discussion on this site and others (Googling "static typing disadvantages" will get you hundreds of pages of flame-wars). Of course, some of said disadvantages are ameliorated by the smaller quantity of type annotations in an inferrable system. Plus, type inference has its own advantages: hole-driven development wouldn't be possible without type inference.

Java* proves that a language requiring too many type annotations gets annoying, but with too few you lose out on the advantages I described above. Languages with opt-out type inference strike an agreeable balance between the two extremes.

*Even Java, that great scapegoat, performs a certain amount of local type inference. In a statement like Map<String, Integer> = new HashMap<>();, you don't have to specify the generic type of the constructor. On the other hand, ML-style languages are typically globally inferrable.

Title: What's the tradeoff for type inference?

ContentLicense: CC BY-SA 4.0


答:
It looks great to me but I'm wondering if there are any trade-offs or why let's say Java or the old good languages don't have type inference

Java happens to be the exception rather than the rule here. Even C++ (which I beleive qualifies as a "good old language" :) ) supports type inference with the auto keyword since the C++11 standard. It not only works with variable declaration, but also as function return type, which is especially handy with some complex template functions.

Implicit typing and type inference have many good use cases, and there are also some use cases where you really shouldn't do it. This is sometimes matter of taste, and also subject of debate.

But that there are undoubtedly good use cases, is by itself a legitimate reason for any language to implement it. It is also not a hard to implement feature, no runtime penalty, and does not affect compile time significantly.

I do not see a real drawback in giving an opportunity to the developer to use type inference.

Some answerer reasond how explicit typing is good sometimes, and they are certainly right. But not supporting implicit typeing would mean that a language enforces explicit typing all the time.

So the real draw back is when a language does not support implicit typeing, because with this it states, that there is no legitimate reason for the developer to use it, which is not true.

Title: What's the tradeoff for type inference?


问:
What is a good practical example demonstrating an architectural advantage in interface dependency injection
I need help (preferably by way of a practical example) to understand why/if the following implementation of IoC/DI (in this case using Ninject) provides an architectural advantage:

```<code>using (IKernel kernel = new StandardKernel())
{
    kernel.Bind<ITaxCalculator>()
          .To<TaxCalculator>()
          .WithConstructorArgument("rate", .2M);

    var tc = kernel.Get<ITaxCalculator>();
    Assert.Equal(20M, tc.CalculateTax(100M));
}
</code>```

As far as I can see the pattern doesn't really ensure greater probability of re-use of the interface by using the interface as a DI. We could just as easily achieve a guarantee of interface re-use by plain inheriting the interface within a 'TaxCalculator' class, and we would then have a more simple and readable way of calling a 'CalculateTax method'.

I'm not interested in the unit or integration test benefits of the pattern right now, just a tangible example or even abstract justification of how the above pattern can help to achieve any benefit (for example loose coupling) in a way that can't be achieved without using DI.

答:
You gain a few things by using IoC and DI:

1. Easier replacement of the underlying implementation:

What I mean by this is that you can change the implementation is one place and then safely assume that everything that's injecting your interface is using the new implementation instead.

Today you have

```<code>kernel.Bind<ITaxCalculator>().To<TaxCalculator>()
</code>```

Tomorrow you may have

```<code>kernel.Bind<ITaxCalculator>().To<BetterTaxCalculator>()
</code>```

Using IoC, you have to simply change this one line and everything else will inject the new implementation. Without it, you'd have to go all over your code and change all the classes that are using TaxCalculator to BetterTaxCalculator.

Now this is not always something you'd want to do of course but there may be times that you'd need to do this (specially if you're doing your injections via XML and you want to switch the strategies without changing the code).

2. MUCH easier handling of interdependencies.

Easier to explain with an example. Let's say today this is your class:

```<code>public class TaxCalculator
{
    public TaxCalculator() { }
}
</code>```

Without dependency injection, you create an instance like this:

```<code>var taxCalculator = new TaxCalculator();
</code>```

With:

```<code>kernel.Get<ITaxCalculator>();
</code>```

Tomorrow's implementation:

```<code>public class TaxCalculator
{
    public TaxCalculator(IAdder adder, ISubstractor substractor) { }
}
</code>```

Without dependency injection, you create an instance like this:

```<code>var taxCalculator = new TaxCalculator(new Adder(), new Substractor());
</code>```

With:

```<code>kernel.Get<ITaxCalculator>(); // it's the same!!!! :-o
</code>```

This may be hard to appreciate but in larger apps with many levels of hierarchy, this is a godsend! What this means is that users of my ITaxCalculator do not need to know which interfaces are required to create an instance of a TaxCalculator which means, if I decide to add a new IMultiplier to my constructor in a week, I don't have to touch the code for the users of my API. The only thing they need to change is the part that they setup their DI (by injecting an IMultiplier).

You will most likely only have one place in your entire code that injects your interfaces but may have a lot of places that need an ITaxCalculator which would've needed changing if you weren't using a DIF.

3. Management of the lifecycle of your objects.
 With most DI frameworks, it's very easy to define if you want your objects to be short lived, global singletons or, maximum n instances or any other fancy behavior you want.

I'm sure there are more but these were the ones I could think of for now.

Body:
You gain a few things by using IoC and DI:

1. Easier replacement of the underlying implementation:

What I mean by this is that you can change the implementation is one place and then safely assume that everything that's injecting your interface is using the new implementation instead.

Today you have

kernel.Bind<ITaxCalculator>().To<TaxCalculator>()

Tomorrow you may have

kernel.Bind<ITaxCalculator>().To<BetterTaxCalculator>()

Using IoC, you have to simply change this one line and everything else will inject the new implementation. Without it, you'd have to go all over your code and change all the classes that are using TaxCalculator to BetterTaxCalculator.

Now this is not always something you'd want to do of course but there may be times that you'd need to do this (specially if you're doing your injections via XML and you want to switch the strategies without changing the code).

2. MUCH easier handling of interdependencies.

Easier to explain with an example. Let's say today this is your class:

public class TaxCalculator
{
    public TaxCalculator() { }
}

Without dependency injection, you create an instance like this:

var taxCalculator = new TaxCalculator();

With:

kernel.Get<ITaxCalculator>();

Tomorrow's implementation:

public class TaxCalculator
{
    public TaxCalculator(IAdder adder, ISubstractor substractor) { }
}

Without dependency injection, you create an instance like this:

var taxCalculator = new TaxCalculator(new Adder(), new Substractor());

With:

kernel.Get<ITaxCalculator>(); // it's the same!!!! :-o

This may be hard to appreciate but in larger apps with many levels of hierarchy, this is a godsend! What this means is that users of my ITaxCalculator do not need to know which interfaces are required to create an instance of a TaxCalculator which means, if I decide to add a new IMultiplier to my constructor in a week, I don't have to touch the code for the users of my API. The only thing they need to change is the part that they setup their DI (by injecting an IMultiplier).

You will most likely only have one place in your entire code that injects your interfaces but may have a lot of places that need an ITaxCalculator which would've needed changing if you weren't using a DIF.

3. Management of the lifecycle of your objects.
 With most DI frameworks, it's very easy to define if you want your objects to be short lived, global singletons or, maximum n instances or any other fancy behavior you want.

I'm sure there are more but these were the ones I could think of for now.


问:
Which open-source license is right to keep some advantage for me AND for the developer-community?
I know that this question has been asked a many times but there are at least that much different answers.

I'd like to release a software, i developend for about a year. So i would like to keep some advantages of this. The software generates some kind of infrastructure for app-development.

Anyway it would be great if other people could use and improve this software too.

Which license would be best for this project to get the best out of both sides (proprietary and open-source)?

Which kind of advantage provides the license?

Thank you very much.

答:
Copyright licenses specify if and under which conditions you can make modifications to something that is created by someone else and if and under what conditions you can distribute the original or modified versions.

The default copyright 'license' is "all rights reserved", which means that only the original author is allowed to make changes and distribute copies.

Copyright licenses can restrict how you are allowed to use a program, but such restrictions are not accepted in open-source licenses. Having such a restriction in your license automatically makes it a proprietary license.

Open source licenses come in various flavors and choosing one is often a matter of what appeals to you.

Strong copyleft licenses (like GPL) are based on the ideal that everyone should have the liberty to change/enhance the software that they received a copy of and to distribute those changes. If you distribute software under the GPL license, the source code for the entire application must be available. If someone distributes changes to a GPL program, then those changes must also be distributed under the GPL license (so, including all sources).

Weak copyleft licenses (like LGPL) are like strong copyleft licenses, but have dropped the requirement that the source code for the entire application must be available. When you distribute code under the LGPL license, the sources for that code must be available and changes to the code must also be released under the LGPL.

If someone wants to use LGPL licensed code in their product, then they must provide a means for their users to replace the LGPL code portions. This is typically done by having the LGPL code in a dynamically linked library.

Permissive licenses (like MIT, BSD or Apache License) typically lack the requirement that when changes are made, that then the source code for those changes also must be published. They can even allow one to distribute the changed version under a completely different (possibly closed-source) license.

As sole author of the software, you are in the special position that you can choose under which license terms to release the software and even to use different licenses when releasing it to different people. Once you start accepting contributions, those contributions are provided to you under the license terms that the contributor received your software under and you are now also bound by those license terms.

For example, if you have two versions of your software, one licensed under the GPL and the other under a closed-source license, and I contribute a change to the GPL version, then my contribution is also under the GPL license and you can't use it in the closed-source version without my consent to change the license.

As your application appears to be generating code, where a significant portion of the output is code that you have written (regardless of who uses the program), that code is by default under the same copyright license as your program itself.

You can choose to release your program under the GPL license (so your program and any changes to it remain open), but to add an exemption clause that your code that makes it into the output files is not bound by the copyleft provisions.

That way, your program could still be used to create the infrastructure for commercial (closed-source) apps. This wouldn't be possible if the code you output is covered by the GPL.


问:
How do you take advantage of your whiteboard in your development team?
Today we got our own website design. The theme is the "whiteboard".

I'm a big fan of them. I would like you to share with me how you use it. I'm sure I don't exploit its potential enough.

I will really enjoy answers that will come with pictures of your own whiteboard as an illustration ;)

I use it as an information radiator to support a light version of scrum.

How do you use this essential development tool?

Please note that I'm also interested in people using a virtual whiteboard or even big touchscreen whiteboard emulator.

答:
Maybe not the answer you're looking for since a whiteboard is somewhat of an investment, but I tend to use a college notebook for everything for a few reasons:

With a notepad, there's a record of everything you've written, sorted in chronological order -- all your thoughts are documented for you to go back to.

Unless you're in a bigger team, the text is usually big enough for 4-5 people sitting at a table to read.

They're readily available at more stores than whiteboards are.

They're lined, so you're inclined to keep things more neat.

Something about holding a pencil to paper gets my head going (but that's probably just me).

I love the semi-erased whiteboard look in the background of the new site design, but it gets really distracting when I see it on my own boards.

Notepads don't smell weird.

We bought whiteboards once... ended up asking the same question you did, until we just went back to pen/pencil/paper. Schedules and such go on Outlook or a normal gloss-paper wall calendar.

Sorry, don't have any pictures of my notebook to share off-hand :( Will post later if I can find one.


问:
Why is Today() an example of an impure function?
It seems like, when reading something like this Wikipedia article about "pure functions", they list Today() as an example of an impure function but it seems pretty pure to me. Is it because there is no formal input argument? Why is the actual time of day not treated as the "input to the function" in which case if you gave it the same input, i.e. executed today() twice at the same time, or traveled back in time to execute it again (maybe a hypothetical :) ), the output would be the same time. Today() never gives you a random number. it always gives you the time of day.

The Wikipedia article says "different times it will yield different results" but that's like saying for different x sin(x) will give you different ratios. And sin(x) is their example of a pure function.

答:
To be a pure function, providing the same parameters must give the same result every time.

Each time we call Today(), we are providing it the same parameters (none), and yet not necessarily getting the same result (Monday, Tuesday, etc.).


问:
What's the benefit of GIT for solo programmer?
If I am working on a program alone, I just zip entire program folder once in a while. I keep only latest 2-3 files so my disk isn't cluttered.

So for example I would have 2 files:
test-project-2015-02-03.zip
test-project-2015-01-31.zip

Obviously it's not worth ziping files every 5 minutes, when some feature is done I zip it.
Also I am not branching. That way I don't waste too much time on backup. I need backup very rarely and when I need it I don't have a clutter of 1000s of options, I just have 2 to restore from.

I am just learning github and I am amazed at complexity and clutter that it produces in recommended workflow. I can imagine it has to be like that for projects where many developers are working on same time, but why are single programmers having such complicated workflow?

1) Why do you commit every 5 minutes? Why not commiting when something is worthy of commit, like once every 2-3 days?

2) Why do you "add to stage" and commit? (To be sarcastic why not make 4 more stages in between)

3) Why do you create branches? You are going to restore latest best version anyway. Why not just stop commiting every 5 minutes if you are doing something risky? Commit when "branch" is done.

I need to learn git one day, but I can't put it on list of priorities when I don't see any benefits. I hope answers to this question will change that.

答:
You're making some incorrect assumptions.

Here are a few:

Having a granular version history (thousands of options, as you put it) is not clutter.  For example, when you're looking to revert small changes made a long time ago, going over 1000 properly commented commits is a breeze.  You can't do that with only 2 revisions in your history.

Commit early/often does not mean every 5 minutes.  It simply means don't be afraid of committing.  It's a cheap operation that is almost without drawbacks.  Every commit is a point in time you can unambiguously revert to.  Having to revert mistakes or experiments by hand is a recipe for disaster.

You seem annoyed at having to commit in stages.  And as gnat pointed it, it looks like you haven't even tried to research its use on your own.  Granted, this feature probably makes more sense when working in teams or offline, but it's still useful for solo development.  For example, when I work on a feature I make several commits throughout development.  Typically, I only commit when my code builds, but that doesn't mean the application actually runs correctly or that all the automated tests pass.  Once I've finished the feature and done my testing and I can guarantee the application is operational, then, and only then, do I push my changes.  This triggers my Continuous Integration server and plops out a new builds for my adoring fans :).  So, staged commits are a way of getting the benefit of source control locally without negatively influencing other developers on the same repo.  Ie, they don't have to put up with versions of the application that build, but fail half of the tests and crash immediately at runtime.


问:
Can I test effectively javascript functions with a PHP unit-testing framework?
If I want to unit-test some of my javascript functions, would it be more efficient (and doable) to use the already installed PHP unit-testing framework, or should I use a javascript unit-testing framework?

EDIT: It seems I have to clarify things a bit. I'm using javascript for form validation. It seems that some logic doesn't work as I want it to be, and I thought to myself that would be a good point to begin to use unit-testing (something that came to my scope only recently). I already began to use SimpleTest on a little project of mine, but never to test logic that is generated client-side.

Now I know that SimpleTest have the possibility to emulate a browser for example. But I was wondering what other method would they be to unit-test my form validation. While I was searching for idea, I realized that there is also unit-testing framework for javascript, but after a bit of searching on some of the SE sites, I didn't find anything about use of PHP and Javascript Framework together, so I wondered how common such a situation it was, and how do other people manage in such an environment.

答:
I have done something similar with javascript validation, not execution.

I use the command line tool gjslint from Google  to validate javascript.

```<code>/**
 *
 * @test
 * @dataProvider dataprovider_javascript_file
 */
public function javascript_files_are_valid ($fn){
    $dn = getcwd();
    $fn = "$dn/$fn";
    // most of these are whitespace- file-ending- and missing-semicolon flags
    $cmd1 = "gjslint --disable 131,1,2,5,10,11,300,-2 --nojsdoc --max_line_length 12000";
    $cmd .= "$cmd1 $fn";
    $flag = 1;
    $act_string = system($cmd, $flag);
    $exp_string = "1 files checked, no errors found.";
    $this->assertEquals($exp_string, $act_string, print_r("cmd: $cmd", 1));
}

public function dataprovider_javascript_file() {
    $dt->confArray = array("dirname1" => "", "dirname2" => "");
    $files = array_filter($dt->confArray, "self::getfilenames2");
    $files = array_map("self::val2array", $files);
    return $files;
}

private function val2array($v){
    return array($v);
}

private function getfilenames2($var){
    //fetch js files, but not minified files
    //return preg_match('/\.js$/', $var) ; #&& ! preg_match('/\.min\./', $var);

    return preg_match('/\.js$/', $var) && ! preg_match('/\.min\./', $var);

}
</code>```

Here I grab the output from the system() command and check the message string. That's a poor-man's method but it might suffice for a start.

A similar strategy would be to include the headless browser phantomjs to really execute your javascript. Then grab the output string and check that it does not contain any error messages.

I came here to look for some answers where someone might have done that, but didn't find any code so far. maybe have to write it myself.

Edit:

phantomjs-1.9.7-linux-x86_64/bin/phantomjs --web-security=false  /phantomjs-1.9.7-linux-x86_64/examples/arguments.js test hello

Output:

0: /opt/smallapps/phantomjs-1.9.7-linux-x86_64/examples/arguments.js
1: test
2: a

Grab this output from the command line and check it with phpunit assertions.

example.js contains:

```<code>var system = require('system');
if (system.args.length === 1) {
    console.log('Try to pass some args when invoking this script!');
} else {
    system.args.forEach(function (arg, i) {
            console.log(i + ': ' + arg);
    });
}
phantom.exit();
</code>```

Unfortunately, all this will only work with the simplest javascript files - without any dependencies to frameworks such as jQuery, or real interactions with other javascript-files that need to be embedded in a real html page, e.g. for accessing the DOM.

Body:
I have done something similar with javascript validation, not execution.

I use the command line tool gjslint from Google  to validate javascript.

/**
 *
 * @test
 * @dataProvider dataprovider_javascript_file
 */
public function javascript_files_are_valid ($fn){
    $dn = getcwd();
    $fn = "$dn/$fn";
    // most of these are whitespace- file-ending- and missing-semicolon flags
    $cmd1 = "gjslint --disable 131,1,2,5,10,11,300,-2 --nojsdoc --max_line_length 12000";
    $cmd .= "$cmd1 $fn";
    $flag = 1;
    $act_string = system($cmd, $flag);
    $exp_string = "1 files checked, no errors found.";
    $this->assertEquals($exp_string, $act_string, print_r("cmd: $cmd", 1));
}

public function dataprovider_javascript_file() {
    $dt->confArray = array("dirname1" => "", "dirname2" => "");
    $files = array_filter($dt->confArray, "self::getfilenames2");
    $files = array_map("self::val2array", $files);
    return $files;
}

private function val2array($v){
    return array($v);
}

private function getfilenames2($var){
    //fetch js files, but not minified files
    //return preg_match('/\.js$/', $var) ; #&& ! preg_match('/\.min\./', $var);

    return preg_match('/\.js$/', $var) && ! preg_match('/\.min\./', $var);

}

Here I grab the output from the system() command and check the message string. That's a poor-man's method but it might suffice for a start.

A similar strategy would be to include the headless browser phantomjs to really execute your javascript. Then grab the output string and check that it does not contain any error messages.

I came here to look for some answers where someone might have done that, but didn't find any code so far. maybe have to write it myself.

Edit:

phantomjs-1.9.7-linux-x86_64/bin/phantomjs --web-security=false  /phantomjs-1.9.7-linux-x86_64/examples/arguments.js test hello

Output:

0: /opt/smallapps/phantomjs-1.9.7-linux-x86_64/examples/arguments.js
1: test
2: a

Grab this output from the command line and check it with phpunit assertions.

example.js contains:

var system = require('system');
if (system.args.length === 1) {
    console.log('Try to pass some args when invoking this script!');
} else {
    system.args.forEach(function (arg, i) {
            console.log(i + ': ' + arg);
    });
}
phantom.exit();

Unfortunately, all this will only work with the simplest javascript files - without any dependencies to frameworks such as jQuery, or real interactions with other javascript-files that need to be embedded in a real html page, e.g. for accessing the DOM.


问:
Guesstimating multiple Epics
The company I work for is planning a big release. There are multiple teams and each team's Product Manager has come up with multiple Epics (we are using JIRA).

Now, we are supposed to guesstimate all those Epics so that release can be planned accordingly. But I don't understand the idea of this Epic guesstimate. So let's say my team guesstimate 4 epics and based on our velocity 2 of them can be considered for the release. But that's just guesstimate anyway right? More importantly, since it is a time-bound release, would it not make more sense to denote that these are release candidates and take an epic as we finish the current one?

-V

答:
The point of the exercise is most like that the Product Managers want to get a feel for what functionality they can expect in the next release.

Most likely, the epics will also not all be of the same size.

Suppose the team can, based on the current velocity, handle 30 storypoints until the release date.  Suppose also that the guesstimates come out to:

Epic A 20 SP,

Epic B 10 SP,

Epic C: 8 SP,

Epic D: 8 SP.

If you just work on those epics in the order given (A -> B -> C -> D), then you might finish the first two of them, if your guesstimates are not too far of reality.

On the other hand, the Product Managers can use this information to re-prioritize the epics and do Epic A last. That way you would be able to finish three of them with a bit of slack to counter the uncertainty in the guesstimates.

Title: Guesstimating multiple Epics


问:
How do you balance between "do it right" and "do it ASAP" in your daily work?
I find myself pondering over this question from time to time, again and again. I want to do things the right way: to write clean, understandable and correct code that is easy to maintain. However, what I end up doing is writing patch upon a patch; just because there is no time, clients are waiting, a bug should be fixed overnight, the company is losing money on this problem, a manager is pressing hard etc., etc.

I know perfectly well that in the long term I am wasting more time on these patches, but as this time spans months of work, nobody cares. Also, as one of my managers used to say: "we don't know if there will be a long term if we don't fix it now."

I am sure I am not the only one entrapped in these endless real/ideal choice cycles. So how do you, my fellow programmers, cope with this?

UPDATE:
Thank you all for this interesting discussion.
It is sad that so many people have to choose daily between a quantity and a quality of their code. Still, surprisingly many, people think it is possible to win this battle, so thank you all for this encouragement.

答:
I do most things the routine way, the first way that comes to mind. That is quick, and I like to think that I am a decent programmer and I do most things reasonably OK on the first try.

Every now and then (I'd like to say twice per day, but twice per week is more realistic), especially when I find something extremely boring to do in the routine way, I think "what would be an AWESOME way to do this?" and I spend the extra time to find or invent a better way to do it.

If I keep doing that often enough my routine coding will continue to improve, I think.


问:
Applying agile methodologies in a fast moving support environment
Do any agile methodologies have a place in the following setting:

Small web development team, working on a mixture of frontend, backend, design work, with a mixture of new projects, inherited bad projects and day to day maintenance/support of existing sites

Team of 2 developers with a pool of around 4 external freelance resources as and when required

1 project manager

The difficulty in doing sprint based development for me is the support tasks which can come in daily and priorities change from day to day.

答:
scrum methodology would be one good option for your scenario, with small modifications. When doing the sprint planning,

Either exclude n number of persons from sprint and dedicate them for support tasks over the sprint if possible, and in the next sprint rotate the persons who's doing support

Or allocate certain amount of effort based on past experience for support tasks. So you are allowed to burn some effort on fixing support tasks.

Since you have external resources, following proper sprint will help you to determine how much time you need from them.


问:
Any reasons why SQL-92 changed *, ? into %, _?
Do you know any reasons why SQL-92 standard has changed glob pattern wildcard characters from * and ? (SQL-89) to % and _?

Currently I need to do mask conversions to allow users searching data with * and ? which they already know from file system. Also, % and _ need escaping more frequently, because they tend to appear in data fields more frequenly than * or ?. What was breaking the glob standard good for?

答:
SQL dates back to the early 1970s. It's about the same age as UNIX. UNIX-style file name matching wildcards didn't become ubiquitous until much later.

* was already a reserved character in SQL, as in SELECT * FROM Customer. Having it also be a wildcard would probably have been confusing.

And standardization -- of wildcard characters or anything else -- always takes "prior art" into account, i.e. what database vendors were already doing in the late 1980s / early 1990s.  If no one was using * and ? as pattern matching wildcards there's no way those characters would work their way into the standard (the vendors are, after all, represented on the standards committee).

I'd also note that pattern matching (LIKE) expressions aren't exactly analogous to file system globbing.  The regular expression functionality found in sed, awk, and many other UNIX utilities IMO represent a much better analogue.

So a better question might be, why didn't SQL adopt regular expressions for pattern matching?


答:
Microsoft Access was based on a database engine called Jet which offered * and ? as wildcards for LIKE.  These were never a part of the SQL standard.  At some point, Microsoft incorporated a SQL-92 mode which offered the standard characters.

The use of % and _ goes back a very long way.  My copy of An Introduction to Database Systems by C.J. Date (4th edition, 1986) describes it that way.  IBM DB2 (first appeared ca. 1983) had it, and I wouldn't be surprised if predecessors SQL/DS (1981) and System R (mid- to late 1970s) did, too.  SQL in those products became the foundation for the standards.

Title: Any reasons why SQL-92 changed *, ? into %, _?

Body:
Do you know any reasons why SQL-92 standard has changed glob pattern wildcard characters from * and ? (SQL-89) to % and _?

Currently I need to do mask conversions to allow users searching data with * and ? which they already know from file system. Also, % and _ need escaping more frequently, because they tend to appear in data fields more frequenly than * or ?. What was breaking the glob standard good for?


问:
Time complexity analysis for recurrence relation
I was asked to figure out the time complexity analysis for the following recurrence relation
T(n) = 4*T(n-1) + c.

Basically, I did a replacement.. T(n-1) = 4 * T(n-2) + c and so on..

```<code>T(n) = 4^k T(1) + c(1 + 4 + 4^2..4^(k-1))
</code>```

I worked it out as O(4^k) Would like to know if this is right or wrong?

答: O(4^n) seems to be correct as c(1 + 4 + 4^2 + .. + 4^(n-1)) gives c(4^n - 1) / 3 thus reducing it to O(4^n) and the first part is already O(4^n).


问:
Should a newcomer to Perl learn both Perl 5 and 6?
I have started playing around with Perl 5 lately, and it seems very interesting. I would like to spend some time learning it more in depth when I can.

My question, since Perl 6 is slowly taking place (I believe...) and is said to break backward compatibility, is this: am I better learning Perl 5 and then Perl 6, or is learning Perl 6 directly a better time investment according to you?

If the changes from Perl 5 to 6 are making it hard to understand Perl 5, I should certainly start with Perl 5 to be able to read "old" scripts, then check Perl 6. There is also the "Perl 6 is not yet completely released" problem. I know there's an early adopter implementation for Perl 6, but if Perl 6 isn't officially released before some more years, I'll stick to 5 for now.

I would certainly like some insight on this. Feel free to discuss related stuff. My interest in scripting languages is fairly new.

Thanks!

答:
If you are interested in scripting style languages, I would suggest learning Python and/or Ruby instead. I first learned Perl several years ago. The main thing I learned from it is regular expressions. Most other languages that have built in regex are derivatives of the Perl implementation. But beyond that, I didn't use Perl for all that much. The main criticism of Perl is that some consider it a 'write-only' language. It is very hard to come back to old code and easily understand what was done.

It's my perception that more progress is being made with Python, and Ruby (like Rails), than there is with Perl. It's always good to stretch your brain an learn a new language, but Perl probably wouldn't be a top suggestion.


答:
Yes, you are correct.

The homogenous version of your recurrence relation is simply T(n) = 5*T(n-1) - 4*T(n-2) (You can get this by expressing c in the formula for T(n) and in the formula for T(n-1) and then equating them).

The characteristic polynomial of the relation is then x^2 - 5x + 4 = 0. Solving this you get the roots 1 and 4. Hence any solution of the recurrence relation has form a * 4^n + b * 1^n, which simplifies to a * 4^n + b. The values of a and b depend on your initial conditions (the value of c and T(0)). For example, for c = 1 and T(1) = 1, the solution is 1/3 * 4^n - 1/3 - you can check this yourself!

The overall strategy of solving these simple types of recurrence relations is described in the Wiki.

Title: Time complexity analysis for recurrence relation

Body:
I was asked to figure out the time complexity analysis for the following recurrence relation
T(n) = 4*T(n-1) + c.

Basically, I did a replacement.. T(n-1) = 4 * T(n-2) + c and so on..

```<code>T(n) = 4^k T(1) + c(1 + 4 + 4^2..4^(k-1))
</code>```

I worked it out as O(4^k) Would like to know if this is right or wrong?


问:
One controller to rule them all?
I am developing a single-page application. The page has a toolbar. When the user clicks on any button, it visually creates a tab, and triggers an ajax request to the required controller.
Now two things: firstly, the user always has to be authenticated, and secondly, not every user has access to each functionality.
In the first draft of this application, I didn't have much time to think about it, and I wrote a Javascript function whose body mainly was a Switch structure calling the right controller based on which button was clicked.
I'm no web developer, but I feel this solution is bad for at least three reasons:

The most obvious: I have one more file to modify if I change or add some controller.

This reveals the URL of all the existing controllers to anyone that reads the code of the page.

I have to do the same security checks in every controller.

I imagined the following scenario... what if, after authentication, I only had one controller that checks if the requested functionality is available for the connected user, and only then calls the right code (controller? simple class?) and return the result of this code. This code would never be accessible from outside, only internally.

Am I just confused with MVC and the SPA pattern?

答:
If implemented correctly, then MVC can certainly meet your needs.

How are you doing the authentication? If you are using the built in MVC functionality, then all you need to do is add an [Authorize] attribute to either each controller, or each method. All code for validation is then taken care of.

Additionally, you can create a BaseController, from which every controller then inherits. This can then be used to avoid repetitive code, such as setting up common variables, providing custom authentication, etc.

See this question for a good example of a BaseController, and a discussion on using them.

Title: One controller to rule them all?


答:
Without knowing too much about your project I would suggest a generic solution for this type of problems. /Note this might not be best in all cases/

Since you said authentication is done in every case it can obviously be done separately to avoid code duplication and complexity.

After authentication based on the users rights you generate a temporary code.

Then you separately store the value of the button which was clicked.

Now you have two numbers (codes): your user rights and the button clicked => a classical case of a 2D lookup table. Where the two codes meet you have a function call (or whatever it is you want to do).

BTW: If you have large switch-cases or if-statements those can pretty much always be replaced with a lookup table, which is much more efficient. In your case that could just be a 2D array.

Pseudo-code:

```<code>FunctionalityTable[][] =
{
    {event1(), notAllowed(), notAllowed()},
    {event2(), event2(), notAllowed()},
    ...
};

int rights = authenitcate().toInt();

int option = getButtonPressed().toInt();

FunctionalityTable[rights][option];
</code>```

Title: One controller to rule them all?

Body:
I am developing a single-page application. The page has a toolbar. When the user clicks on any button, it visually creates a tab, and triggers an ajax request to the required controller.
Now two things: firstly, the user always has to be authenticated, and secondly, not every user has access to each functionality.
In the first draft of this application, I didn't have much time to think about it, and I wrote a Javascript function whose body mainly was a Switch structure calling the right controller based on which button was clicked.
I'm no web developer, but I feel this solution is bad for at least three reasons:

The most obvious: I have one more file to modify if I change or add some controller.

This reveals the URL of all the existing controllers to anyone that reads the code of the page.

I have to do the same security checks in every controller.

I imagined the following scenario... what if, after authentication, I only had one controller that checks if the requested functionality is available for the connected user, and only then calls the right code (controller? simple class?) and return the result of this code. This code would never be accessible from outside, only internally.

Am I just confused with MVC and the SPA pattern?

Body:
Without knowing too much about your project I would suggest a generic solution for this type of problems. /Note this might not be best in all cases/

Since you said authentication is done in every case it can obviously be done separately to avoid code duplication and complexity.

After authentication based on the users rights you generate a temporary code.

Then you separately store the value of the button which was clicked.

Now you have two numbers (codes): your user rights and the button clicked => a classical case of a 2D lookup table. Where the two codes meet you have a function call (or whatever it is you want to do).

BTW: If you have large switch-cases or if-statements those can pretty much always be replaced with a lookup table, which is much more efficient. In your case that could just be a 2D array.

Pseudo-code:

FunctionalityTable[][] =
{
    {event1(), notAllowed(), notAllowed()},
    {event2(), event2(), notAllowed()},
    ...
};

int rights = authenitcate().toInt();

int option = getButtonPressed().toInt();

FunctionalityTable[rights][option];


答:
Your controller is simply feeding data to your website.  How it is presented is entirely up to you, be it a SPA or whatever else you want to use.  In that sense you are more than welcome to use MVC because how your view is structured is independent from the underlying design of using a controller.

The switch structure that determines which controller to call based on which button was clicked sounds like it belongs in the routing engine.  Each button should form a URI request that is submitted to the web server.  The web server then uses its routing information to call the underlying Controller and Method based on that configuration.  Of course each new button will do new things, and as such will require a new controller method.

How you want to logically structure your controllers is up to you.  With ASP.NET MVC you can dictate authorization at a Controller level or a Method level.  You could create a single controller and use the Authorize attributes at the method level.  You could create different controllers based on authorization levels (IE if you have a User and Admin area) and control authorization at the controller level.  Once you have access to the controller, you will have access to all of its methods.

Take a look at http://www.asp.net/mvc/overview/security and see if you can find some more information that leads you to the right answer for your specific problem.

Title: One controller to rule them all?


问:
Version control for independent developers?
Do you think it's worth it to use version control if you are an independent developer, and if so, why? Do you keep the repository on your own computer, or elsewhere, where it can serve as a backup?</p>

答:
source code control is utterly useless for independent developers, because as we all know:

independent developers never make mistakes

independent developers never go off on revisions that don't work out

independent developers never have more than one version so they have no use for branches

independent developers never care about what they changed yesterday or last week

independent developers never, ever need backups

Call me a "dependent developer": Mercurial repositories clone easily between my desktop, laptops, USB backup drives, and bitbucket.org. I've grown dependent, and I like it that way!


问:
Convention for logging within nested try catch blocks
I've looked at this question but it doesn't really help solve my dilemma.

System 1 calls system 2 within a try catch, the method in system 2 has it's own try catch, which sadly handles an exception but does not re-throw it. So my question is: Which system should log it? Each system has it's own logging files.

Sample:

```<code>Class System1{
Public void DoSomething(){
    Try{
        var sys = new System2();
        sys.ExecuteMethod();
    }
    Catch{Exception e){
        logger.log(e);
    }
}
}
// ------IN A DIFFERENT SYSTEM ON A DIFFERENT MACHINE------
Class System2{
Public void ExecuteMethod(){
    Try{
        throw new Exception("Test Excpetion");
    }
    Catch{Exception e){
        logger.log(e);
    }
}
}
}
</code>```

答:
You could argue that they should both log it.

System 1 is trying to accomplish something but needs to access System 2.  System 1 should log that it couldn't successfully complete its work for some reason or another due to its dependency on System 2.  If System 2 encounters an internal error processing a request, it should be logging those types of issues as well.

Other use cases do arise, including authorization, network connectivity, malformed requests, etc.  Consider each one and how each system should (if required) log that.


答:
As pointed out by Bart van Ingen Schenau: The Kanban development method might work well for you.

Kanban is a fairly "minimal" method; in particular, it prescribes much less than Scrum.

The basic principles are:

Visualize the workflow - typically by having (physical or virtual) cards for each task, that move across a board with different phases/steps

Reduce work in progress (WIP) - do not work on too many cards in parallel

Learn and improve continuously

Kanban emphasizes a constant "flow" of work and results, not working in sprints or iterations (though the approaches can be combined). It works fairly well in situations where work often comes in unexpectedly and priorities change often.

Title: Applying agile methodologies in a fast moving support environment

Body:
Do any agile methodologies have a place in the following setting:

Small web development team, working on a mixture of frontend, backend, design work, with a mixture of new projects, inherited bad projects and day to day maintenance/support of existing sites

Team of 2 developers with a pool of around 4 external freelance resources as and when required

1 project manager

The difficulty in doing sprint based development for me is the support tasks which can come in daily and priorities change from day to day.


问:
Who should be allowed to add stories to the product backlog?
What is the best practice for that prevents the backlog from becoming a mess, but also maintaining developer productivity

Who should we allow to add stories to the product backlog? And how do you make sure these stories meet certain requirements?

For example I find a few small css bugs during the development of Feature X. Should I then as a developer be allowed to add a story describing the bugs to the bottom of the backlog? Or should I discuss it with the product owner?

Having all ideas/bugs go through the product owner sounds like possible bottleneck.

答:
The usual approach is that anyone can add stories to the backlog.  The product owner prioritizes them and the team estimates them.  Story quality issues generally get taken care of one way or another in planning meetings or retrospectives.

That means the product owner isn't a bottleneck as long as you're satisfied with the priorities he's assigning.  Otherwise, make your case.


答:
It depends on the exception. If you expect that the exception may occur and it is valid, and you are actually handling it, as in, you've got plan B for that situation, then don't throw it.

If the exception breaks the workflow and you aren't actually handling it, go ahead and log it if you deem it necessary, but sometimes the current method scope doesn't have enough useful information to justify logging it. Sometimes you'll want to throw it to a higher scope with more useful information, catch it there, then log it.

For example:

```<code>int DoSomething1(int userId, int transactionId) {
    try {
        int orgId = GetOrgId(userId);
        DoSomething2(orgId);
        /* ... more things ... */
    } catch(MyException ex) {
        Log(string.Format("{0}\nuser: {1}, trns: {2}\n\tMessage: {3}\n\t\tTrace: {4}",
            ex.Message, userId, transactionId, ex.InnerException.Message, ex.InnerException.StackTrace));
        throw;
    } catch(Exception ex) {
        Log(string.Format("user: {0}, trns: {1}\n\tMessage: {2}\n\t\tTrace: {3}",
            userId, transactionId, ex.Message, ex.StackTrace));
        throw;
    }
}

int DoSomething2(int orgId) {
    try {
        /* ... some stuff .... */
    } catch(Exception ex) {
        throw new MyException { Message = string.Format("org: {0}", orgId),
            InnerException = ex };
    }
}
</code>```

Your front-end shouldn't dump stack traces to users, so if the exception gets that far, you have to handle it one way or another. But then that depends on what the front-end is. If its a webservice, error codes are very nice instead of deceptively pretending that everything went swimmingly, or giving them no feedback at all.

Title: Convention for logging within nested try catch blocks

Body:
I've looked at this question but it doesn't really help solve my dilemma.

System 1 calls system 2 within a try catch, the method in system 2 has it's own try catch, which sadly handles an exception but does not re-throw it. So my question is: Which system should log it? Each system has it's own logging files.

Sample:

```<code>Class System1{
Public void DoSomething(){
    Try{
        var sys = new System2();
        sys.ExecuteMethod();
    }
    Catch{Exception e){
        logger.log(e);
    }
}
}
// ------IN A DIFFERENT SYSTEM ON A DIFFERENT MACHINE------
Class System2{
Public void ExecuteMethod(){
    Try{
        throw new Exception("Test Excpetion");
    }
    Catch{Exception e){
        logger.log(e);
    }
}
}
}
</code>```

Body:
It depends on the exception. If you expect that the exception may occur and it is valid, and you are actually handling it, as in, you've got plan B for that situation, then don't throw it.

If the exception breaks the workflow and you aren't actually handling it, go ahead and log it if you deem it necessary, but sometimes the current method scope doesn't have enough useful information to justify logging it. Sometimes you'll want to throw it to a higher scope with more useful information, catch it there, then log it.

For example:

int DoSomething1(int userId, int transactionId) {
    try {
        int orgId = GetOrgId(userId);
        DoSomething2(orgId);
        /* ... more things ... */
    } catch(MyException ex) {
        Log(string.Format("{0}\nuser: {1}, trns: {2}\n\tMessage: {3}\n\t\tTrace: {4}",
            ex.Message, userId, transactionId, ex.InnerException.Message, ex.InnerException.StackTrace));
        throw;
    } catch(Exception ex) {
        Log(string.Format("user: {0}, trns: {1}\n\tMessage: {2}\n\t\tTrace: {3}",
            userId, transactionId, ex.Message, ex.StackTrace));
        throw;
    }
}

int DoSomething2(int orgId) {
    try {
        /* ... some stuff .... */
    } catch(Exception ex) {
        throw new MyException { Message = string.Format("org: {0}", orgId),
            InnerException = ex };
    }
}

Your front-end shouldn't dump stack traces to users, so if the exception gets that far, you have to handle it one way or another. But then that depends on what the front-end is. If its a webservice, error codes are very nice instead of deceptively pretending that everything went swimmingly, or giving them no feedback at all.


答:
We allow posting bugs to bottom of product backlog for everyone in the team. The item should correspond to certain rules (e.g. conditions for reproducing, what's the correct behaviour, etc)
New features, however, are added to separate list 'Ideas', from which the PO pulls them into Backlog (and obviously turns them into a PBI with more information if needed)</p>

Title: Who should be allowed to add stories to the product backlog?

Body:
What is the best practice for that prevents the backlog from becoming a mess, but also maintaining developer productivity

Who should we allow to add stories to the product backlog? And how do you make sure these stories meet certain requirements?

For example I find a few small css bugs during the development of Feature X. Should I then as a developer be allowed to add a story describing the bugs to the bottom of the backlog? Or should I discuss it with the product owner?

Having all ideas/bugs go through the product owner sounds like possible bottleneck.


答:
If the system 2 handles the exception and doesn't rethrow it, then it sounds like system 1 doesn't have any way of knowing that an exception occurred. In that case, there's really no question as to whether system 1 should log anything, since it doesn't know an error occurred!

If both systems are aware of the error, and they are logging to different places, and the error is something you want logged, then you probably should have both of them log the error. You might want to think about finding a way to unify the logging though, as multiple log files are a pain to sift through (unless this is a client/server system where system 2 is running on a different machine than system 1, then you want to log in both places).

If system 2 is legitimately handling the error, then there is probably no need to log it in system 1. There might not even be a reason to log it in system 2 either, but you need to analyze whether that is required for your situation.

I would generally recommend that when in doubt, log it. But you definitely want to check at some point whether you are logging too much information, preferably before going to production.


问:
What to use instead of IDs in selectors in CSS
I recently installed a csslint package for my Atom text editor. I keep getting warnings saying "Don't use IDs in selectors." I found this weird since I've always been using IDs in selectors in CSS, and I haven't really run into any coding or syntactic problems using them.

On StackOverflow, I found posts, like this one, stating that I shouldn't use IDs because they have priority over classes. However, I found another post that states I should use IDs because they have priority over classes. I understand both of these posts, but I still don't know if I should continue to use them or not.

Lets say I have this code as an example:

HTML

```<code><div id="opening-subject-container">
    <div class="subject"></div>
    <div class="subject"></div>
    <div class="subject"></div>
</div>
<div id="body-subject-container">
    <div class="subject"></div>
    <div class="subject"></div>
    <div class="subject"></div>
</div>
</code>```

CSS

```<code>.subject {
    width: 100%;
    height: 20px;
}
#opening-subject-container .subject {
    background-color: red;
}
#body-subject-container .subject {
    background-color: blue;
}
</code>```

where I want the first subjects in the opening container to be red and the remaining subjects in the body container to be blue.

If I shouldn't ever use IDs in CSS selectors, what should I use instead?

Thanks for everyone's advice. I decided to stick with using IDs since they are convenient and I am able to keep track of when I should use an ID and when not to. I got tired of the warning messages in the lint, so I just changed the source code and deleted some rules that display warnings like this.

答:
I think the gist of the argument, for those that agree with it, is to use class for css selectors instead of id. This avoids unintended css precedence rules from kicking in.

If you know what you're doing (re class vs id selectors), and it works for you, I wouldn't change just for the sake of changing, though.

From http://csslint.net/about.html:

IDs shouldn't be used in selectors because these rules are too tightly
  coupled with the HTML and have no possibility of reuse. It's much
  preferred to use classes in selectors and then apply a class to an
  element in the page.


问:
How to earn team members respect as team lead
If you were hired into a new company as a team lead (say a team of 10) one of the important things to do is to earn the respect of the members of the team. In the early days the new team lead may know nothing of the team culture, code base and business domain: in other words, is a complete neophyte. </p>

<p>How does one go about this? What are the do's and don'ts? </p>

答:
your first day there, kick somebody's @$$, or become somebody's ... no wait, that's prison.

show respect to earn respect, listen intently, and be yourself - but most of all, lead by being a good example


答:
Using ids is like using singletons, and singletons are not very good style. For prototype, yes, but in you're trying to make things right, do not presume that "this kind thing will always be here once and only once" unless you know for sure. It's more flexible to be prepare for 0 and many, not just for 1.

And of course, the CSS precedence is valid concern as well.

Eg. in your example there should be class="opening subject-container" and class="body subject-container" and you can select yourself if the style is applicable to all .opening things or only to .opening.subject-container, plus you can style things common to all .subject-containers as well. Just a possible example.

Title: What to use instead of IDs in selectors in CSS

Body:
I recently installed a csslint package for my Atom text editor. I keep getting warnings saying "Don't use IDs in selectors." I found this weird since I've always been using IDs in selectors in CSS, and I haven't really run into any coding or syntactic problems using them.

On StackOverflow, I found posts, like this one, stating that I shouldn't use IDs because they have priority over classes. However, I found another post that states I should use IDs because they have priority over classes. I understand both of these posts, but I still don't know if I should continue to use them or not.

Lets say I have this code as an example:

HTML

```<code><div id="opening-subject-container">
    <div class="subject"></div>
    <div class="subject"></div>
    <div class="subject"></div>
</div>
<div id="body-subject-container">
    <div class="subject"></div>
    <div class="subject"></div>
    <div class="subject"></div>
</div>
</code>```

CSS

```<code>.subject {
    width: 100%;
    height: 20px;
}
#opening-subject-container .subject {
    background-color: red;
}
#body-subject-container .subject {
    background-color: blue;
}
</code>```

where I want the first subjects in the opening container to be red and the remaining subjects in the body container to be blue.

If I shouldn't ever use IDs in CSS selectors, what should I use instead?

Thanks for everyone's advice. I decided to stick with using IDs since they are convenient and I am able to keep track of when I should use an ID and when not to. I got tired of the warning messages in the lint, so I just changed the source code and deleted some rules that display warnings like this.


答:
ID's are needed to be unique while classes tend to group several elements' style together. I read somewhere it as this analogy :

```<code><student id="JonathanSampson" class="Biology Calculus" />
<student id="MarySmith" class="Biology Networking" />
</code>```

Student ID cards are distinct. No two students on campus will have the
  same student ID card. However, many students can and will share at
  least one Class with each other.

Moreover , ID elements tend to have higher priority over other selectors which makes it harder to reapply rules on them.
There was an stackoverflow answer regarding some JS function selecting only first occurence of same ID elements too (I'll include link asap).

EDIT : try getting a bunch of elements by using getElementByID() in js and you'll notice what I was trying to say.

On the other hand , IMO you shouldn't take csslint complaints too strictly on your css rules. Some of them are flawed by nature.

reference

Body:
ID's are needed to be unique while classes tend to group several elements' style together. I read somewhere it as this analogy :

<student id="JonathanSampson" class="Biology Calculus" />
<student id="MarySmith" class="Biology Networking" />

Student ID cards are distinct. No two students on campus will have the
  same student ID card. However, many students can and will share at
  least one Class with each other.

Moreover , ID elements tend to have higher priority over other selectors which makes it harder to reapply rules on them.
There was an stackoverflow answer regarding some JS function selecting only first occurence of same ID elements too (I'll include link asap).

EDIT : try getting a bunch of elements by using getElementByID() in js and you'll notice what I was trying to say.

On the other hand , IMO you shouldn't take csslint complaints too strictly on your css rules. Some of them are flawed by nature.

reference


问:
Potential abuse of observer pattern
I have a MeetingRoom object that contains a list of Employees, there is a function on each employee called SetMeetingDate, this method has to take into account the state of all other employees in the MeetingRoom in particicular the IsReadyForMeeting property.

An individual employee for example can only successfully call SetMeetingDate(Date date) when every employee in the ChatRoom has IsReadyForMeeting set to true.

I have thought about a couple of ways to implement this functionality, I can do something where the employee checks the state of the other employees by going via the MeetingRoom object like this:

```<code>    public void SetMeetingDate(DateTime date)
    {
        if (!MeetingRoom.AllEmployeesAreReady)
        {
            throw new ApplicationException("all employees are not ready");
        }

        MeetingDate = date;
    }
</code>```

which seems to me to have the responsibility in the wrong place.

A second approach that I can use is to set up an observer so that the Employee class will inform the MeetingRoom object that it has set a meeting date and the MeetingRoom class will raise the exception if MeetingRoom.AllEmployeesAreReady is false thus moving the responsibility to the MeetingRoom object and the code for the employee would look like this:

```<code>    public void SetMeetingDate(DateTime date)
    {
        MeetingDate = date;

        Observer.MeetingDateAdded();
    }
</code>```

And the Meeting Room would then have a method like this:

```<code>    public void MeetingDateAdded()
    {
        if (!AllEmployeesAreReady)
        {
            throw new ApplicationException("all employees are not ready");
        }
    }
</code>```

This use of the observer has been met with opposition from other developers in my team and  I can see why but I can't think of a better way to implement the requirement, is there an easy/different approach that can be used in this situation?

答:
You should go with your first solution.

Your first solution is better because it's simpler (but maybe show the user a message instead of throwing an exception if it seems more appropriate).

Head First Design Patterns says it best:

First of all, when you design, solve things in the simplest way possible. Your goal should be simplicity, not "how can I apply a pattern to this problem." Don't feel like you aren't a sophisticated developer if you don't use a pattern to solve a problem. Other developers will appreciate and admire the simplicity of your design. That said, sometimes the best way to keep your design simple and flexible is to use a pattern.

It's usually best to use design patterns only when your alternatives all seem far too complicated. Let KISS and YAGNI be your guides when it comes to deciding whether to use a design pattern.

Title: Potential abuse of observer pattern


答:
I'd take a different approach, hopefully a clearer one.

```<code>// This is a filter function, needlessly wordy in Java.
List<Employee> getUnreadyParticipants(DateTime meetingMoment) {
  ArrayList<Employee> unreadyParticipants = new ArrayList<>();
  for (Employee e : this.getMeetingParticipants()) {
    if (!e.readyForMeeting(meetingTime)) unreadyParticipants.add(e);
  }
  return unreadyParticipants;
}

public void setMeetingDate(DateTime meetingMoment) {
  ArrayList<Employee> unreadyParticipants = getUnreadyParticipants(meetingMoment);
  if (unreadyParticipants.size() > 0) {
    throw new InvalidOperationException(
      "Participants not ready: " + printListNicely(unreadyParticipants)
    );
  }
  // whatever else is the logic
}
</code>```

Reasons:

Checking time compatibility is MeetingRoom's concern, not Employee's.

The list of unready participants is available for diagnostics.

There are no flags and other pieces of state that denote readiness (like .AreAllEmployeesReady) which may go out of sync with the list of participants.

Title: Potential abuse of observer pattern

Body:
I have a MeetingRoom object that contains a list of Employees, there is a function on each employee called SetMeetingDate, this method has to take into account the state of all other employees in the MeetingRoom in particicular the IsReadyForMeeting property.

An individual employee for example can only successfully call SetMeetingDate(Date date) when every employee in the ChatRoom has IsReadyForMeeting set to true.

I have thought about a couple of ways to implement this functionality, I can do something where the employee checks the state of the other employees by going via the MeetingRoom object like this:

```<code>    public void SetMeetingDate(DateTime date)
    {
        if (!MeetingRoom.AllEmployeesAreReady)
        {
            throw new ApplicationException("all employees are not ready");
        }

        MeetingDate = date;
    }
</code>```

which seems to me to have the responsibility in the wrong place.

A second approach that I can use is to set up an observer so that the Employee class will inform the MeetingRoom object that it has set a meeting date and the MeetingRoom class will raise the exception if MeetingRoom.AllEmployeesAreReady is false thus moving the responsibility to the MeetingRoom object and the code for the employee would look like this:

```<code>    public void SetMeetingDate(DateTime date)
    {
        MeetingDate = date;

        Observer.MeetingDateAdded();
    }
</code>```

And the Meeting Room would then have a method like this:

```<code>    public void MeetingDateAdded()
    {
        if (!AllEmployeesAreReady)
        {
            throw new ApplicationException("all employees are not ready");
        }
    }
</code>```

This use of the observer has been met with opposition from other developers in my team and  I can see why but I can't think of a better way to implement the requirement, is there an easy/different approach that can be used in this situation?

Body:
I'd take a different approach, hopefully a clearer one.

// This is a filter function, needlessly wordy in Java.
List<Employee> getUnreadyParticipants(DateTime meetingMoment) {
  ArrayList<Employee> unreadyParticipants = new ArrayList<>();
  for (Employee e : this.getMeetingParticipants()) {
    if (!e.readyForMeeting(meetingTime)) unreadyParticipants.add(e);
  }
  return unreadyParticipants;
}

public void setMeetingDate(DateTime meetingMoment) {
  ArrayList<Employee> unreadyParticipants = getUnreadyParticipants(meetingMoment);
  if (unreadyParticipants.size() > 0) {
    throw new InvalidOperationException(
      "Participants not ready: " + printListNicely(unreadyParticipants)
    );
  }
  // whatever else is the logic
}

Reasons:

Checking time compatibility is MeetingRoom's concern, not Employee's.

The list of unready participants is available for diagnostics.

There are no flags and other pieces of state that denote readiness (like .AreAllEmployeesReady) which may go out of sync with the list of participants.


问:
Understanding RESTful web services
I've been trying to understand how RESTful web services work and I've come up with a series of doubts and questions for which I have been unable to find an answer. First of all and to make sure I am correctly understanding what this is all about, the following diagram summarizes what a RESTful architecture for a small website could look like:

The first server basically contains a set of services identified by URL's. Those services obtain information from different databases and provide it to someone asking through a REST API (JSON) over http or https. On another server, a web application in an MVC style interacts with those services through their URL's upon user requests.

Is my understanding correct?

How do web applications such as facebook cope with the delays in getting responses when handling multiple services?

How does one make sure that only certain entities are allowed access to services (in this example, how does Server 1 authenticate Server 2)?

Is it common to use these kinds of architectures for mobile applications too?

When mixing this type of architecture with AJAX, are the AJAX calls done directly to the services or do they go through the main web application controller?

答:
Yes, your understanding is correct. Although, some REST services can be accessed directly, without passing by the server 2.

Getting a response is a matter of milliseconds, especially when data centers are close to each other geographically (because indeed, speed of light matters). If we are talking about small web apps, the REST service and the app may be hosted on the same machine, which may mean that the time lost exchanging data is less than a millisecond.

There are several authentication mechanisms. For instance, Server 2 may use an API key which is unknown by other servers. Another possibility is to look at the IP address of the client, although usually, it is a better idea to have the same authentication mechanism for internal and external use.

Yes. REST services are used for mobile applications, desktop applications, embedded apps, etc.

REST services can be used directly. Passing them through another server (would it be Server 2 in your diagram, or Server 3) adds a layer of complexity, but may sometimes be a valid choice.

Note that in many cases, multiple servers are involved anyway. For instance, for a small but reliable website which has no REST services:

The request to the home page of a website may be handled by a failover server (such as Nginx) which determines which one of two app servers should handle the request.

The app server starts handling the request.

This produces several log entries which are sent to a log server.

Since data is required, database servers are solicited. If the first database server is down, the failover one is used.

See? Without any REST services, five machines were used to generate a response (not counting different switches and network devices which were passing the request and the response).

Title: Understanding RESTful web services


答:
There are many reasons to select by an id. I think the spirit of that message from lint is that you should primarily apply styling by classes.

Selecting by id can be the exception where your styling is shared across similar elements,  except this one, or only this one.

You can use classes to act as an id, but I think thats probably evangelism. That'd be like the guys that insist to never use a table even when a table is perfectly appropriate.


答:
We have a similar setup and Kanban works fine. You can add/remove tasks from boards as needed.
It would be difficult to involve external freelancers in Scrum activities, such as sprint planning, daily scrums and review.</p>


问:
How to split large, tightly coupled classes?
I have some huge classes of more than 2k lines of code (and growing) that I would like to refactor if possible, to have some more light and clean design.

The reason it is so big is mainly because these classes handle a set of maps that most methods need to access, and methods are very connected to each other.

I will give a very concrete example: I have a class called Server that handles incoming messages.
It has methods like joinChatroom, searchUsers, sendPrivateMessage, etc.
All of these methods manipulate the maps such as users, chatrooms, servers, ...

Maybe it would be nice if I could have a class handling messages concerning Chatrooms, another handling all about Users, etc.
but the main problem here is that I need to use all of the maps in most of the methods.
That's why for now they are all sticked in the Server class as they all rely on these common maps and the methods are very connected to each other.

I would need to create a class Chatrooms, but with a reference to each of the other objects.
A class users again with a reference to all the other objects,
etc.

I feel like I would be doing something wrong.

答:
To add to casablanca's insightful answer - if multiple classes need to do the same basic things with some type of entity (adding users to a collection, handling messages etc), those processes ought to be kept separate as well.

There are multiple ways to do this - by inheritance or composition. For inheritance, you can use abstract base classes with concrete methods that provide the fields and functionality to handle users or messages for example, and have entities like chatroom and user (or any other) extend those classes.

For various reasons, it's a good general rule to use composition over inheritance. You might use composition to do this in various ways. Since handling users or messages are functions central to the responsibility of the classes, it can be argued that constructor injection is most appropriate. This way, the dependency is transparent and an object cannot be created without having the required functionality. If the way users or messages are handled is likely to change or be extended, you ought to consider using something like the strategy pattern.

In both cases, be sure to code towards interfaces, not concrete classes for flexibility.

All that being said, always consider the cost of added complexity when using such patterns - if you're not going to need it, don't code it. If you know you're very probably not going to change how handling of users / messages is done, you don't need the structural complexity of a strategy pattern - but in order to separate concerns and avoid repetition, you should still divorce common functionality from the concrete instances that use it - and, if no overriding reasons to the contrary exist, compose the users of such handling-functionality (chatrooms, users) with an object that does the handling.

So, to sum up:

As casablanca wrote: Separate and encapsulate chatrooms, users etc.

Separate common functionality

Consider separating individual functionality to divorce data-representation (as well as access and mutation) from more complex functionality over individual instances of data or aggregates thereof (for example, something like searchUsers could go in a collection-class, or a repository / identity-map)

OwnerDisplayName: Matthew


答: Ideally If you have something that was estimated to be an epic on the initial estimate you would then hold a separate discussion on how best to break it down into more manageable stories and estimate each one of those, and do that for each epic or at least the most important two. Epics themselves should never actually be part of a sprint, if something with a high stack rank is deemed to be an epic the grooming should be targeted at breaking down that epic. This allows all the newly created stories to be prioritized so all the most important work has the best chance of getting done. By the deadline it may happen that none of the epics are actually 100% done, but all the important bits of each epic are done. This should result in happier customers, because a basic car is a lot better than a car with all the bells and whistles, but it doesn't have wheels yet.</p>

Title: Guesstimating multiple Epics

Body:
The company I work for is planning a big release. There are multiple teams and each team's Product Manager has come up with multiple Epics (we are using JIRA).

Now, we are supposed to guesstimate all those Epics so that release can be planned accordingly. But I don't understand the idea of this Epic guesstimate. So let's say my team guesstimate 4 epics and based on our velocity 2 of them can be considered for the release. But that's just guesstimate anyway right? More importantly, since it is a time-bound release, would it not make more sense to denote that these are release candidates and take an epic as we finish the current one?

-V


问:
What do polynomial algorithms entail?
From here, I know it is that an algorithm that...

...is said to be solvable in polynomial time if the number of steps required to complete the algorithm for a given input is O(n^k) for some nonnegative integer k, where n is the complexity of the input.

Can some of you offer examples involving common data structures to explain polynomial time? I've looked it up but the available information is scarce.

答:
One of the most common ways to express polynomial time, O(nk), is nested loops where n is used as an input to calculate the maximum iterations of each loop and k is the level of nested loops.

For example, this loop is O(n2) because it is a doubly-nested loop where n is the number of iterations:

```<code>int n = ...;
int x = 0;
for (int i = 0; i < n; ++i) {
  for (int i = j; j < n; ++j) {
    ++x;
  }
}
</code>```

If you add a third loop it would be O(n3).

OwnerDisplayName: eltigre

Title: What do polynomial algorithms entail?

Body:
One of the most common ways to express polynomial time, O(nk), is nested loops where n is used as an input to calculate the maximum iterations of each loop and k is the level of nested loops.

For example, this loop is O(n2) because it is a doubly-nested loop where n is the number of iterations:

int n = ...;
int x = 0;
for (int i = 0; i < n; ++i) {
  for (int i = j; j < n; ++j) {
    ++x;
  }
}

If you add a third loop it would be O(n3).