September 2008 Entries

Model View Presenter / Passive View Benefits

A hot topic near and dear to my heart is Model View Presenter (MVP) or Passive View design pattern.   This design pattern forms a good model for keeping a strong separation between UI logic and business logic.

In the MVP model, the data access objects constitute the model, the View is the UI components kept as simple as they can be and the Presenter is where the business logic is.   These three components interact with other through interfaces to further reinforce the logical separation.  

The presenter should have no idea where the Model gets its data or how the data is persisted.    The Model defines an interface that must be implemented.   Anything that implements this interface can serve as the model.  This means that we can switch out the data storage strategy without having to change anything in the presenter.

The presenter should also have no idea about the nature of the View.    The View implements an interface that exposes all of the methods, properties, and events that the Presenter will need and the Presenter implements the business logic through this interface.   This means that View may actually been a Win Form, Web Form, a server control, a user control, a SharePoint web part, or even a class library with no UI components.   The only requirement is that the View must implement the interface.

Among other things, this gives us these benefits:

·        Simplified testing.   The Presenter can be tested without having to worry about the database or the UI.   Both the Model and View can be replaced with “Mock” objects designed to simplify testing
·        Business logic implemented in the Presenter can easily be retargeted to any number of UIs.    Once the business logic is implemented and tested, the original View can be converted from a Win Form to Web Form or a Mobile Web Form, etc without impacting the Presenter as long as the new Views continue to implement the same interface
·        The Model can be switched out to for demo purposes to read from local flat files or static XML files.   As long as the new Models implement the original interfaces, neither the Presenter nor the Views needs to change.
·        If you have multiple lines of business with similar business logic but very different data sources, new Models can be implemented targeting the new data sources.   As long as the new models implement the original interfaces, neither the Presenter nor the View needs to change.  
Future posts will explore what some of these benefits mean as well as ferret out some additional benefits.

What benefits do you see with the MVP pattern?  What hurdles have you had to face?

 
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati


What can we do for meaningful variable names?

You hear much about naming conventions and some shops still have some arcane rules in place.   Fortunately most of us have stepped beyond Hungarian notation.   I have seen some shops define rules that the method name should include the number of parameters.   I have seen shops define rules that would ban overloading and insist on a sequence number for  methods that should be overloads.   I have seen shops that wanted the Requirement Number embedded in method names, and I have seen shops put maximum character size limits to simplify reading.   This unfortunately led to awkward abbreviations.

None of these standards have led to more meaning variable names.   The fact that a variable is an integer or a string does nothing for me.   Having a method signature come like:

        Public void int  DoSomething (string strParam, int intParam)

does nothing for us.    Having one like:

        Public void int  ProcessIncomingClaims (string branchCode, int transactionID)

Can be very enlightening.

Like legislating morality, none of these rules will guarantee that the names are good.   At the same time, almost any set of “good” rules could still be applied and end up with “bad” variable names.  We may not always know when a name is “good” but we usually know when the name is “bad”.  

Enter GhostDoc.   GhostDoc is a wonderful tool designed to help automate your comments.   Caution it works best for C#, but they are building support for VB.   The intention here is that GhostDoc takes your method, properties, parameters, etc. and splits them to come up with the documentation for that item.   There are several thinks that seem to be happening here.   First it splits the words at a case change.   Second, it interprets methods as being in the form verb – object and will attempt to structure the comment like that.

For instance, if you have a method called DataBind (), GhostDoc will come up with the comment:

/// <summary>

/// Datas the bind.

/// </summary>

 

This is clearly not what we want for a comment.   Note that the naming convention was not followed.   We would want to have methods following the pattern of Vern Object.   Here it is following the convention of Object Verb.   Ghost Doc ends up with a comment that does not make sense grammatically.   Now consider the comment generated for the method   BindData ():

/// <summary>

/// Binds the data.

/// </summary>

Our method name follows the naming conventions that we have setup and now the generated comment makes sense as well.

Try it and you will find that whenever GhostDoc does not come up with a boiler plate comment, your variable names or method names or property names are probably not named well.

Not a bad litmus test for good names!

