问:
Should one check for null if he does not expect null?
Last week, we had a heated argument about handling nulls in our application's service layer. The question is in the .NET context, but it will be the same in Java and many other technologies.

The question was: should you always check for nulls and make your code work no matter what, or let an exception bubble up when a null is received unexpectedly?

On one side, checking for null where you are not expecting it (i.e. have no user interface to handle it) is, in my opinion, the same as writing a try block with empty catch. You are just hiding an error. The error might be that something has changed in the code and null is now an expected value, or there is some other error and the wrong ID is passed to the method.

On the other hand, checking for nulls may be a good habit in general. Moreover, if there is a check the application may go on working, with just a small part of the functionality not having any effect. Then the customer might report a small bug like "cannot delete comment" instead of much more severe bug like "cannot open page X".

What practice do you follow and what are your arguments for or against either approach?

Update:

I want to add some detail about our particular case. We were retrieving some objects from the database and did some processing on them (let's say, build a collection). The developer who wrote the code did not anticipate that the object could be null so he did not include any checks, and when the page was loaded there was an error and the whole page did not load.

Obviously, in this case there should have been a check. Then we got into an argument over whether every object that is processed should be checked, even if it is not expected to be missing, and whether the eventual processing should be aborted silently.

The hypothetical benefit would be that the page will continue working. Think of a search results on Stack Exchange in different groups (users, comments, questions). The method could check for null and abort the processing of users (which due to a bug is null) but return the "comments" and "questions" sections. The page would continue working except that the "users" section will be missing (which is a bug). Should we fail early and break the whole page or continue to work and wait for someone to notice that the "users" section is missing?

答: Every null in your system is a ticking time bomb waiting to be discovered. Check for null at the boundaries where your code interacts with code you don't control, and forbid null within your own code. This rids you of the problem without naively trusting foreign code. Use exceptions or some sort of Maybe/Nothing type instead.


问:
What are the valid test cases for method calls within if-else condition
I have a discount service that gets called if certain conditions are met. I need to write test cases to check if the discount service is called. My doubt is checking if the discount service is NOT called for type 4 and 5 is a valid test case scenario.  </p>

```<code>public void ApplyDiscount(int typeId, double amount)
{

if(typeId == 1)
{
  //call discount service
}

else if(typeId == 2)
{
  //call discount service
}

else if(typeId == 4)
{
   //do other stuff
}
else if(typeId == 5)
{
   //do some other stuff
}

}
</code>```

答:
At this point there are no valid test cases.

There's not a lot to test here.  The method returns void, so any test would be focused on any effect to an object or state that is internal to this method,  or alters state the is global in scope.  If cases 1 and 2 simply call a service then there is no change in state, so there is nothing to test.

Cases 4 and 5, don't know what kind of stuff you are doing so at this point I would not write any tests for this.

Additionally, I would probably use a switch statement instead of a bunch of if/elses.  Looks like case 1 and 2 are the same.

ContentLicense: CC BY-SA 3.0


问:
Are optional parameters helpful or a hindrance to application maintenance?
As stated in the title, are optional parameters, such as those used in C# helpful or are they a hindrance to application maintenance and should be avoided as they can make the code harder to understand?</p>

答: I'd think it would be better to overload a function with different signatures (i.e. parameters) than use optional parameters.</p>

ContentLicense: CC BY-SA 2.5


问:
Interface Segregation Principle - type hinting multiple interfaces
The question is about typehinting of the role interfaces.

The code example has two DataMappers which typehint the interface they need in the constructor,

FooDataMapper type hints the Preparable interface. Because it dependens on it and no other method from the dependency.

In the other mapper, BarDataMapper i replaced the type hint with ??? as it requires both the Preparable and the Queryable interface.

How do i handle this (what should replace ???), typehinting a single of them would not suffice, should i make a new interface (maybe one that extends the previous mentioned) and hint this new interface?

The code example is a boiled down example in PHP and the type hint (???) is in the last Class declared.

```<code><?php
// TWO ROLE INTERFACES, SMALL SEGREGATED PART OF A DBAL

Interface Preparable {
  public function prepare( .. );
}

Interface Queryable {
  public function query( ... );
}

// ADAPTER IMPLEMENTS SEGREGATION

class DbalAdapter implements Preparable, Queryable {
  private $dbal;

  public function __construct($dbal)
  {
    private $this->dbal = $dbal;
  }

  public function prepare( .. )
  {
    ..
    return $this->dbal->prepare( .. );
  }

  public function query( .. )
  {
    ..
    return $this->dbal->query( .. );
  }
}

// DATAMAPPER CTOR HINTS FOR METHODS IT NEEDS TO USE

class FooDataMapper implements DataMapper {
  private $dbal;

  public function __construct(Preparable $dbal)
  {
    $this->dbal = $dbal;
  }

  public function create(Foo $Foo)
  {
    ..
    $this->dbal->prepare( .. )
  }
}

// DATAMAPPER CTOR HINTS FOR METHODS IT NEEDS TO USE
// BUT THIS TIME NONE OF THE ROLE INTERFACES MATCH, BUILD A NEW INTERFACE?

class BarDataMapper implements DataMapper {
  private $dbal;
  public function __construct(??? $dbal)
  {
    $this->dbal = $dbal;
  }

  public function SomeMethodThatNeedsBothPrepareNQuery(Bar $Bar)
  {
    ..
    $this->dbal->query( .. )
    $this->dbal->prepare( .. )
  }
}
</code>```

The initial solution i come to is making a new interface extending the ones needed.

Beware the naming of classes in the code are only for shown, might as well have been Fooable, BarAble...

答:
I think you are standing on one edge case, which can either mean that you have pushed software engineering in some place where PHP can't help you much or that you have some kind of conception problem.

According to the interface segregation principle the DataMapper interface should be strict enough for you to set one interface and one only that all your DataMappers implementations should match. Those implementation shouldn't expect any more specialized object.

One possible solution for your problem of using two interfaces at the same time, you could use traits with abstract methods (if >= PHP 5.4) instead of interface. But I wouldn't do that since it's trying to mimic "interface inheritance" by using traits composing capability.

If what you want is suggestion in your IDE you are not constrained to use type hinting (which is what you are doing). You can use the PHPDoc and your IDE may recognize what you are doing (I keep recommending PhpStorm):

```<code>/**
  * @param MySuperClass $a
  * @return void
  */
public function myFunction($a) {
    // Here your IDE will know what kind of object is $a
}
</code>```

Last point: don't try to do Java with PHP. At some point if you want to ensure what is the provided object you can use quick introspection to check the right usage of the right classes, subclasses, traits and interface.

Body:
I think you are standing on one edge case, which can either mean that you have pushed software engineering in some place where PHP can't help you much or that you have some kind of conception problem.

According to the interface segregation principle the DataMapper interface should be strict enough for you to set one interface and one only that all your DataMappers implementations should match. Those implementation shouldn't expect any more specialized object.

One possible solution for your problem of using two interfaces at the same time, you could use traits with abstract methods (if >= PHP 5.4) instead of interface. But I wouldn't do that since it's trying to mimic "interface inheritance" by using traits composing capability.

If what you want is suggestion in your IDE you are not constrained to use type hinting (which is what you are doing). You can use the PHPDoc and your IDE may recognize what you are doing (I keep recommending PhpStorm):

/**
  * @param MySuperClass $a
  * @return void
  */
public function myFunction($a) {
    // Here your IDE will know what kind of object is $a
}

Last point: don't try to do Java with PHP. At some point if you want to ensure what is the provided object you can use quick introspection to check the right usage of the right classes, subclasses, traits and interface.


问:
Unit testing methods with logical dependencies on other classes
Suppose I have an interface declaring the following method signature:

```<code>SearchResults SearchProducts(string type, string filter, string anotherFilter);
</code>```

Inside a concrete implementation of this, I instantiate a helper class (call it QueryBuilder), built to ease the construction of strongly-typed search queries for the specific search library I'm using. I want to unit test SearchProducts (ideally by mocking the query builder), which means I need to decouple the method from QueryBuilder.

How do I do this appropriately when the two things are logically coupled? That is to say:

It's not appropriate to pass an IQueryBuilder into the method as the implementation of IQueryBuilder is tightly coupled to the implementer of ISearchProducts, i.e. the types of the return values of QueryBuilder's methods are specific to the library being used in the concrete SearchService.

It's not appropriate to pass an instance of IQueryBuilder into the SearchService constructor (via DI or directly) as the logical scope of the query builder instance is local to the SearchProducts method call - it is instantiated in the method, its state is manipulated by adding sub-queries and a complete "query" is extracted for this SearchProducts call).

So, given the above, what's the appropriate way of handling this? It sounds like a case for a factory; however the implementation of this factory would be trivial and it seems a little contrived to define a factory interface and add a constructor parameter just for the sake of testability.

Is this indicative of a fundamental flaw in the design of my search interface? How do I decouple these things appropriately such that I can test both the search service and the query builder implementations in isolation?

答: This is the ideal use for Inversion of Control, or specifically, Dependency Injection.  In your test context, your query builder is the mock; in your normal execution context, it's the real deal.  No need for a factory, just a different context.</p>


答:
The consumer of dependencies is the one responsible for defining them (by means of their interfaces). In your example, BarDataMapper rules. I see two possible scenarios:

If BarDataMapper depends on a single object implementing both prepare() and query() methods, then yes, a proper PreparableAndQueryable interface should be defined including the two of them, and passed to the constructor. But then, perhaps you want to find another meaningful, non-composed name not hinting at bad separation of concerns.

If it makes sense for BarDataMapper to consume independent Preparable and Queryable dependencies, then its constructor takes them as separate parameters, even if in the end there's really one single object implementing both interfaces. Who's really implementing interfaces should not bother the one consuming them.

Title: Interface Segregation Principle - type hinting multiple interfaces

Body:
The question is about typehinting of the role interfaces.

The code example has two DataMappers which typehint the interface they need in the constructor,

FooDataMapper type hints the Preparable interface. Because it dependens on it and no other method from the dependency.

In the other mapper, BarDataMapper i replaced the type hint with ??? as it requires both the Preparable and the Queryable interface.

How do i handle this (what should replace ???), typehinting a single of them would not suffice, should i make a new interface (maybe one that extends the previous mentioned) and hint this new interface?

The code example is a boiled down example in PHP and the type hint (???) is in the last Class declared.

```<code><?php
// TWO ROLE INTERFACES, SMALL SEGREGATED PART OF A DBAL

Interface Preparable {
  public function prepare( .. );
}

Interface Queryable {
  public function query( ... );
}

// ADAPTER IMPLEMENTS SEGREGATION

class DbalAdapter implements Preparable, Queryable {
  private $dbal;

  public function __construct($dbal)
  {
    private $this->dbal = $dbal;
  }

  public function prepare( .. )
  {
    ..
    return $this->dbal->prepare( .. );
  }

  public function query( .. )
  {
    ..
    return $this->dbal->query( .. );
  }
}

// DATAMAPPER CTOR HINTS FOR METHODS IT NEEDS TO USE

class FooDataMapper implements DataMapper {
  private $dbal;

  public function __construct(Preparable $dbal)
  {
    $this->dbal = $dbal;
  }

  public function create(Foo $Foo)
  {
    ..
    $this->dbal->prepare( .. )
  }
}

// DATAMAPPER CTOR HINTS FOR METHODS IT NEEDS TO USE
// BUT THIS TIME NONE OF THE ROLE INTERFACES MATCH, BUILD A NEW INTERFACE?

class BarDataMapper implements DataMapper {
  private $dbal;
  public function __construct(??? $dbal)
  {
    $this->dbal = $dbal;
  }

  public function SomeMethodThatNeedsBothPrepareNQuery(Bar $Bar)
  {
    ..
    $this->dbal->query( .. )
    $this->dbal->prepare( .. )
  }
}
</code>```

The initial solution i come to is making a new interface extending the ones needed.

Beware the naming of classes in the code are only for shown, might as well have been Fooable, BarAble...


问:
Ensuring transactional consistency with DDD
I am starting out with DDD and understand that aggregate roots are used to ensure transnational consistency. We should not modify multiple aggregates in one application service.

I would like to know however how to deal with the following situation.

I have an aggregate root called Products.

There is also an aggregate root called Group.

Both have Id's, and can be edited independently.

Multiple Products can point to the same Group.

I have an application service that can change a product's group:

ProductService.ChangeProductGroup(string productId, string groupId)

Check group exists

Get product from repository

Set its group

Write the product back to repository

I also have an application service where the group can be deleted:

GroupService.DeleteGroup(string groupId)
 1. Get products from repository whose groupId is set to provided groupId, ensure count is 0 or abort
 2. Delete group from groups repository
 3. Save changes

My question is the following scenario, what would happen if:

In the ProductService.ChangeProductGroup, we check the group exists (it does), then just after this check a separate user deletes the productGroup (via the other GroupService.DeleteGroup). In this case we set a reference to a product which has just been deleted?

Is this a flaw in my design in that i should use a different domain design (adding additional elements if necessary), or would i have to use transactions?

答:
Why don't you store the product ids in the Group entity? This way you are only dealing with a single aggregate which will make things easier.

You will then need to implement some type of concurrency pattern e.g. If you choose optimistic concurrency simply add a version property to the Group entity and throw an exception if the versions don't match when updating i.e.

Add product to a group

Check if product exists

Get Group from repository (including its version id property)

Group.Add(ProductId)

Save Group using repository (update with new version id and add a where clause to ensure version has not changed.)

Lots of ORM's have optimistic concurrency built in using version ids or timestamps but it is easy to roll your own. Here is a good post on how its done in Nhibernate http://ayende.com/blog/3946/nhibernate-mapping-concurrency .


问:
Python - assert vs if & return
I am writing a script that does something to a text file (what it does is irrelevant for my question though). So before I do something to the file I want to check if the file exists. I can do this, no problem, but the issue is more that of aesthetics.

Here is my code, implementing the same thing in two different ways.

```<code>def modify_file(filename):
    assert os.path.isfile(filename), 'file does NOT exist.'

Traceback (most recent call last):
  File "clean_files.py", line 15, in <module>
    print(clean_file('tes3t.txt'))
  File "clean_files.py", line 8, in clean_file
    assert os.path.isfile(filename), 'file does NOT exist.'
AssertionError: file does NOT exist.
</code>```

or:

```<code>def modify_file(filename):
    if not os.path.isfile(filename):
        return 'file does NOT exist.'

file does NOT exist.
</code>```

The first method produces an output that is mostly trivial, the only thing I care about is that the file does not exist.

The second method returns a string, it is simple.

My questions is: which method is better for letting the user know that the file does not exist? Using the assert method seems somehow more pythonic.

答:
assert is intended for cases where the programmer calling the function made a mistake, as opposed to the user.  Using assert under that circumstance allows you to make sure a programmer is using your function correctly during testing, but then strip it out in production.

Its value is somewhat limited since you have to ensure you exercise that path through the code, and you often want to additionally handle the problem with a separate if statement in production.  assert is most useful in situations like, "I want to helpfully work around this problem if a user hits it, but if a developer hits it, I want it to crash hard so he will fix the code that calls this function incorrectly."

In your particular case, a missing file is almost certainly a user error, and should be handled by raising an exception.

Title: Python - assert vs if & return


答:
I think this is not a Domain-Driven Design specific question, but a resource management one.

Resources simply must be locked as they are acquired.

This is true when the application service knows in advance that the acquired resource (the Group aggregate, in your example) is going to be modified. In Domain-Driven Design, resource locking is an aspect that belongs to the repository.

Title: Ensuring transactional consistency with DDD

Body:
I am starting out with DDD and understand that aggregate roots are used to ensure transnational consistency. We should not modify multiple aggregates in one application service.

I would like to know however how to deal with the following situation.

I have an aggregate root called Products.

There is also an aggregate root called Group.

Both have Id's, and can be edited independently.

Multiple Products can point to the same Group.

I have an application service that can change a product's group:

ProductService.ChangeProductGroup(string productId, string groupId)

Check group exists

Get product from repository

Set its group

Write the product back to repository

I also have an application service where the group can be deleted:

GroupService.DeleteGroup(string groupId)
 1. Get products from repository whose groupId is set to provided groupId, ensure count is 0 or abort
 2. Delete group from groups repository
 3. Save changes

My question is the following scenario, what would happen if:

In the ProductService.ChangeProductGroup, we check the group exists (it does), then just after this check a separate user deletes the productGroup (via the other GroupService.DeleteGroup). In this case we set a reference to a product which has just been deleted?

Is this a flaw in my design in that i should use a different domain design (adding additional elements if necessary), or would i have to use transactions?


问:
Does late have any meaning in Agile methodologies?
This came out of some of the answers and comments on another question (this one).

I've worked primarily with waterfall projects and while I've worked on ad-hoc projects that have taken on agile behaviours and have read a fair bit about agile, I'd say I've never worked on a "proper" agile project.

My question is does the concept of "late" have any meaning in agile, if so then what?

My reasoning is that with agile you have no upfront plan and you have no detailed requirements at the outset.  You may have a high level goal in mind and a notional date attached to it but both may change (potentially massively) and neither are certain.

So if you don't know exactly what you're going to deliver basically until you deliver it and the user accepts it, and if you don't have a schedule beyond the next sprint, how could you ever be late in any way that actually has meaning?

(Obviously I understand that a sprint might overrun but I'm talking about beyond that.)

Just to be clear I'm (personally) happy with the assumption that on time waterfall projects (even relatively large ones) are possible based on the fact I've seen them and been involved in them - they're not easy or common even but they are possible.

This isn't about knocking agile, it's about me understanding it.  I've always seen the benefit of agile as nothing to do with deadlines or budgets (or rather only indirectly), it's to do with scope - agile delivers closer to what is really important rather than what the project team think is important before they've seen anything.

答:
I disagree that an Agile project has no upfront plan.

My experience is that the business analysts have spent a fair amount of time working in design meetings with customers and developers to come up with a detailed list of achievable requirements that are presented as user stories. These are then broken down into tasks with suitable estimates attached by experienced developers.

Once the most important tasks have been identified at the start of the sprint/iteration then coding can begin. This selection process determines the meaning of the iteration in the overall project ("We're building the login process"). Various memebers of the team get on with the various tasks necessary to make that user story happen.

At the end of the iteration all the user stories for that iteration should be complete, or you're late. Equally, development should be able to stop at the end of each iteration and the product released. It may not be complete in terms of all user stories, but those user stories that were requested in the iteration are complete and the product can work to those limits.


问:
Why should passwords be encrypted if they are being stored in a secure database?
I have a web service. Right now, I have passwords stored in plain text in a MySQL table on my server. I know this isn't the best practice, and that is why I am working on it.

Why should passwords be encrypted if they are being stored in a secure database? I realize that if someone hacks in to my database they will get everyone's password. But I have other problems if someone gets in my database, for example, deleting data.

The scenario I can think of is that you are hacked. You restore a database from a couple of hours ago and everything is well. However, if your passwords are plaintext... The thief has all the passwords and you have to reset them all. Hassle to your users.

If the passwords were encrypted, you could just restore to previous database. Is this correct thinking?

答:
First up, you should be more free with read-only access rights than read-write. It might be possible that a hacker has access to your data but isn't able to edit it.

But, much more importantly, this is not about you. The fact that you might be screwed if someone has full access to your database is irrelevant. Much more important is your user's data.

If you recover your database, the hacker still has access to your user's account.

And who knows what else? What if they use the same password at Google? Or PayPal? What if that gives a hacker access to their mother's maiden name, or the last 4 digits of their credit card?

What if that gets them into other accounts? Don't put it past a hacker to go through a user support system and get more info.

Just ... just don't. That's your user's private information and you don't need to be able to see it. It's also your reputation. Encrypt it.

EDIT: One extra comment, to save any future reader from reading every answer and comment ...

If you're going to encrypt (in the strictest sense) then you need to use a public / private key pair, which is fine but makes life a little bit more difficult for both you and your user.

A simpler, and just as effective, solution is to random-salt and hash the password. Hashing alone is not enough; if your user uses a common password, it will appear in reverse-hashing tables, which are readily available with a simple internet search.


答:
I won't repeat what other people have said, but assuming you have PHP 5.3.8 or better, you should be using the PHP native bcrypt to store your passwords. This is built into PHP. If you have PHP 5.5 you can use the best available password constant.
You can also use a library to make 5.3.8 or better behave like 5.5.

Stack Overflow question How do you use bcrypt for hashing passwords in PHP? explains it, and the other replies there explain more. Please don't mess around trying to do this yourself.

Body:
I have a web service. Right now, I have passwords stored in plain text in a MySQL table on my server. I know this isn't the best practice, and that is why I am working on it.

Why should passwords be encrypted if they are being stored in a secure database? I realize that if someone hacks in to my database they will get everyone's password. But I have other problems if someone gets in my database, for example, deleting data.

The scenario I can think of is that you are hacked. You restore a database from a couple of hours ago and everything is well. However, if your passwords are plaintext... The thief has all the passwords and you have to reset them all. Hassle to your users.

If the passwords were encrypted, you could just restore to previous database. Is this correct thinking?


答:
I agree with the answer from pdr, for the reasons stated in that answer.

I would add the following: you should do it because it is easy to do and generally accepted as best practice for any application.  More specifically, passwords should always be salted and hashed before writing to any persistent storage.  Here is a good reference on the importance of salting and choosing a good cryptographic hash (that also provides free source code in several popular languages): https://crackstation.net/hashing-security.htm

The small amount of extra development time is well worth the protection it provides your users, and to your reputation as a developer.

Title: Why should passwords be encrypted if they are being stored in a secure database?


答:
But I have other problems if someone gets in my database, i.e. deleting data.

It's not about the problems you have, it's about the problems it might cause for all your other users.  It's about removing temptation (or even worse, potential liability) for people working on the site to abuse data that's stored there.

See, even though people should use different passwords on different systems, the reality is that don't.

...and since it's so easy to hash passwords, you have no excuses for not following industry best practices.


答:
Noticeable attacks like deleting data are usually the stuff of amateurs, and are the least of your worries.  One of the first things an experienced attacker will do is attempt to gain legitimate access, so even if you patch the original vulnerability he used, he will still be able to get in.  He will do everything possible to avoid drawing attention to himself until he accomplishes what he desires.  By leaving passwords unhashed, you just potentially made his job a lot easier.  You also made it harder to detect and isolate his future malicious behavior.

Also, not all compromises give you full shell access.  What if the vulnerability an attacker used is just a read-only SQL injection on the users table?  Leaving passwords unhashed just gave him pretty much full access.

That's in addition to the reasons given by other answers about your responsibility to safeguard your users' data.  My point is, it's not just your users who have something to lose.


答:
Yes, but it will only take 1 month to know you won't hit your 9-month-mythical-final-project-due-date instead of 9.

Your reasoning is based on the assumption that upfront plans and detailed requirements for large projects are possible. Not sure there is a lot of evidence to support that. Maybe all the horror stories are just anecdotal? Any developer would love to work with complete and never changing specifications that the client fully agrees with and understands.

Title: Does late have any meaning in Agile methodologies?

Body:
This came out of some of the answers and comments on another question (this one).

I've worked primarily with waterfall projects and while I've worked on ad-hoc projects that have taken on agile behaviours and have read a fair bit about agile, I'd say I've never worked on a "proper" agile project.

My question is does the concept of "late" have any meaning in agile, if so then what?

My reasoning is that with agile you have no upfront plan and you have no detailed requirements at the outset.  You may have a high level goal in mind and a notional date attached to it but both may change (potentially massively) and neither are certain.

So if you don't know exactly what you're going to deliver basically until you deliver it and the user accepts it, and if you don't have a schedule beyond the next sprint, how could you ever be late in any way that actually has meaning?

(Obviously I understand that a sprint might overrun but I'm talking about beyond that.)

Just to be clear I'm (personally) happy with the assumption that on time waterfall projects (even relatively large ones) are possible based on the fact I've seen them and been involved in them - they're not easy or common even but they are possible.

This isn't about knocking agile, it's about me understanding it.  I've always seen the benefit of agile as nothing to do with deadlines or budgets (or rather only indirectly), it's to do with scope - agile delivers closer to what is really important rather than what the project team think is important before they've seen anything.


答:
If you get hacked you can restore the site from backups and fix it.  But the hacker still has passwords for everyone's accounts!  There are documented real world examples of this happening (Sony, Linked-in), where if the password tables had been properly hashed and salted, securing and restoring the sevice quickly would have been much easier.

It's probably a good idea to assume you will be hacked, and design your backup strategy and encrypt any sensitive data with this assumption in mind.  And it's not just hackers you need to protect against.  Disgruntled, dishonest, or just clueless employees could give away plain-text passwords.

Without hashing you will have to disable access for everyone until they change their password (which, even if possible, will be a huge headache for everyone).  If the passwords had been hashed and salted you could restore the web service and it would be much harder for an attacker to gain access to people's accounts.

A properly hashed and salted password is basically one-way.  You can't easily guess the password from the hashed password.  Even you, as the service provider won't be able to guess it, you can only reset it.

Also, as Elin said, don't try and roll your own hashing (or encryption).  Use a standard library.


问:
Help in (re)designing my Swing application
I have developed a Swing application that controls execution of several scripts like jobs. I need to display the interim output of the jobs concurrently. I have followed MVC while writing the application. The application is working as expected. But off late I have the following requirements in hand:

A few of the script jobs need special user privileges to execute so as to access specialized resources. There seems to be no way in Java to impersonate as a different user while running an application.[examined in this question]. Also trying to run the Swing application as a scheduled task in windows is not helping.

Once started the jobs should be running even if the user logs off after starting the jobs. I am thinking of separating the execution logic from the UI and run that as a service; and introduce JMS in between the two layers so as to store/retrieve the interim the output.

Note: I need to run this application on windows.

Any ideas on meeting my requirements, will be highly appreciated.

答: I designed my application as a 3 part architecture. A GUI part, a model part which runs as a windows service using IBM service wrapper and a JMS messaging middleware to communicate between the previous 2 components.</p>


问:
Testing vs Don't Repeat Yourself (DRY)
Why is repeating yourself by writing tests so highly encouraged?

It seems that tests basically express the same thing as the code, and hence is a duplicate (in concept, not implementation) of the code. Wouldn't the ultimate target of DRY include elimination of all test code?

答:
It seems that tests basically express the same thing as the code, and hence is a duplicate

No, this is not true.

Tests have a different purpose than your implementation:

Tests make sure that your implementation works.

They serve as a documentation: By looking at the tests, you see the contracts which your code must fulfil, i.e. which input returns what output, what are the special cases etc.

Also, your tests guarantee that as you add new features, your existing functionality does not break.

Title: Testing vs Don't Repeat Yourself (DRY)


问:
Programming with Dyslexia
I have very severe Dyslexia along with Dysnomia and Dysgraphia. I have known about it since I was a child. My reading and writing skills are pretty crippled, but I have learned to deal with it.

However, with today's IDEs, I find it very easy to stay focused and in the zone when I code. But when I write text (like this post) I find it much harder to stay focused.

In general, do dyslexics find it easier to read and write code compared to general reading and writing? What types of tricks and tools do dyslexics use to help them master programming better than normal reading and writing?

答:
"I've tutored a number of dyslexic programmers and it has always surprised me that they find it easier to write/type when using an IDE as opposed to say a text doc."

I'm dyslexic and have been programming since 1972: I was surprised that it was impossible for me to learn python without an IDE. I didn't have difficulty using Visual Studio for .Net etc.

The problems with all print:

dyslexics find it extremely difficult to follow a long line of text all the way to the end and to easily follow the next line in sequence.
  Their eye movements while reading make it harder to scan the text smoothly (saccade)
  http://www.optomotorik.de/dyslex/index-e.htm

The errors that result from not being able to scan a page as accurately as most others do have to be noticed, understood, thought about in the context used, and finally corrected.
Dyslexics are not aware of mis reading. Programming languages require syntax that is correct.

IDE's provide a visual structure that assists the dyslexic to read and code with fewer errors.
A single window with sub windows for different tasks prevents the dyslexic coder from becoming lost on the page. It reduces visual stress, like having rails on a bridge does for drivers.

Similar symbols that appear to be the same to a dyslexic are difficult to find and fix. Automatic syntax highlighting saves a ton of time looking over the error codes.

Code completion is a workaround for typing in the wrong character, looking up functions is a great help.

I don't know how people can code in an environment that allows the eye to wander and does not mark wrong syntax.
Having the right IDE allows a dyslexic to program without losing time. A familiar IDE is comfortable to work in, similar to using a tool that feels right in your hand.

Dyslexic programmers tend to think visually in design blocks of code function rather than in lines of characters. Each functional block has to be translated into code.
The benefit of thinking in functional blocks rather than code is that one does not become confused by large systems because a visual of the system can be used to map the code.

Title: Programming with Dyslexia


问:
Is mentioning my blog on my resume helpful or hurtful to a job search?
I have a blog that I use mostly to record solutions to problems I have had, that I had some trouble finding an answer to. Mostly problems where the online doc I googled provided too much info, and I found the answer to my question on the fifth page of my third google hit.

(Or if I asked the question here, I either didn't get an answer or I got slammed for asking a question that "the answer could be easily googled.")

I frequently look up stuff on this blog to remind myself of how I solved a problem, and it gets a decent amount of hits from others as well.

Anyway, I was wondering if mentioning this blog on my resume would help or hurt me in a job search? The topics are all over the map.

What I would hope it shows is that

I am a person who finds solutions to problems

I have used many different technologies in my work

I am not afraid to tackle a challenge

What I am concerned it shows is that

This person had trouble with something that simple?

Why is this person bothering to blog this stuff?

答: did you put something crazy in your blog?  does it have anything to do with your work?  It won't hurt to put in your blog if it has something to do with your work.  A family blog would be okay but might not influence me that much.</p>


答: Because sometimes repeating yourself is okay. None of these principles are meant to be taken in every circumstance without question or context. I have at times written tests against a naïve (and slow) version of an algorithm, which is a fairly clear-cut violation of DRY, but definitely beneficial.</p>

Title: Testing vs Don't Repeat Yourself (DRY)

Body:
Why is repeating yourself by writing tests so highly encouraged?

It seems that tests basically express the same thing as the code, and hence is a duplicate (in concept, not implementation) of the code. Wouldn't the ultimate target of DRY include elimination of all test code?


答: No.  DRY is about writing code just once to do a particular task, test are validation that the task is being done correctly. It's somewhat akin to a voting algorithm, where obviously using the same code would be useless.</p>

Title: Testing vs Don't Repeat Yourself (DRY)


问:
Workaround for Java checked exceptions
I appreciate a lot the new Java 8 features about lambdas and default methods interfaces. Yet, I still get bored with checked exceptions. For instance, if I just want to list all the visible fields of an object I would like to simply write this:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
        f -> System.out.println(f.get(p))
    );
</code>```

Yet, since the get method might throw a checked exception, which does not agrees with the Consumer interface contract, then I must catch that exception and write the following code:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
            f -> {
                try {
                    System.out.println(f.get(p));
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    throw new RuntimeException(ex);
                }
            }
    );
</code>```

However in most cases I just want the exception to be thrown as a RuntimeException and let the program handle, or not, the exception without compilation errors.

So, I would like to have your opinion about my controversial workaround for checked exceptions annoyance. To that end, I created an auxiliary interface ConsumerCheckException<T> and an utility function rethrow (updated according to the sugestion of Doval's comment) as follows:

```<code>  @FunctionalInterface
  public interface ConsumerCheckException<T>{
      void accept(T elem) throws Exception;
  }

  public class Wrappers {
      public static <T> Consumer<T> rethrow(ConsumerCheckException<T> c) {
        return elem -> {
          try {
            c.accept(elem);
          } catch (Exception ex) {
            /**
             * within sneakyThrow() we cast to the parameterized type T.
             * In this case that type is RuntimeException.
             * At runtime, however, the generic types have been erased, so
             * that there is no T type anymore to cast to, so the cast
             * disappears.
             */
            Wrappers.<RuntimeException>sneakyThrow(ex);
          }
        };
      }

      /**
       * Reinier Zwitserloot who, as far as I know, had the first mention of this
       * technique in 2009 on the java posse mailing list.
       * http://www.mail-archive.com/javaposse@googlegroups.com/msg05984.html
       */
      public static <T extends Throwable> T sneakyThrow(Throwable t) {
          throw (T) t;
      }
  }
</code>```

And now I can just write:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
            rethrow(f -> System.out.println(f.get(p)))
    );
</code>```

I am not sure that this is the best idiom to turn around the checked exceptions, but as I explained, I would like to have a more convenient way of achieving my first example without dealing with checked exceptions and this is the simpler way that I found to do it.

答:
In this example, can it ever really fail?  Don't think so, but maybe your case is special.  If it really "can't fail", and its just an annoying compiler thing, I like to wrap the exception and throw an Error with a comment "cannot happen".  Makes things very clear for maintenance.  Otherwise they will wonder "how can this happen" and "who the heck handles this?"

This in a controversial practice so YMMV.  I'll probably get some downvotes.

Title: Workaround for Java checked exceptions


答:
I believe this is a misconception any way I can think of.

The test-code that tests production-code is not at all similar. I'll demonstrate in python:

def multiply(a, b):
    """Multiply ``a`` by ``b``"""
    return a*b
```

<p>Then a simple test would be:</p>

<pre class="lang-py prettyprint-override"><code>def test_multiply():
    assert multiply(4, 5) == 20
</code>```

Both functions have a similar definition but both do very different things. No duplicate code here. ;-)

It also occurs that people write duplicate tests essentially having one assertion per test function. This is madness and I have seen people doing this. This is bad practice.

def test_multiply_1_and_3():
    """Assert that a multiplication of 1 and 3 is 3."""
    assert multiply(1, 3) == 3

def test_multiply_1_and_7():
    """Assert that a multiplication of 1 and 7 is 7."""
    assert multiply(1, 7) == 7

def test_multiply_3_and_4():
    """Assert that a multiplication of 3 and 4 is 12."""
    assert multiply(3, 4) == 12
```

<p>Imagine doing this for 1000+ effective lines of code. Instead you test on a per 'feature' basis:</p>

<pre class="lang-py prettyprint-override"><code>def test_multiply_positive():
    """Assert that positive numbers can be multiplied."""
    assert multiply(1, 3) == 3
    assert multiply(1, 7) == 7
    assert multiply(3, 4) == 12

def test_multiply_negative():
    """Assert that negative numbers can be multiplied."""
    assert multiply(1, -3) == -3
    assert multiply(-1, -7) == 7
    assert multiply(-3, 4) == -12
</code>```

Now when features are added/removed I only have to consider adding/removing one test function.

You may have noticed I have not applied for loops. This is because repeating some things is good. When I would have applied loops the code would be a lot shorter. But when an assertion fails it could obfuscate the output displaying an ambiguous message. If this occurs then your tests will be less useful and you will need a debugger to inspect where things go wrong.

Title: Testing vs Don't Repeat Yourself (DRY)

Body:
I believe this is a misconception any way I can think of.

The test-code that tests production-code is not at all similar. I'll demonstrate in python:

def multiply(a, b):
    """Multiply ``a`` by ``b``"""
    return a*b

Then a simple test would be:

def test_multiply():
    assert multiply(4, 5) == 20

Both functions have a similar definition but both do very different things. No duplicate code here. ;-)

It also occurs that people write duplicate tests essentially having one assertion per test function. This is madness and I have seen people doing this. This is bad practice.

def test_multiply_1_and_3():
    """Assert that a multiplication of 1 and 3 is 3."""
    assert multiply(1, 3) == 3

def test_multiply_1_and_7():
    """Assert that a multiplication of 1 and 7 is 7."""
    assert multiply(1, 7) == 7

def test_multiply_3_and_4():
    """Assert that a multiplication of 3 and 4 is 12."""
    assert multiply(3, 4) == 12

Imagine doing this for 1000+ effective lines of code. Instead you test on a per 'feature' basis:

def test_multiply_positive():
    """Assert that positive numbers can be multiplied."""
    assert multiply(1, 3) == 3
    assert multiply(1, 7) == 7
    assert multiply(3, 4) == 12

def test_multiply_negative():
    """Assert that negative numbers can be multiplied."""
    assert multiply(1, -3) == -3
    assert multiply(-1, -7) == 7
    assert multiply(-3, 4) == -12

Now when features are added/removed I only have to consider adding/removing one test function.

You may have noticed I have not applied for loops. This is because repeating some things is good. When I would have applied loops the code would be a lot shorter. But when an assertion fails it could obfuscate the output displaying an ambiguous message. If this occurs then your tests will be less useful and you will need a debugger to inspect where things go wrong.

ContentLicense: CC BY-SA 4.0


答:
Since unit-testing is about making unintentional changes harder, it can sometimes make intentional changes harder, too. This fact is indeed related to the DRY principle.

For example, if you have a function MyFunction which is called in production code in just one place, and you write 20 unit tests for it, you can easily end up having 21 places in your code where that function is called. Now, when you have to change the signature of MyFunction, or the semantics, or both (because some requirements change), you have 21 places to change instead of just one. And the reason is indeed a violation of the DRY principle: you repeated (at least) the same function call to MyFunction 21 times.

The correct approach for such a case is applying the DRY principle to your testing code as well: when writing 20 unit tests, encapsulate the calls to MyFunction in your unit tests in just a few helper functions (ideally just one), which are used by the 20 unit tests. Ideally, you end up with just two places in your code calling MyFunction: one from your production code, and one from you unit tests. So when you have to change the signature of MyFunction later, you will have only a few places to change in your tests.

"A few places" are still more than "one place" (what you get with no unit tests at all), but the advantages of having unit tests should heavily outweigh the advantage of having less code to change (otherwise you doing unit testing completly wrong).

Title: Testing vs Don't Repeat Yourself (DRY)


问:
What difference with Android when iOS is not open?
My question may seem silly, but, I've read in many Android books that the better part of Android is Android is open, and iOS is closed.

But, from a programmer viewpoint, who cares about this point? Programmers just care about the platform: is it easy to program in, easy to have help in the network, etc. They don't care about whether the platform is open or closed.

One book had additional information, but I don't understand it much. Since iOS is not open, I’d be able to share my work with others only if Apple allowed it.

So, if you write an app, and need to share, you must have Apple's permission, but not Android's?

Please help me understand this point. I'm preparing for a presentation on Android. And I don't know if I should put this point into my presentation.

答: Android is a open source because is provide the source code while in ios is closed so,that it not provide the source code.</p>


答:
Because Android is open-source is more appealing to be installed on many other devices, different than smartphones and tablets (for example wearable devices, cars, game consoles, TV media players and many others). Besides that, different manufacturers can easily customize Android, on their specific phones but still be able to use all the apps.

This means that Android is used in tens of devices from tens of different vendors while iOS is used in 2 devices (iPhone and iPad) from just one vendor (Apple).
As a programmer in Android you are able to program for all of devices while on iOS you are know to program only for iPhone and iPad.

Also Android is based on Linux, so the source code is not entirely strange or undocumented.

Title: What difference with Android when iOS is not open?

Body:
My question may seem silly, but, I've read in many Android books that the better part of Android is Android is open, and iOS is closed.

But, from a programmer viewpoint, who cares about this point? Programmers just care about the platform: is it easy to program in, easy to have help in the network, etc. They don't care about whether the platform is open or closed.

One book had additional information, but I don't understand it much. Since iOS is not open, I’d be able to share my work with others only if Apple allowed it.

So, if you write an app, and need to share, you must have Apple's permission, but not Android's?

Please help me understand this point. I'm preparing for a presentation on Android. And I don't know if I should put this point into my presentation.


问:
how to do database updates in each release
Our application uses database (mostly Oracle), and database is at the core. Each customer has its own database, with its own copy of application. Now with each new release of our product, we also need to update the database schema. These changes are adding new tables, removing columns, manipulating data etc. How do the people handle this? Are there any standard processes for this? </p>

<p>EDIT:- The main issue is the databases are huge with many tables and more of huge amount of data. We provide the scripts and some utilities to manipulate the data. How to handle the failures and false negatives? More of looking for this kind articles.
http://thedailywtf.com/Articles/Database-Changes-Done-Right.aspx </p>

答:
It depends of the actual language, framework, platform and other things.
If it's Java (standalone or EE), the best solution could be Liquibase while there are other solutions also.</p>


答: For one, even database administrators should not see the users' passwords. Hashing them will prevent this in case the administrator decides to look at a password and login into their users' account.</p>


问:
How do you move beyond code examples without a project?
I am currently learning Scala and I find a mental blog of how to proceed to a degree where I can use Scala daily beyond the normal examples. I just do not have a particular project in mind of what I can do.

This is not really Scala specific in mind, just generally how do you get yourself proficient in a language via self learning without doing / having a project in your hand?

答:
Nothing replaces a real project, but I find Code Katas are a good way to get your hands dirty solving real problems with the language. The nice thing is, many solutions are available online so you'll be able to compare them with your own and hopefully learn from that. It will also make you more familiar with a test environment.

There are some Scala specific katas out there as well as platforms where you can submit your solutions and get feedback on them.


问:
Are classes with only a single (public) method a problem?
I am currently working on a software project that performs compression and indexing on video surveillance footage. The compression works by splitting background and foreground objects, then saving the background as a static image, and the foreground as a sprite.

Recently, I have embarked on reviewing some of the classes that I have designed for the project.

I noticed that there are many classes that only have a single public method. Some of these classes are:

VideoCompressor (with a compress method that takes in an input video of type RawVideo and returns an output video of type CompressedVideo).

VideoSplitter (with a split method that takes in an input video of type RawVideo and returns a vector of 2 output videos, each of type RawVideo).

VideoIndexer (with an index method that takes in an input video of type RawVideo and returns a video index of type VideoIndex).

I find myself instantiating each class just to make calls like VideoCompressor.compress(...), VideoSplitter.split(...), VideoIndexer.index(...).

On the surface, I do think the class names are sufficiently descriptive of their intended function, and they are actually nouns. Correspondingly, their methods are also verbs.

Is this actually a problem?

答:
```<code>public interface IVideoProcessor
{
   void Split();

   void Compress();

   void Index();
}
</code>```

What you've got is modular and that's good, but if you were to group these responsibilities into IVideoProcessor, that would probably make more sense from DDD point of view.

On the other hand, if splitting, compressing and indexing wasn't related in any way, than I'd keep them as separate components.

Body:
public interface IVideoProcessor
{
   void Split();

   void Compress();

   void Index();
}

What you've got is modular and that's good, but if you were to group these responsibilities into IVideoProcessor, that would probably make more sense from DDD point of view.

On the other hand, if splitting, compressing and indexing wasn't related in any way, than I'd keep them as separate components.


问:
Preventing some downsides of a static class
Here is my situation. I have implemented the accepted .NET 4.0 answer in this question, which is working.

However, my codebase is quite large and as responsible for this code I've started getting inquiries regarding this solution. I've been asked if there are no easier ways of accomplishing the same thing, and if there is any way to shorten the usage.

In almost all cases, this class is used to get or set a single property only. This favors other solutions, since the usage ends up like this: new UserSessionData().CustomerNumber = 123;

The closest thing I have is a class (static or not) with static members and methods, like this:

```<code>public static class UserSessionData
{
    public static Dictionary<string, string> AsDictionary()
    {
        return typeof(UserSessionData).GetProperties()
                   .ToDictionary(p => p.Name, p => p.GetValue(null, null) as string);
    }
    private static string Get(Expression<Func<string>> e)
    {
        var me = e.Body as MemberExpression;
        return ExternalInterfaceClass.Get(me.Member.Name);
    }
    private static void Set(Expression<Func<string>> e, string value)
    {
        var me = e.Body as MemberExpression;
        ExternalInterfaceClass.Set(me.Member.Name, value);
    }

    public static string CustomerNumber {
        get { return Get(() => CustomerNumber); }
        set { Set(() => CustomerNumber, value); }
    }

    // ... and hundreds more properties similar to "CustomerNumber"
}
</code>```

This feels like a quite good solution:

It's strongly typed (i.e. I can easily refactor CustomerNumber throughout)

Usage is great (UserSessionData.CustomerNumber = 123;)

The boilerplate is not that ugly - I think it's acceptable

However, there is one issue that I can't wrap my head around. Sometimes we need to be able to use this a little differently, A) as a return type and B) bulk-editing the structure before saving. As for A, I understand that a static class cannot be used as a return type, however I don't know what my alternatives would be in this specific situation?

As for B, I guess that I could delay the actual saving by providing a stated subclass and requiring explicit save, but the usage would be worsened for the normal use case (setting or getting a single property) since every one-liner would have to be followed by a call to the save method.

I thought about creating an interface for the class but interfaces can't define static properties. I'm feeling a little muddled here, help is appreciated. Please provide a minimal code example when presenting your thoughts, if possible - it clarifies the point a lot.

答:
First off: It seems weird that the class is abstract. An abstract class is meant to be a base class which cannot be instantiated and contains some abstract methods which need to implemented by derived classes. If all your methods and properties on the class are static and you don't want the class to be able to be instantiated then you can simply make the class static too:

```<code>public static class UserSessionData
{
    ... // all static methods and properties and fields
</code>```

Secondly: Don't do it like this. Seriously. Don't.

Your example code shows that your UserSessionData class also accesses an ExternalInterfaceClass which also seems to be a static class. This is getting real nasty here - global state galore. Unit testing code like this is hugely painful (been there done that).

I don't see the reason why the class should be static. There is nothing wrong with having an instance of it which being passed around. Going even further the class should get the external interface injected as a dependency so you can mock it out. Incidentally this could provide you wit ha solution to your bulk editing problem.

Let's try something:

```<code>public class UserSessionData : IUserSessionData
{
    private IExternalInterface _ExternalInterface;

    public UserSessionData(IExternalInterface externalInterface)
    {
        _ExternalInterface = externalInterface;
    }

    protected virtual string Get(Expression<Func<string>> e)
    {
        var me = e.Body as MemberExpression;
        return _ExternalInterface.Get(me.Member.Name);
    }

    protected virtual void Set(Expression<Func<string>> e, string value)
    {
        var me = e.Body as MemberExpression;
        _ExternalInterface.Set(me.Member.Name, value);
    }

    public Dictionary<string, string> AsDictionary()
    {
        return typeof(UserSessionData).GetProperties()
                   .ToDictionary(p => p.Name, p => p.GetValue(this) as string);
    }

    public IBulkEditableUserSessionData AsBulkEditable()
    {
        return new BulkEditableUserSessionData(_ExternalInterface);
    }

    public string CustomerNumber {
        get { return Get(() => CustomerNumber); }
        set { Set(() => CustomerNumber, value); }
    }

    // ... hundreds of properties

    private class BulkEditableUserSessionData : UserSessionData, IBulkEditableUserSessionData
    {
        private Dictionary<string, string> _EditCache = new Dictionary<string, string>();

        public BulkEditableUserSessionData(IExternalInterface externalInterface)
            : base(externalInterface)
        {
        }

        protected override string Get(Expression<Func<string>> e)
        {
            var fieldName = ((MemberExpression)e.Body).Member.Name;
            // return modified value from cache if present
            string value;
            if (_EditCache.TryGet(fieldName, out value))
            {
                return value;
            }
            return _ExternalInterface.Get(fieldName);
        }

        protected virtual void Set(Expression<Func<string>> e, string value)
        {
            var fieldName = ((MemberExpression)e.Body).Member.Name;
            _EditCache[fieldName] = value;
        }

        public void Save()
        {
            foreach (var kvp in _EditCache)
            {
                _ExternalInterface.Set(kvp.Key, kvp.Value);
            }
        }
    }
}

public interface IExternalInterface
{
    string Get(string fieldName);
    void Set(string fieldName, string value);
}

public interface IUserSessionData
{
    Dictionary<string, string> AsDictionary();

    string CustomerNumber { get; set; }

    // .. all the other hundreds of properties
}

public interface IBulkEditableUserSessionData : IUserSessionData
{
    void Save();
}
</code>```

Intended usage:

At one point in the application life cycle (presumably somewhere in the initialization phase) a UserDataSession instance gets created and the external interface injected.

Any code which needs access to the user session data gets given that instance (e.g. passed through as constructor parameter) and can use it like this:

```<code>public class BusinessClass
{
    private IUserSessionData _UserSessionData;

    public BusinessClass(..., IUserSessionData userSessionData, ...)
    {
        _UserSessionData = userSessionData;
    }

    public void UpdateCustomerNumber(string newCustomerNumber)
    {
        _UserSessionData.CustomerNumber = newCustomerNumber;
    }

    public void UpdateManyProperties()
    {
        var bulkEdit = _UserSessionData.AsBulkEditable();

        bulkEdit.CustomerNumber = ...
        bulkEdit.CustomerPhone = ...
        bulkEdit.CustomerWhatever = ...

        bulkEdit.Save();
    }
}
</code>```

The design can be refined and probably needs adjustment based on your use cases but should illustrate the idea.

Slight downside is that you have to add new properties to the class and the interface but that should not be too much of a problem. If you forget to add it to the interface your users will be complaining that it's not available. And if you forget to add it to the implementation the compiler will complain.

OwnerDisplayName: Simeon

Body:
First off: It seems weird that the class is abstract. An abstract class is meant to be a base class which cannot be instantiated and contains some abstract methods which need to implemented by derived classes. If all your methods and properties on the class are static and you don't want the class to be able to be instantiated then you can simply make the class static too:

public static class UserSessionData
{
    ... // all static methods and properties and fields

Secondly: Don't do it like this. Seriously. Don't.

Your example code shows that your UserSessionData class also accesses an ExternalInterfaceClass which also seems to be a static class. This is getting real nasty here - global state galore. Unit testing code like this is hugely painful (been there done that).

I don't see the reason why the class should be static. There is nothing wrong with having an instance of it which being passed around. Going even further the class should get the external interface injected as a dependency so you can mock it out. Incidentally this could provide you wit ha solution to your bulk editing problem.

Let's try something:

public class UserSessionData : IUserSessionData
{
    private IExternalInterface _ExternalInterface;

    public UserSessionData(IExternalInterface externalInterface)
    {
        _ExternalInterface = externalInterface;
    }

    protected virtual string Get(Expression<Func<string>> e)
    {
        var me = e.Body as MemberExpression;
        return _ExternalInterface.Get(me.Member.Name);
    }

    protected virtual void Set(Expression<Func<string>> e, string value)
    {
        var me = e.Body as MemberExpression;
        _ExternalInterface.Set(me.Member.Name, value);
    }

    public Dictionary<string, string> AsDictionary()
    {
        return typeof(UserSessionData).GetProperties()
                   .ToDictionary(p => p.Name, p => p.GetValue(this) as string);
    }

    public IBulkEditableUserSessionData AsBulkEditable()
    {
        return new BulkEditableUserSessionData(_ExternalInterface);
    }

    public string CustomerNumber {
        get { return Get(() => CustomerNumber); }
        set { Set(() => CustomerNumber, value); }
    }

    // ... hundreds of properties

    private class BulkEditableUserSessionData : UserSessionData, IBulkEditableUserSessionData
    {
        private Dictionary<string, string> _EditCache = new Dictionary<string, string>();

        public BulkEditableUserSessionData(IExternalInterface externalInterface)
            : base(externalInterface)
        {
        }

        protected override string Get(Expression<Func<string>> e)
        {
            var fieldName = ((MemberExpression)e.Body).Member.Name;
            // return modified value from cache if present
            string value;
            if (_EditCache.TryGet(fieldName, out value))
            {
                return value;
            }
            return _ExternalInterface.Get(fieldName);
        }

        protected virtual void Set(Expression<Func<string>> e, string value)
        {
            var fieldName = ((MemberExpression)e.Body).Member.Name;
            _EditCache[fieldName] = value;
        }

        public void Save()
        {
            foreach (var kvp in _EditCache)
            {
                _ExternalInterface.Set(kvp.Key, kvp.Value);
            }
        }
    }
}

public interface IExternalInterface
{
    string Get(string fieldName);
    void Set(string fieldName, string value);
}

public interface IUserSessionData
{
    Dictionary<string, string> AsDictionary();

    string CustomerNumber { get; set; }

    // .. all the other hundreds of properties
}

public interface IBulkEditableUserSessionData : IUserSessionData
{
    void Save();
}

Intended usage:

At one point in the application life cycle (presumably somewhere in the initialization phase) a UserDataSession instance gets created and the external interface injected.

Any code which needs access to the user session data gets given that instance (e.g. passed through as constructor parameter) and can use it like this:

public class BusinessClass
{
    private IUserSessionData _UserSessionData;

    public BusinessClass(..., IUserSessionData userSessionData, ...)
    {
        _UserSessionData = userSessionData;
    }

    public void UpdateCustomerNumber(string newCustomerNumber)
    {
        _UserSessionData.CustomerNumber = newCustomerNumber;
    }

    public void UpdateManyProperties()
    {
        var bulkEdit = _UserSessionData.AsBulkEditable();

        bulkEdit.CustomerNumber = ...
        bulkEdit.CustomerPhone = ...
        bulkEdit.CustomerWhatever = ...

        bulkEdit.Save();
    }
}

The design can be refined and probably needs adjustment based on your use cases but should illustrate the idea.

Slight downside is that you have to add new properties to the class and the interface but that should not be too much of a problem. If you forget to add it to the interface your users will be complaining that it's not available. And if you forget to add it to the implementation the compiler will complain.


答:
There is an important principle at stake here.  There is only one person who has any business knowing a users password.  That's the user.  Not their wife/husband, their doctor or even their priest.

It definitely does not include the programmer, database administrator or system technician responsible the the service they are using. That creates a challenge, as the programmer does have a responsibility to receive prove that the user actually knows the password, which is a non trivial problem to solve in a pure way.

The pure solution is to have a mechanism where the user is challenged with some new and unpredictable data, and then has to return a response that is based on this data and their password.  One implementation of this would be to ask the user to digitally sign some newly generated data with their digital signature, and we could mathematically prove that they used the same cryptographic key pair that they used to originally create the account.

In practice, the pure solutions require substantial client side infrastructure and processing, and for many websites, this is often not appropriate for the data being protected.

A more common solution would be:

At the point where a password is first received in the application, the password is passed to hashing function, along with you application's random 'salt' value into the hash function.

The original string is then overwritten in memory, and from this point on, the salted hash is stored in the database or compared with the database record.

The key aspects that provide security here are:

Knowledge of the hash does not directly provide authentication.

Reverse calculation of the password from the hash is impractical.

The use of rainbow tables (long lists of passwords and their calculated hashes) is made more challenging because the resulting hash is
dependent on both username and password.


问:
available methods change with object state
I'm programming a graph object which can be in either a mutable or immutable state. In both states, it has a get method, but only in the mutable state is the set method allowed. The transition occurs when one invokes a method compress which optimizes the storage of the graph.

How do I deal with the fact that some methods are legal in some states but not others?

I can think of two approaches. The blunt way is to use the state pattern. If you invoke set when the graph is mutable, it executes as normally; but, if you invoke set when the graph is immutable, an error is thrown. This looks ugly to me because an immutable object still has a set method.

Alternatively, I can make a graph type with a mutable_graph sub-type; only the second one has a set method. The state change is effected by changing the type of the graph. However, this also looks ugly to me; for every implementation of graph (of which there are several), I now have to make two types instead of just one.

EDIT: I'm using the state pattern and throwing an exception; if neither solution is especially preferable, this one involves writing the least code. Thanks for the advice!

答:
I would prefer to throw an exception, because it is:

easy to understand

easy to implement (and read)

easy to test

Maybe it looks not to perfect, but the best design is still "As Simple as Possible, as Complex as Necessary"! And one of the most implemented anti-designs is "over engineered and too complicate without a business value"!

E.g. in java the interface List describes multiple methods that could throw exception too (because they have not to be implemented a implementation) - but otherwise (with multiple interfaces for each case) the List interfaces would be over engineered and would definitely be very complicated..


问:
Unit tests tactics
The only unit tests tactic I'm familiar with is comparing against golden data _ a predefined set of input data for which output is known (preferably including corner cases).

I cannot think of any other reasonable way of unit testing. Trying to unit test using arbitrary input data is (at least) as difficult as writing the application itself.

Are there any effective tactics for unit testing other than golden data testing?

Note: By saying arbitrary data I mean any syntactically valid input which a method can accept (including logically invalid inputs).

答: You might want to have a look at equivalence partitioning vs boundary value analysis. Testing against "golden data" (boundary value analysis) is indeed the best compromise, giving good enough confidence that everything is covered in most cases.</p>

Title: Unit tests tactics


问:
How to limit time period to another period?
For a project planning I have an initial period, lets call it PPStart-PPEnd.

The planning is associated with a project. This also has a period PrjStart-PrjEnd. PrjStart and PrjEnd are fixed, and can be unbound, i.e. the project start time or end time are not defined.

PPStart-PPEnd should be adjusted so that people can only plan tasks in the valid project period. If that changes the duration, fine.

How do I efficiently limit PPStart-PPEnd to PrjStart-PrjEnd without having to go over all the possible combinations?

Maybe first detecting overlapping periods is a good start?

4 examples on a time axis ([-- = bound, <-- = unbound):

```<code>Project planning period:
                              [---PPStart-PPEnd---]
Project periods relative to ppp:
                                    [---PrjStart-PrjEnd---]   PPStart should be set to PrjStart, PPEnd unchanged
                     [---PrjStart-PrjEnd---]                  PPEnd should be set to PrjEnd, PPStart unchanged
                     [---PrjStart-PrjEnd------------------->  No adjustments
    [---PrjStart-PrjEnd---]                                   PPStart should be set to PrjStart and PPEnd to PrjEnd.
</code>```

Cases like that last one make it complex.

答:
If I understand your question correctly, you're asking how you can adjust time intervals without having a tangle of if elseifs checking every possibility, am I right?

You can simplify things a bit by looking at one date at a time.  In other words, don't think in terms of checking if the start and end are outside the interval and if so, adjust both start and end.

Think of it rather in terms of:

```<code>Is both PrjStart and PrjEnd less than PPStart or is both PrjStart and PrjEnd greater than PPEnd?  If yes, update both values.

Is PPStart not open-ended and less than PrjStart?  If yes, then update PPStart to the value of PrjStart.

Is PPEnd not open-ended and greater than PrjEnd?  If yes, then update PPEnd to the value of PrjEnd.
</code>```

You'll find that this satisfies all your conditions.  If you try to handle it in terms of both PPStart and PPEnd, then you'll have to cover every combination of these two dates with those of PrjStart and PrjEnd.  The reason you'd have to check if both are over or under is because only in that instance do the latter two rules differ.  In other words, if they overlap, you're willing to shorten the planning period whereas when there is no overlap, the entire period is set.

Body:
If I understand your question correctly, you're asking how you can adjust time intervals without having a tangle of if elseifs checking every possibility, am I right?

You can simplify things a bit by looking at one date at a time.  In other words, don't think in terms of checking if the start and end are outside the interval and if so, adjust both start and end.

Think of it rather in terms of:

Is both PrjStart and PrjEnd less than PPStart or is both PrjStart and PrjEnd greater than PPEnd?  If yes, update both values.

Is PPStart not open-ended and less than PrjStart?  If yes, then update PPStart to the value of PrjStart.

Is PPEnd not open-ended and greater than PrjEnd?  If yes, then update PPEnd to the value of PrjEnd.

You'll find that this satisfies all your conditions.  If you try to handle it in terms of both PPStart and PPEnd, then you'll have to cover every combination of these two dates with those of PrjStart and PrjEnd.  The reason you'd have to check if both are over or under is because only in that instance do the latter two rules differ.  In other words, if they overlap, you're willing to shorten the planning period whereas when there is no overlap, the entire period is set.


问:
What semantics should be used when referring to waterfall and agile methodologies
I've just been involved in a debate regarding semantics of how to define approaches to the software development lifecycle.

As far as I have been concerned, waterfall and agile are not methodologies, they are vaguely defined approaches/models. The definition of a methodology being a set of tools and techniques used to exactly define the steps taken to develop a successful software project.

In my understanding, the following statements are true: -

SSADM (Structured System Analysis and Design) is a waterfall
methodology

Scrum is an agile methodology

XP is an agile methodology

Thus, it would not make sense to write: -

Waterfall is a waterfall methodology

Agile is an agile methodology

Since you would get into a recursive mess.

The issue is, whenever I get into this debate with anyone, they seem to be certain that waterfall is a methodology and so is agile.

An example of what I see as being incorrect is the following article: -

http://en.wikipedia.org/wiki/Software_development_methodology

Methodologies
  Waterfall Prototype model Incremental Iterative V-Model Spiral Scrum Cleanroom RAD DSDM RUP XP Agile Lean Dual Vee Model TDD FDD DDD

These are listed as methodologies on the wikipedia page and I find that this is just plain wrong. Can someone please correct me and/or let me know what terminology I should be using?

答:
If you call "Waterfall" a methodology, or if you only call something like SSADM a methodology, depends mainly on the level of detail and the context of your discussion. Same holds for "Agile" (though I guess the latter term is not very often considered to be a methodology on its own).

So my advice is: whenever you want to talk about those things, just clarify the context before you run into a fruitless debate.

Natural language is not always precise.


答:
The tactics for unit testing vary depending on the "test unit" being tested in that test.

If the test unit is an implementation of a function that performs a calculation based on a combination of inputs and its current state, then a good unit test would be to put that object into the defined state, and then call the function and verify its output is the golden data

If the test unit is responsible for deciding which object from a list it should return, then a good unit test would be to force populate that list with its (mock?) objects, and then verify that the expected object instance was returned.

Some units being tested do not match the "golden value" style of testing.

Consider, a function which is responsible for sequencing a series of calls to other objects.  In this case, you are likely to create a mock/fake objects to receive these calls, and then instead of comparing golden values, you are checking that these objects were called with appropriate parameters.

Some unit tests are written to verify the absence of behaviour

Consider how you would validate that a function that needed to make a function call if certain conditions were met.  Its as important to validate that this call does not occur if the conditions are not met, as it is to verify its called when they do meet.

Finally, sometimes verifying that a function does not generate exceptions across a wide range of inputs can be important.

Title: Unit tests tactics

Body:
The only unit tests tactic I'm familiar with is comparing against golden data _ a predefined set of input data for which output is known (preferably including corner cases).

I cannot think of any other reasonable way of unit testing. Trying to unit test using arbitrary input data is (at least) as difficult as writing the application itself.

Are there any effective tactics for unit testing other than golden data testing?

Note: By saying arbitrary data I mean any syntactically valid input which a method can accept (including logically invalid inputs).


问:
The best possible way to implement Business Rules in PHP
I'm planning to write an e-commerce app using PHP & MySQL with lots & lots of custom rules. Say for example, I want to have a rule like "Give Customer X, a 10% a discount  for Product Y if he bundles it with Product Z"

I've heard about Business rules engine(in Java and others). I intend to implement a flexible business rules functionality without hard-coding anything into PHP and with a good, solid architecture with the goal of maintainability and re-usability with the help of PHP OOPS.

Please advice me on the following aspects:

Does decision table fit my intended purpose?

How can I change rule/business logic of the PHP application without redeploying/re-writing?

答:
For my own purposes I considered https://github.com/bobthecow/Ruler - a production rules engine. It is applicable to your needs: Give Customer X, a 10% a discount for Product Y if he bundles it with Product Z.

I'll try to write some sort of a pseudo-code:

Context: your shopping cart items
Rules: cart contains ProductY and ProductZ
Execute: ProductY->discount(10%)
```


答:
Wouldn't the ultimate target of DRY include elimination of all test
  code?

No, the ultimate target of DRY would actually mean elimination of all production code.

If our tests could be perfect specifications of what we want the system to do, we'd just have to generate the corresponding production code (or binaries) automatically, effectively removing the production code base per se.

This is actually what approaches like model-driven architecture claim to achieve - a single human-designed source of truth from which everything is derived by computation.

I don't think the reverse (getting rid of all tests) is desirable because :

You have to solve the impedance mismatch between implementation and specification. Production code can convey intent to a degree, but it will never be as easy to reason about as well-expressed tests. We human beings need that higher view of why we're building things. Even if you don't do tests because of DRY, specifications will probably have to be written down in documents anyway, which is a definitely more dangerous beast in terms of impedance mismatch and code desynchronization if you ask me.

While production code is arguably easily derivable from correct executable specifications (assuming enough time), a test suite is much harder to reconstitute from a program's final code. Specifications don't appear clearly just looking at the code, because interactions between code units at runtime are difficult to make out. This is why we have such a hard time dealing with testless legacy applications. In other words : if you want your application to survive for more than a few months, you'd probaly be better off losing the hard drive that hosts your production codebase than the one where your test suite is.

It's much easier to introduce a bug by accident in production code than in test code. And since production code is not self-verifying (though this can be approached with Design by Contract or richer type systems), we still need some external program to test it and warn us if a regression occurs.

Title: Testing vs Don't Repeat Yourself (DRY)


答:
You need to "encrypt" (actually, "hash", for a proper notion of hashing) the passwords as a second layer of defence: this is meant to prevent an attacker, who got a read-only glimpse of the database, from escalating that into read-write access and, precisely, begin to alter the data. Read-only partial breaches happen in the real world, e.g. through some SQL injection attack from an account with read-only access, or by retrieving a discarded hard disk or old backup tape from a dumpster. I have written at length on this subject there.

As for the proper ways to hash passwords, see this answer. This involves salts, iterations, and, most of all, not inventing your own algorithms (homemade cryptography is a sure recipe for disaster).


问:
Potentially Shippable Product Increment - what if users don't like the latest increment?
In our company we do usability test at the end of each Sprint. Many times we discover that the users don't like the implemented feature, so we either completely change it or scrap it in the next Sprint.

However if we start doing potentially shippable product, thus fixing all bugs, running a lot of tests, preparing documentation for FDA and for users, fixing little UI issues - all this work will go to waste if users will not like the feature. Isn't it better NOT to do all this extra potentially shippable stuff until we are sure users actually like the feature?

答:
Scrum states that the aim of a Sprint is to produce a potentially releasable product increment. In the situation you describe, where users don't like what the team have produced, try to understand why. Inspect the reasoning and adapt accordingly.

The great news with Scrum is that you're finding these problems now, at the end of a Sprint and not at the end of an 18 month development project.

You may find that there's value in having the Product Owner engage more with the stakeholders to better understand their wishes and motivations. This, in turn, helps to order items on the Product Backlog appropriately and you may find that you're better able to delight your stakeholders at the next Sprint Review.


问:
How to organise the different bits and pieces in an agile environment?
Trying to make our shop an agile environment, we struggle with some bits and pieces of that world. While not making it waterfally, we do have to have some sort of agreement on what a new feature needs to do. We follow the KISS and "minimally viable product" principle. Still, after discussing a story, we end up with:

UI/UX design

Acceptance criteria

Constraints

Use cases

Some extra specifications (like what fields to show in tables etc)

As tools we use JIRA, Greenhopper, Balsamiq, Glyphy and Confluence and they are working very well but we're not quite sure where to store which bits and how to make this work together well.

How do you guys approach that. Please include details on how far you go detailing the feature before development starts.

答:
This may sound like heresy on a programmers site but I'd advise that you ditch the tools and go manual.

Have a good read of the Scrum Guide (available for free at https://www.scrum.org/Scrum-Guide ) It's only 17 pages long and really easy to understand.

Then try using manual items like index cards for writing user stories, large flat spaces for scrum boards, post-it notes for tasks etc.

If you want a quick start, here's an article on creating a product backlog. (Disclosure: This links to an article on my website)

Doing this manually prevents tools from perverting what you're trying to do. Later, with experience, if you still want to use a tool, you can bend it to your will, rather than the other way round.


答:
It sounds like you need to engage more with your customer.

Maybe you tried to already and they will not engage because they are busy with what they see as their "real job". If so, at a higher management level, IT need to get buy in from customers to be more involved with the project.

Early prototyping phases might help.

Somehow making them aware of the cost might help, although binning say 2 weeks or work should be indication enough. Moving shipping dates or cutting features from future releases might focus their minds.

Title: Potentially Shippable Product Increment - what if users don't like the latest increment?

Body:
In our company we do usability test at the end of each Sprint. Many times we discover that the users don't like the implemented feature, so we either completely change it or scrap it in the next Sprint.

However if we start doing potentially shippable product, thus fixing all bugs, running a lot of tests, preparing documentation for FDA and for users, fixing little UI issues - all this work will go to waste if users will not like the feature. Isn't it better NOT to do all this extra potentially shippable stuff until we are sure users actually like the feature?


答:
That is the Product Owner's responsibility -- to come up with a product that meets the needs of the users.

So you may wonder how your Product Owner wrote the user stories -- did he not check them with end users? Did he not create screen mockups for them to evaluate? Did he not gather their needs?

If users don't like what you did, the Product Owner must find out what must change and how, and then you can make those changes. If necessary (but unlikely I'd say), you can revert to the previous release and build from there.


问:
Allowing enum to express a valid combination of values
Suppose in a manufacturing environment, there are certain stock materials available for use in a product. For example, there are only a few different sizes of copper tube, each having a specific thickness and diameter combination. For the purposes of clean and minimal code as well as the ability to control the available options, is an enum a good fit for this combination of data? I was thinking I could make an enum with a member for each valid stock item (representing metal, physical measurements, etc.), and then provide extension methods on the enum to return the mentioned details.

The stocks available for use may change over time, so maybe an enum is not the best answer. Is there a better way to express the valid combination of related values? I am using c#.

答:
I would probably just make a class TubeParameterCombination  with read-only properties Thickness and Diameter, and provide an array or list like

```<code>List<TubeParameterCombination> validCombinations;
</code>```

somewhere in the code. If you want to be absolutely sure no one changes that list afterwards once it got initialized, encapsulate it behind some kind of ValidCombinationProviderclass which allows only read-only access.  What you have to decide is where and when you initialize that list.

You can either hardcode the initialization in your program (which means you have to change your program whenever the valid combinations change), read the combinations from a text file (which could be changed by a user ot an administrator), maybe just once when your program starts. Or you read the valid combinations from a database (which makes sense when your program is already using a database for such kind of data, and you want to provide a possibility for controlled changes to that list). Pick whatever suits your needs best.

Body:
I would probably just make a class TubeParameterCombination  with read-only properties Thickness and Diameter, and provide an array or list like

List<TubeParameterCombination> validCombinations;

somewhere in the code. If you want to be absolutely sure no one changes that list afterwards once it got initialized, encapsulate it behind some kind of ValidCombinationProviderclass which allows only read-only access.  What you have to decide is where and when you initialize that list.

You can either hardcode the initialization in your program (which means you have to change your program whenever the valid combinations change), read the combinations from a text file (which could be changed by a user ot an administrator), maybe just once when your program starts. Or you read the valid combinations from a database (which makes sense when your program is already using a database for such kind of data, and you want to provide a possibility for controlled changes to that list). Pick whatever suits your needs best.


答: Enum in C# is meant as list of static enough items to discriminate something. If there is even chance of this list of items changing, especially in production, then using it is not appropriate. If you want specific behavior, you have to code it yourself. It shouldn't be hard to code a class or hierarchy of classes that express what you need.

Title: Allowing enum to express a valid combination of values

Body:
Suppose in a manufacturing environment, there are certain stock materials available for use in a product. For example, there are only a few different sizes of copper tube, each having a specific thickness and diameter combination. For the purposes of clean and minimal code as well as the ability to control the available options, is an enum a good fit for this combination of data? I was thinking I could make an enum with a member for each valid stock item (representing metal, physical measurements, etc.), and then provide extension methods on the enum to return the mentioned details.

The stocks available for use may change over time, so maybe an enum is not the best answer. Is there a better way to express the valid combination of related values? I am using c#.


问:
Why should passwords be encrypted if they are being stored in a secure database?
I have a web service. Right now, I have passwords stored in plain text in a MySQL table on my server. I know this isn't the best practice, and that is why I am working on it.

Why should passwords be encrypted if they are being stored in a secure database? I realize that if someone hacks in to my database they will get everyone's password. But I have other problems if someone gets in my database, for example, deleting data.

The scenario I can think of is that you are hacked. You restore a database from a couple of hours ago and everything is well. However, if your passwords are plaintext... The thief has all the passwords and you have to reset them all. Hassle to your users.

If the passwords were encrypted, you could just restore to previous database. Is this correct thinking?

答:
I have to post an answer here on a fallacy in the question itself. You are asking if passwords should be encrypted. No one encrypts passwords; no one, with the exception of services and programs like Firefox Sync and Roboform, whose sole purpose is to encrypt passwords.

Let's take a look at the definitions:

In cryptography, encryption is the process of encoding messages (or information) in such a way that only authorized parties can read it.

And hashing:

A hash function is any algorithm that maps data of arbitrary length to data of a fixed length.

In other words, encryption is a two-way conversion and hashing is a one-way conversion, so unless you are decrypting to view them later, this is not encryption.

Also, don't just hash, salt! Read this entire page before you hash your passwords.

As for hashing algorithms, which the OP is now looking into, I would suggest any of the high-end SHA-2 varients, such as SHA-384 or SHA-512.

Optionally, you can use multiple rounds of hashing.

Consider reading this page to secure your login process more.

Second, your database can never be secure enough. There will always be security holes and ever-evolving risks. You should follow Murphy's Law and always prepare for the worst eventuality.

The other points pdr makes are exactly what else I would say: people who use the same password for every website, hackers using social engineering to gain more information, etc. etc.


问:
I know the language but still can't code like other peers
I have moved to a new job and code base (been doing C#, .NET, Windows Forms, etc. for last four years) and I have been on this for three months until today. During these three months I caught up with parts of the language and syntax that I didn't know before (MVVM, Silverlight, some advanced stuff in .NET like Action, Func, Callbacks, etc.), so now I know those but still when I go in the code to fix a bug and see their code, I get disappointed, because I see some coding techniques that although I know the syntax and understand it but I think to myself "could I write this myself"?

The answer is no. For example they create classes that have a member as "Action" and at run-time they assign actions to separate instances, or register - unregister events at some parts of the code, etc.

Is it normal? and gets better by time? or I am just a stupid mediocre developer? and how can I make it better?

答:
Practice, practice, practice.

Also, don't assume you know the language. The fact that you're surprised to see someone register and unregister events shows that you have still things to learn about the language. The fact that you're surprised to see Actions in action indicates that you also have things to learn in .NET Framework.

Is it normal?

Totally. You become expert in a field after ten years of practice, and even after that, you have still things to learn.

Or am I just a stupid mediocre developer?

The fact that more experienced colleagues are doing things you don't know how to do doesn't mean that you're mediocre. They know the stuff better, because they are more experienced. You'll gain the same experience with time.

Having more experienced colleagues is also an excellent thing: you can learn from them a lot. Take this as an opportunity.

How do I practice?

By doing four things:

Reading code of others, and inspecting the parts you don't understand; if you're stuck, ask your colleagues—the ones who originally wrote the code.

Writing code: you can't learn something if you don't practice that.

Reading your own code you wrote months ago, looking for things you may have written differently. If the problem is sufficiently complex (and you still remember it), you could even rewrite that code using what you've learned since then. Doing that allows you to learn how to write code using the improved techniques you've learned, without getting bogged down in learning about the problem domain.

Asking more experienced colleagues to review your code, and to make constructive criticism.