Just like Ghost Writers in the publishing world, there is only so much that GhostDoc can do.  It does a good job of structuring your comments.  It does a good job of mapping out the details needed for comprehensive XML documentation.   It also does a good job brining in ancestor details when overriding from a base class.  

It does not explain how logic works or why logic is needed.   This you still need to add yourself, but at least you will know where it goes to produce in comprehensive documentation.     The better you name your methods and parameters, the less you should have to write.    The more highly cohesive your methods, the less you should have to write.    The less you have have to write manually, the better your code can be understand without your comments.

Has anyone else used GhostDoc to help ensure naming conventions or help ensure that code is readable?

?


You hear much about naming conventions and some shops still have some arcane rules in place.   Fortunately most of us have stepped beyond Hungarian notation.   I have seen some shops define rules that the method name should include the number of parameters.   I have seen shops define rules that would ban overloading and insist on a sequence number for  methods that should be overloads.   I have seen shops that wanted the Requirement Number embedded in method names, and I have seen shops put maximum character size limits to simplify reading.   This unfortunately led to awkward abbreviations.

None of these standards have led to more meaning variable names.   The fact that a variable is an integer or a string does nothing for me.   Having a method signature come like:

        Public void int  DoSomething (string strParam, int intParam)

does nothing for us.    Having one like:

        Public void int  ProcessIncomingClaims (string branchCode, int transactionID)

Can be very enlightening.

Like legislating morality, none of these rules will guarantee that the names are good.   At the same time, almost any set of “good” rules could still be applied and end up with “bad” variable names.  We may not always know when a name is “good” but we usually know when the name is “bad”.  

Enter GhostDoc.   GhostDoc is a wonderful tool designed to help automate your comments.   Caution it works best for C#, but they are building support for VB.   The intention here is that GhostDoc takes your method, properties, parameters, etc. and splits them to come up with the documentation for that item.   There are several thinks that seem to be happening here.   First it splits the words at a case change.   Second, it interprets methods as being in the form verb – object and will attempt to structure the comment like that.

For instance, if you have a method called DataBind (), GhostDoc will come up with the comment:

/// <summary>

/// Datas the bind.

/// </summary>

 

This is clearly not what we want for a comment.   Note that the naming convention was not followed.   We would want to have methods following the pattern of Vern Object.   Here it is following the convention of Object Verb.   Ghost Doc ends up with a comment that does not make sense grammatically.   Now consider the comment generated for the method   BindData ():

/// <summary>

/// Binds the data.

/// </summary>

Our method name follows the naming conventions that we have setup and now the generated comment makes sense as well.

Try it and you will find that whenever GhostDoc does not come up with a boiler plate comment, your variable names or method names or property names are probably not named well.

Not a bad litmus test for good names!

Just like Ghost Writers in the publishing world, there is only so much that GhostDoc can do.  It does a good job of structuring your comments.  It does a good job of mapping out the details needed for comprehensive XML documentation.   It also does a good job brining in ancestor details when overriding from a base class.  

It does not explain how logic works or why logic is needed.   This you still need to add yourself, but at least you will know where it goes to produce in comprehensive documentation.     The better you name your methods and parameters, the less you should have to write.    The more highly cohesive your methods, the less you should have to write.    The less you have have to write manually, the better your code can be understand without your comments.

Has anyone else used GhostDoc to help ensure naming conventions or help ensure that code is readable?

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

SQL Tips for Learning a new Database

 

The hardest part of writing SQL statements is in understanding the database that you are working with. The raw mechanics of SQL for the most part are fairly straight forward. Often times really complex SQL statements point to business logic showing up where it doesn’t belong.

The hard part about learning a database is the lack of consistency and documentation. Data diagrams are often of little help. Diagrams are good for an overview and to get a list of tables, etc, but when the database has hundreds of tables with some tables having dozens of columns; the diagram can be a little overwhelming. Sometimes, a data diagram may not be helpful because all of the relationships are not actually defined. Poor design or data integrity problems often mean that foreign keys are implied but not enforced by the database. A data diagram will offer little help in finding such relationships, but you may still be able to ferret out such relationships through the system tables.

Every database includes a data dictionary that the database server uses to keep everything straight. We can use this data dictionary to our own benefit.

Instead of simply viewing an alphabetical list of tables, we can view all of the tables that include a given column or a given combination of columns or include these two columns but not a third column. We can easily get a list of all of the tables that include any columns that are of a particular data type or have more than a given number of columns or less than a given number of columns. There is a lot of potential here.

For SQL Server, the main tables that you will be interested in are in the information_shcmea views. These views exist in every database, but they are only visible in the master database. To make most of this magic work, we will really be interested in just a couple of views. Tables and Columns.

Information_Schema.Tables will give us some details about all of the tables in a given database.

Information_Schema.Columns will give us some details about of the columns in a given table.

With these two views, we can write queries such as:

Select * from information_Schema.tables where table_name like ‘%blah%’

Select * from information_Schema.columns where column_name = ‘Member_ID’

Get a list of tables that include a Member_ID column, a FirstName column and any DateTime column and at least 20 columns total.

Select * from information_schema.tables where table_name in (

Select table_name from information_schema.columns where column_name = ‘Member_ID’)

And table_name in (

Select table_name from information_schema.columns where column_name = ‘FirstName’)

And table_name in (

Select table_name from information_schema.columns where datatype = ‘DateTime’)

And table_name in (

select table_name from (select table_name, count (1)

From information_schema.columns

Group by table_name

Having count(1) > 20)

)

As you can see the possibilities are limited only by your imagination.

Oracle provides the same functionality. Actually every relational database must. For Oracle, the view in question would be all_tables and all_tab_columns.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Reflecting on Software Metrics

 

At the risk of sounding pedantic, I like software metrics. They can prove to be invaluable in analyzing source code. To be clear, I am not proposing that developers be bonused based on metrics and their use in estimating and scheduling should be limited at best. I am however a fan of software metrics as benchmarks for evaluating design and understanding how software works.

There is an add-in for reflector called CodeMetrics that allows you to easily calculate a wide range of code metrics from within Reflector. We are most interested in one metric, Cyclomatic Complexity.

Cyclomatic Complexity or CC is the number of logical paths through a piece of code. This can be used to define a lower bound for the number of test cases needed to ensure proper coverage in unit testing. This can also be used to predict ongoing maintenance costs and be scaled to predict the likelihood of actually resolving a particular defect or introducing additional defects.

Tables similar to this are common:

CC

Testing Requirements

Ongoing Maintenance Costs

Resolution Likelihood

1-0

A simple procedure

Low

High

11-50

Complex

Moderate to High

Medium to low

>50

Very Difficult

High Risk

Low

The actual bands may vary depending on the line of business and skills of the developers involved, but these are generally good benchmarks.

A CC of 10 would indicate that 10 test cases are needed to fully test all of the functionality. Depending on what you are working on, that may be more complex than you want to consider or that may still be fairly trivial. As a general rule, I try to keep methods below 10.

When I am working on existing functionality, I try to review the code and refactor the code in the same module with the highest complexity, systematically reducing the overall complexity. Sometimes the best you can do is to review the more complex functions and add comments on how they may be refactored. Often times, the actual refactoring may be out of scope for the change that got you involved in the first place.

It is important to review the complexity of any code before making code changes. If you are about to change code that already has a high complexity, you want to make sure that your changes do not add more complexity. You need to be aware that with higher complexities comes a higher chance of introducing new defects and you are also less likely to resolve the underlying defect if it is embedded in complex code. This may change your estimates and should change your testing strategy.

Sometimes, complex code masks cohesion problems. If the code is very complex, there is a good chance that the particular method is trying to do more than one thing. If it is doing more than one thing, than simplifying the code may be nothing more than separating all of the different tasks that the method is trying to do. For example, code is often complex because data validation logic is blended with business logic or data mapping logic is blended with business logic. Simply pulling all of the data validation logic to a separate method and all of the data mapping logic to a separate method and isolating all of the business logic to a single method, you end up with several methods each of which is less complex than the original. Each of these methods will be much more cohesive. With cohesive methods, it is easier to know where to add new functionality or where to go when reviewing existing functionality.

Future blogs will explore some ways to reduce complexity.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Passive View and Cyclomatic Complexity

We have previously talked about cyclomatic complexity and set forth the goal of keeping the complexity for our methods down below 10.   We have also talked about the goal of systematically refactoring any methods that we find to lower complexities whenever we make code changes.  These are good and admirable goals for business logic.

But what about Passive View?   Passive View is a slight variation on the Model View Presenter pattern designed to drive home the fact that the view should do very little processing.   The view should be passive.  Quiet literally the only code found in the view should be the implementation of the properties and the event handlers for the UI components.  The properties should do the absolute minimal to interact with the user, and the event handlers should simply forward calls on to the presenter.

I cannot stress this enough, there should be no actual logic in the view.

The driving force behind the Passive View pattern is to simplify testing.   Since it is harder to test the UI and the UI does not lend itself to automated testing, we want to move as much logic as possible to locations that are easier to test, class libraries.   Testing aside, logic housed in class libraries is more reusable and can be shared across multiple UIs.   In fact, the automated tests simply become a new UI.

All that being said, any method in the UI should have a cyclomatic complexity of 1!

Yep!   You heard me correctly.  One!   If you find yourself writing a method, event handler or property in the UI with a complexity greater than one, stop and ask yourself why whatever logic you are implemented is in the UI.   Chances are you will find that there is functionality that should be moved to the Presenter or a shared UI component.

I challenge everyone to identify UI code with a complexity greater than 1 that cannot be moved out of the View.   Note that I said out of the View and not out of the UI layer.   There are times when true UI processing may require some logical processing, but these are not so specialized that they cannot be removed from the View.

 

 
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Using Pronouns

This may not be very technical, but hopefully it may generate some discussion and provide some insight.

Pronouns can be very enlightening about our attitudes towards work.   How long do you work for a company before you start thinking of the company as “we” instead of “they?”   Consider:   We are the number 1 producer of product X.   Vs.   They are the number 1 producer of X.   Do you ever make that pronoun switch?   What does it mean if you switch back from “we” to “they?”    What does it mean if you never make the switch?   Are you even aware of which one you use?

The dynamics with interpersonal relationships are also interesting.   Have you ever noticed that a single co –worker will probably say “I” or “my”, or “me” a lot.    A co- worker married or at least in a committed relationship will be much more likely to say “we” even if their partner is not with them.   What should we make of this?  : )

Of course you also get this with team dynamics as well.  A strong team player will frequently refer to “we.”    In this case, “we” probably refers to the team.   We are falling behind and need to catch up.   In a strong team, “I” rarely makes an appearance.    Hopefully, “you” is scarce as well.

I have also noticed something interesting with my wife that I thing is somewhat common.   The switch from “our” or even “mine” to “your” when we get upset about something.   I notice “our” dog becoming “your” dog when the dog does something bad.    Is this common?   Does it show up in other areas of life?    Do “our” processes become “your” processes when we feel like the processes don’t work?   Would such switches be a Freudian slip, malicious behavior, or a harmless word game?   Are we even of it when we make such switches?

So your use of pronouns can be used gauge the ties you feel towards your employer, your team, and your partner.    Here are some of my thoughts:

·        When your employer becomes “we” as in “We have a good work environment” instead of “They have a good work environment”, you finally feel like you are part of the corporate culture.
·        Should you go back to thinking of your employer as “they”, you may be feeling a little disenfranchised or disconnected.   Consider, “They have a strong business model” instead of “We have a strong business model”
·        If you never think of the company as “we,” are you perpetually disconnected looking in on your co-workers from the outside?
·        When you meet someone and they keep referring to “We went to the movies over the weekend”, chances are that person is married.    If your new friend states that “I went to the movies over the weekend,” you may have a new single friend.
·        When your team mates start referring to “we” as in “We have a good sense of the project timelines”, you probably have a strong team.   As long as you are still thinking in terms of “I think I know what needs to be done”, your team probably hasn’t truly formed yet.  Or maybe it is still “storming”
These are not hard and fast rules.   These are probably not even generally guidelines.   These are simple observations that I have made that seem to be true often.

Without a doubt there are many exceptions.   Most of us choose our pronouns without even thinking about it.   If we start thinking about it too much, we will probably throw the whole system out of balance, but a little self reflection is a good thing.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati