Breaking people

An interesting discussion including  Yannick Grenzinger, Romeu Moura and Daniel Gonçalves has recently happened on Twitter. Thanks mates for the respectful and enlightening exchange.

It started from this:

The first objection was from Yannick Grenzinger:

Which, as  Daniel Gonçalves noticed, resonates a lot with an older tweet from Nicole Rauch:

I think the matter deserves a blog post to explain my position. Not because it’s the right position, but rather because we all have different experiences, with interesting things to share. I kind of agree with Nicole, and still I think we can survive it, if we stop trying to fix the system.

What’s breaking people?

The first step is to agree on what it means to “break people”. I was once, when I started my career.
We feel broken when we lost interest in what we are doing. When we stop trying to improve, because it seems excessively hard. We know that something better could be done. But we feel that whatever we can do will not have any meaningful impact. First, we lost our motivation, then our discipline, and finally our values.
Because what we can do doesn’t matter, it doesn’t matter either way if we don’t write a unit test for this code, or if we don’t take the time to refactor it. It doesn’t matter if the build is broken or if there isn’t any automatic build. It doesn’t matter if we ship bad software for unhappy users. That’s because of the corporation, not because of us. They want us to ship too fast. They want us to write crappy code. They recruit only juniors. They don’t care about code quality and good software. They don’t want to hear about pair programming. They just consider the IT as a cost centre. If they don’t want to change and see the world like us, there’s nothing we can do.

The global local impact

I’m a firm believer that you don’t change the world by imposing your view. You change the world by acting locally and leading by example. That’s exactly how I understand Gandhi’s mantra “You must be the change you want to see in the world”.
When I do consulting for a company, no matter how big it is, I start by acting locally. Of course, it would be easier to act globally. It would be easier if the whole company, at all levels, will follow the agile principles at once. But it never happens to me. And who am I to know the correct way of working for the whole company? I don’t know. What I know is how to write software efficiently. What I know is that it doesn’t belong to any managers to choose if we must write unit tests, or if we should use a build server and do code reviews.
Whatever the context is, I can keep my discipline and my values, which are mandatories to stay motivated.

But the system will break you!

Fair enough, that could happen, but at one condition. Only if I fail to recognize the moment when the “system” is creeping into my local safe area. I did this mistake once, and it won’t happen again.
Since then, when I do recognize this moment, I do whatever is possible to protect the safe area. The last possible solution is to abandon it and let it collapse.
Is it a big deal? Absolutely not. Our team could fail, our product could be shitty in the end, our company could re-create a command and control culture, but I (and the people convinced by my example) will be safe. Because we will leave and find another place where the culture is less corrupted, where it will be possible to manage a full project, at least locally, with our discipline and values.

So you’re just a coward?

I always clearly explain how I work during interviews. My behaviour will never be a surprise, as I clearly state that some practices are not optional for me to work.
Anybody who has already quit a gig or a job know how hard it is. Like every other passionate people, I have strong feelings about my job. And it takes lots of courage to admit that we’re no longer in the capacity to protect our local safe zone. It’s a failure. It is the proof that we couldn’t change enough people around us. But it doesn’t mean that we must abandon our discipline and values. It just means that we must abandon this toxic context, to find a better one.

How do you change anything if you left when it’s hard?

As it happens, lots of companies are looking hard for competent developers, with strong skills, discipline and values. It explains why, in 10 years of professional software development, I only need once to quit such a toxic environment. Since, I’ve always found some places where my discipline and values are much welcome.
I didn’t change any system so far, but I’ve done more important things. I’ve influenced the way of working of several people, in such a way that broken systems were no longer able to break them.

Changing things is not as important as changing people. From the latter, the first will happen.

 

 

 

Diverse IT

Here is another privileged white guy who stand up to talk about diversity. Let me explain why.

Google memo, Uncle Bob and the SoftwareCraftsmanship community

If you didn’t follow this thread, you can have few information here. The thing to understand is that it’s a big matter. There are lots of anger, misconception and bad explanations, between smart people. I would like to testify as the average privileged developer why I ignored this matter for so long, and what I decided to do to care about that. Because as Martin Fowler says, “you can’t choose if you hurt someone, but you can choose if you care”.

A long ignorance

I am a passionate developer, and I do respect competent people. I really don’t care if they are higher in hierarchy, if they are men, women, black, white, gay, if they believe in any god(s), if they have lots of experience or if they are juniors, if they drink alcohol, if they eat meat, if they wear suits or t-shirts… I just do care about how competent and passionate (the two are generally connected) they are.
And because of that, I believed that I had the good behaviour. I deal with everybody in the same way, that’s fair isn’t it?

A spark of light

But then I meet different people and attend to different conferences, especially in the Software Craftsmanship community, where I learn so much about this topic. And thanks to them I realized two important mistakes I’ve done: assuming that equality is enough, and assuming that I’m not legitimate to talk about it.

 

 The equality inequality

Treating everyone equally is great. But it’s unfair at the same time. If you were a woman in the twentieth century and won a Nobel’s prize, are you equal or better than other Nobel’s scientifics? From a pure cognitive perspective, you are probably equally smart. But to achieve the same scientifics result in this male world, you probably must fight much more. You must fight for your rights, to be recognized by your pair, much more than an average white man.
The same thing happens in IT today. We must acknowledge for example that to be equally recognized in our field, women need to work harder than men.

 

The legitimacy paradox

Because I didn’t feel legitimate on this topic, I didn’t talk about it. But because I never spoke about that, people like me might think they should not care about it either. Worse, it’s always the same legitimate people who talk about it. But what if they would like to talk about TDD or CQRS/ES instead?

What to do?

First, we have to be careful in our talks, especially in public presentation. Be careful about genders, when we use guys, he, craftsman and so on for instance… Of course, it is the same thing when we write blog posts and when we use twitter.

Every day at work, we can watch our jokes and behaviour. Watch other jokes and behaviours as well, learn to identify when someone is hurt, and let her (or him) know that you care and you will do your best to avoid that it happens again. And when we hurt someone (because everyone can make mistakes), we should just apologize. No need to look for excuses, just apologize. Uncle Bob unfortunately gives us a good example of what not to do recently.

As I already said, it’s important to speak about this, at work, in conferences and everywhere, especially if we are part of the privileged guyz.

It’s far from enough to fix the problem, but it’s a start, and at least, it shows that we care.

 

 

Thanks to the awesome Franzi who specialy helped me to grow up on this topic.

 

What the fuck ORM means?

Today is another day where a data model lealking into my business model ruins my productivity. So let’s talk again about impedance mismatch please.

Relational data model

We are all used to relational database. Back in school we learned how to design 1-n or n-n relationships and how to manage primary and foreign keys to manage consistency. We also learned how to normalize and denormalize the model, and to use views for performances.
What we did not learned in school is that it is only one way to store data, and that an automatic translation from this data storage model into memory is not a great idea.

What the fuck ORM means?

According to wikipedia: an Object Relational Mapper is a programming technique for converting data between incompatible type systems in object-oriented programming (OOP) languages.
The problem lies in the definition: we have incompatible type systems. But we somehow believe that the storage data model and the in memory object oriented model are the same thing.

The mismatch

Relational and object oriented are two different representation of the same model. One uses keys and relations to achieve data integrity, based on relational algebra and tuple relational calculus . The other defines bounded objects with defined responsibilities to simulate business processes in order to take decision, inspired by how cells work in biology.
Loading a relational model into memory as an object grape leads to well known problems. Lack of encapsulation (public get/set) is one of them. Anaemic model (data object without any behaviours) is another one. Both of them violate OOP principles.
There are also technical problems: when do you stop to load the grape? How do you manage circular references?

Complexity increase

In all the projects I met so far, the benefice of using an ORM was balanced by the incredible number of hacks we used to load and save what we need. Not speaking about the unmanageable complexity as soon as we try to cache something, because it is always a nightmare to know what is in memory or not.
Just to be clear: the core problem is not SQL or ORM by themselves (they are just tools), but the fact that most developers consider the data model to be their domain model.

How to escape it?

Keep in mind that a relational model is for storage, and that there is no simple way to automatically convert this model in your object oriented representation.
Using other data storage (document, graph, events…) mights help to remind that storing data and running business processes are two different problems with two different purposes.
And if a SQL storage is choose, I encourage to use simple library like Dapper to write actual SQL requests in the data layers. It will simplify the code, clarify the layers responsibilities and learn some SQL to the team, which is a great idea.

Trying to match automatically data model and domain model is a failure, because they are two different concepts.

 

Just Blog It

Since 1 year I try to write more blog posts. I’m performing at least 1 pomodoro per week to write drafts. I don’t feel pressure about publishing these drafts though, sometimes I do, sometimes I throw them away, and sometimes I merge them into a single post.

I think it might worth sharing what I learned.

Writing for yourself

The first rule of blogging is: don’t write for others, write for yourself. Some people might find what you write interesting, but writing with the goal to be interesting is not possible. It’s by writing consistently about your thoughts that some people might become regular readers. I stopped wondering if my posts were good or even interesting. I just published my current state of mind.

Writing for yourself is the art to express what you think about, in a clear way. It is a useful journey by itself, a personal experience. Having readers is a pleasant side effect for our ego, not the goal.

Writing in English

I don’t think it’s mandatory, still I don’t regret this choice.

Mainly because It improves my English skills.

But also, according to WordPress, I published 28 blog posts for 6500 unique reader. Half of them are not from France. I have some readers in the UK, Belgium, Spain, Germany, Poland and US for example.
It’s a wonderful gift to have feedback from all over the world, and only an English blog allows that. As you see my English is far from perfect, but it’s enough to share and learn with the whole world.

What I learned (in no specific order)

Just blog it

I enjoyed writing to my blog this year. I feel much more comfortable since I write for myself rather than for others. I’m not bilingual, and don’t need to, even to write in English.

I hope this post will help some of you to enjoy writing on their blog as well.

 

Thanks to all my kind reviewers over the year.
Special thanks to Brian Gibson for his time and patience to help me improve my English skills.

And of course, thanks to all my readers, all the best for this New Year!

 

About Inheritance and Composition

Like for dependency injection, heritage and composition are easily misundertsood.

We remember that programs written in Oriented Object Programming (OOP ) are designed by making them out of objects that interact with one another. Technically, we have two possibilities to share code in an OOP style: either composition or inheritance.

why-favor-composition-over-inheritance-in-java

Composition

The purpose of composition is to make wholes out of parts. These wholes (or components) will collaborate to achieve a common goal.
Composition has a natural translation in the real world. A car has 4 wheels. Without the wheels the car is still a car, but it loses its ability to move.
Back to code, a bank account might need a print service. Without the print service, the bank account is still a bank account, but it loses its ability to be printed. It is a “has a” relationship.

composition

Inheritance

Inheritance allows expressing and ordering concepts from generalized to specialized in a classification hierarchy.
The meaning of a class is visible in the inputs and outputs (public contract) of the class. As a child of a class, we are implicitly accepting responsibility for the public contract of the superclass. We are tightly coupled to this superclass: it is a “is a” relationship.
A human being is a mammal. No exceptions, all mammals have a neocortex. Without the neocortex, we are no longer mammals. Back to code, I may design a “human” child class, inheriting a “mammal” base class, both sharing a NeoCortex property.

 inheritance

Common mistake

The problem’s root is that sharing code can be done either by composition or by inheritance, but the impacts are not the same.
Any class can be composed by other classes because it requires their capabilities.
But with inheritance, the key is to decide if we accept responsibilities from the public contract of the superclass. If our parent has some capabilities/properties we don’t need, we deny a part of the responsibility. The “is a” relationship is broken as soon as there is something in the parent that isn’t true for the child. Adding responsibilities in the parent because “some children might need it” is not ok. All children need it, or we need another abstraction, or we need composition.
It is a problem because inheritance implies tight coupling. A refactoring of a capability can impact all the children of a base class. If one of the children does not use the refactored capability, it should not be impacted.

 images15e67y3x

Example

Lots of modern languages use the concept of ViewModel, even if it may be called otherwise. It is appealing to build a ViewModelBase with everything any children might need, like the ability to be printed, or to show a dialog box.
What happens when a child inherits this ViewModelBase but doesn’t need to be printed or to show dialogs? It accepts responsibilities that does not make sense for it. The signature and the meaning of the class are blurred. Without these printing or show dialog ability, the ViewModel is still a ViewModel.

On the other hand, implementing a RaisePropertyChanged function in ViewModelBase makes sense, because any ViewModel is by definition glue between the business logic and the view. It needs the ability to inform the view when a property is updated. Without this ability, it’s no longer a ViewModel. choosing-the-best-local-seo-company

How to choose?

The mantra “favor composition over inheritance”  is helpful, but as every mantra it is limited. It is true because sharing behaviours is always possible by composition, and will be more decoupled, but it is not always the wiser choice.

I think the “has a” vs “is a” relationship, and the reminder that every children must take the full responsibility of the parent in case of inheritance is enough to help choosing the best option.

 

 

 

IOC Containers, Dependency Injection and Service locator

Working mainly on .NET legacy project since a few years, I often meet the same kind of problems. One of them is a bad usage of Inversion Of Control (IOC) Containers, or Service Locator to magically access everything everywhere in the code. Just like a giant singleton.

I think these tools are not well understood. They are used as part of frameworks, or as a “good practice” without understanding the reason of their exsitence.

So let’s back to basics. images

What is Inversion Of Control? (IOC)

It is when Something control your code, instead of your code controling Something.

For example, when we need a library, we call it to delegate some work (like reading a mp3 file). Hence we control it.
When we use a framework, it calls us to manage some events (like user clicks on a button).  Hence there is an inversion of control.
inversion

What is Dependency Injection?

It is when dependencies are injected into a class, instead of this class managing its own dependencies.

For example, we often need to save something using a repository. The class has a dependency on a repository. We could directly instantiate the repository in our class. As a result, we won’t be able to write unit test on this class, because it will require a database connection, no matter what is the context.
Instead, we could inject the repository, to decide depending on our context if we want to inject a test repository or a runtime repository.
 injection

Why to inject dependencies into a class? 

In OOP, computer programs are designed by making them out of objects that interact with one another.
Dependency Injection allows to change the injected class implementation, hence the behavior, depending of the execution contexts (at least test or production). It creates relationships from high-level modules to low-level modules. It is an efficient way to apply the D from SOLID: Dependency Inversion Principle.

It allows to think about a given object in isolation (by isolating its behavior), and is really convenient for unit testing. Using our own class through tests is just dogfooding, and encourages us to write simpler classes with fewer responsibilities.

dogfooding-r-w1024-q75-m1414025204

How can we inject behaviour into a class?

There are three well known possibilities:

Setter injection
A setter with the required dependency in the (public) contract of the class.

public class MyClass
{
private MyRepository _myRepository;
public void SetMyRepository(MyRepository myRepository)
{
_myRepository = myRepository;
}
}

Constructor injection
The constructor is used to inject all the dependencies at once

public class MyClass
{
private readonly MyRepository _myRepository;
public MyClass(MyRepository myRepository)
{
_myRepository = myRepository;
}
}

Service locator
A class (the locator) is called to retrieve a service for us.

public class MyClass
{
private readonly MyRepository _myRepository;
public MyClass()
{
_myRepository = ServiceLocator.GetInstance<MyRepository>();
}
}

What is an IOC container?

Inversion Of Control Container is an unfortunate name for components managing Dependency Injection, in frameworks or libraries.

When we do dependency injection using a Service Locator, we explicitly call the service to get the dependency. IOC containers do dependency injection using constructor or setter injection, there is no explicit request. Here is the Inversion of control, supposed to justify the name.

It’s a bad name because we do not care about the concept of control here, the benefit is dependency injection. In other words, to understand IOC container, forget that they do IOC, just remember they do dependency injection.

dont-try-this-at-home

How not to use it

Here is a list of usage hurting maintenance and readability I saw in different projects.

– Usage of both Dependency Injection by constructor and service Locator.
Choosing one of the three Dependency Injection methods (constructor, setter or service locator) is up to your style of code, but mixing several of them makes it hard to think about the code. Be consistent around the project, the 3 methods achieve the same goal, there is no interest in mixing them.
The lack of consistency hurts the usability of the design.
As a direct painful example, the configuration for unit testing is harder, because some dependencies have to be mocked in the IOC container, some others in the service locator.

– Usage of a static singleton of service locator.
Singleton is probably the most used pattern, unfortunately it is not always wise. It is especially hard to write independent unit tests in this case, because all the dependencies are registered in the same instance of locator.

whisky_singletonsignature

Why to avoid Service Locator

The argument to use a service locator is usually that it reduces the pain for refactoring: the only dependency we have is the service locator, because the service locator can reach anything!
I believe it hides dependencies in order to write code faster. It literally means that each class could depend of anything. And the only way to know what the dependencies are is to look at the implementation.

 b_1_q_0_p_0cri4jaoj

Why to avoid Setter Injection

The main problem with setter injection is that the class is generally not in a valid state just after the creation. I hate when I can create a class, but it raises an exception when I try to call a function because I didn’t initialize the good values. I prefer to have explicit constructor, creating classes in a valid state, or not created it at all. I believe the role of the constructor is to ensure that the new object is in a valid state.

what-is-a-sql-injection-attack

Why Constructor Injection makes sense

I prefer to use IOC container only to instantiate the first classes for the system to start. From this point, I create manually other classes, and explicit all the dependencies in every constructor. Some would argue it is too verbose, but I see it as a guide.
When the constructor is too big, it’s a code smell encouraging me to think again about my design. Lots of dependencies implies lots of responsibilities.

And we know how to deal when a class has too much responsibility, don’t we?

 

To learn more on this topic, read the excellent work from Mark Seeman and Martin Fowler.

 

Thanks Thibaud Desodt and Thomas Pierrain for suggesting improvements.

 

A Craftsman work-life balance

I don’t feel comfortable when I hear people explaining how hard we should work to be “successful”. Mainly because “success” is subjective, it only makes sense in a given context.

For example, Uncle Bob in The Clean Coder asserts that a professional developer must work around 60 to 70 hours per week. 40 hours for his job, the rest of the time to improve his skills.

I deeply respect Uncle Bob, but when he says that I must dedicate 3 hours per day, week end included, from my personal time to improve my craft, I definitely not agree.
worklife-balance

Professionals have a personal life

We are valuables professionals with a really limited resource: time.

A company does not own 100% of our time because it fills a pay check. We don’t sell our lives, we sell our skills for a given period of time.

Investing on these skills is important. Learning new things is important. But it is unsustainable to do it only on our personal time. And when it’s done during our personal time, there are different things that can be done to keep an enjoyable life.

cat on beach

How to learn at work and stay efficient?

We can learn new things at work. Of course it does not mean we can play all day long with the last shiny technology when it produces no value for the company.

But we can do pair/mob programming. Whatever the job and the level of the co-worker we are pairing/mobing with, we will learn a lot of unexpected things.

We can explore new languages/tools on tiny internal topic. During a limited time (half a day? A few days?), we can pick an internal subject (improve the deployment script?) and try to solve it using an unknown tool/language we like.

It’s possible to organise 1 hour katas once a week. Or maybe to watch an interesting talk during lunch?

We can also switch a few people in the team on a regular basis. It will reduce the bus factor and spread good practices through the whole company
 b_1_q_0_p_0cb02vl5z-jpg

How to learn at home and keep friends and family?

When we think about it, we tend to realize there are lots of time we don’t use efficiently.

Work commuting is a good example. This travel time cannot be reduce. We can use it to read a book about the last subject we’d like to learn about. In car it’s possible to listen for audio-books or podcasts.

Waiting queue is another example. We wait a lot for: a plane, a train, a meeting, a doctor… It’s easy to keep a book, or better, a pdf on our phone to read instead of passively lose our time.

For sport addicts, what about listening some podcasts during the workout? It is true multi-tasking: the brain can listen to the podcast when the muscles are working on something different.

images

A crafstman work-life balance

I believe a good work-life balance is essential to be a software craftsman.

Personal life matters, it is the pillar to build a strong professional career. Not the other way around.

If people believe that they have to work 70 hours a week for their whole life to be professional, who will ever want to commit for a life career as a software engineer?

 

 

 

A path to escape the “No time for tests” death spiral.

We all know the “no time for tests” death spiral.

First we take exceptional shortcuts to ship something because “we have to ship it now but we’ll do better next time”. Of course next time we have even less time, we have to add features, we can’t really fix the shortcuts. It takes longer and longer to add features because of the shortcuts we took and cant’ remove. We start to invest a lot into fixing bugs.

That’s the beginning of a painful road for the team in charge, and we all know the end is bad. Some will try to work overtime to manage the mess. Some will burnout, tired of being so unproductive. In this hard time we’ll hear things like: “It has always been done this way, I know it’s wrong, but what can I do, I’m just a developer…”

No need to say I don’t agree, and here is the path I take as a developer every time I face this situation.

death-spiral

Step 1: Fix known bugs with unit tests

To introduce a quality culture in any company, start by adding unit tests every time a bug is identified outside of the development team (by the quality analysis team or in production).

When we talk about unit testing, people usually ask if it’s worth it. What’s the return on investment? How do you know what to test?

If a bug goes out of our team, we can’t afford to let it happen again. It worth it because a regression shows we are not mastering what we are building, and is really annoying for users. We know what to test because we have an exact failing use case.

Use this opportunity to introduce a build server, we want to know before shipping if we have regression.

jenkins.jpgStep 2: the tester strikes back with test first

Most people arguing against unit tests have this experience:
1> They write some unit tests
2> It is incredibly painful
3> They stop testing with the conclusion that unit tests are incredibly painful
(The official explanation is most likely: “It takes too much time to write tests”)

Truth is: writing good code is incredibly hard, writing bad code is freaking easy.

Testing our software do nothing but reveals the nature of our code. It reveals how it behaves when we try to use it. When the code is hard to test, the code is bad, that’s what we need to accept to overcome this step. No need to blame the tools or the methods. What we need is to learn how to improve the code in terms of decoupling and maintainability.

When it comes to an important piece of code, write the test first. It will lead to more testable code, because nobody likes painful things.

huretsjpg

Step 3: Test Driven Development as a rule of thumb

After a few months, if we do not observe any improvement, it is interesting to understand why? In my experience, it may be due to a lack of experience with unit tests (tools and/or methods) and/or a lack of discipline.

But if we observe an improvement due to step 1 and 2, it’s easy to argue that to improve even more, we should not ship any use case not covered by unit tests.

The good news is that our industry already uses an efficient method for that. It’s called Test Driven Development, and we can find tons of documentation online about it.

tdd.jpgStep 4: Less stress and better work

Be disciplined, don’t give up on TDD, and within a few months the results will be clear. The team will feel more confident and less stressed. With less stress, fewer bugs will be shipped, and we’ll have more time to improve, and to drink beers.

No overtime required. Only good habits, discipline and continuous improvement around good practices.

It is important to communicate at this stage. It may take several years to reach such a result. We should remember where we come from, what we did to improve and share our story with other teams.

zen

It’s even better when we’re not alone

Some help by someone who already took a similar path is gold, because she will point out what’s wrong in the code and how to improve it.
She will also be familiar with tools and can avoid silly mistakes we all do when discovering these practices.
She mights also know how to manage tricky managerial issues.

It is with this kind of expertise that such a path can be achieved in a few months, instead of a few years.

path

That’s what a developer can do

This path is not a myth, this path is not a theory.
This path I followed 3 times already, and every single time it helps me to gain confidence, credibility and to be proud of my work.

That’s the kind of things we can do, as developers, to change the way it has always been done.

 

Many Thanks Nelson Da Costa for the review.

 

Clarifying MVVM with DDD

I regularly see a lot of questions around MVVM, last one only a few weeks ago.

The problem is usually the same: what should be a Model, and what should be a ViewModel?
We can’t really blame developers, because references online are not really good, especially MSDN’s one. The explanation is simplified to be understandable for most developers. The result is an oversimplified pattern which doesn’t fit for complex line of business application.

There are many contradictory implementations of MVVM. I’ll describe in this post an effective implementation for me since many years.

Contradiction

Problem roots 

Everybody agree on a ViewModel definition: it is an abstraction of a View. This abstraction is simpler to test than the GUI, we don’t need to run the solution to test a ViewModel in isolation. It decouples UI design from UI behavior.

But what should be in this ViewModel abstraction is really unclear. Usually the implementation is a ViewModel where we put too much business logic, and a simple POCOs Models (mainly because of ORMs). In this case, a question arises: when I use only one Model in one ViewModel, do I need a ViewModel at all ? Can’t I just bind the model and notify the View if one of the properties is updated ?MVVM1

 DDD to the rescue

Domain Model is a tactical pattern from Domain Driven Design (DDD), which could fit the Model in MVVM. Using DDD, we want to avoid Anemic Domain Model, which clarifies what could be a MVVM implementation.

The ViewModel is only an abstraction of the View, and it manipulates Models where the business logic is.

For example a ViewModel can use a User to change an address:

user.ChangeAdress(new Adress("3 route de tartampion", "6900", "Lyon", "France"));

MVVM2What if I need several Models?

Another tactical pattern from DDD could help us: Domain Service. A Domain Service is where we manage interaction between Domain Models. We use it if we do not find a better place to put the business logic for a given use case. Our ViewModel will manipulate Domain Services, which manipulate Domain Models. Typical use case requiring several Models is validation.

For example a ViewModel can use a buying service to validate a command:

_buyingService.Validate(/*products to buy*/, /*current user*/)

MVVM3

What if I don’t know/care about DDD?

Just replace the word DomainModel by Model, and DomainService by BusinessService. Apply SRP to well design classes.

For example in C#, a Model should not be INotifyPropertyChanged, it is a UI concern. It’s the responsibility of a ViewModel to notify a View when a property changed.

In the same idea, a ViewModel should not embed business logic, since it is already responsible for UI behavior. MVVM4Simple rules for simple design 

  • A View has the responsibility to display something to our user. We don’t want any behavior here.
  • A ViewModel has the responsibility to represent the behavior of our View. We talk about UI behavior, not Business behavior.
  • A Model has the responsibility to encapsulate the business logic, and do not care about how it will be display. It’s where we put business behavior.
  • A Business Service has the responsibility to encapsulate the business logic for a given use case, if several Models are involved to meet a business needs.

MVVM6

I tried to give a simple example on Github. (Note that I let the DDD part away).
Any feedback welcome.

 

Thank you Brian Gibson for the suggestion to add diagrams.

 

Panorama to Hub

If you decided to use a Panorama control in your Windows Phone application, then you will be as disappointed as I am to discover Microsoft remove it from the Universal Windows Platform.

With a quick search on the web, you see it should be easy to replace with a Hub control.

But, surprise, the convenient ItemsSource property has been removed. In a panorama it was easy to bind a data source to generate one panorama section per item. You can’t natively do that with a Hub.windows-phone-7-panoramaDear Microsoft, bringing some cool stuff from Linux is great, but please consider keeping convenience for what is already awesome in your development environment: DataBinding. I would even say it’s one of the killer feature of C#/XAML applications.

Anyway, I will describe a DynamicHub implementation, to get the ability to generate one hub section per item in your data source.

First re-create your own DependencyObject. Then when the interesting dependency changes, iterate on your data and create one hub section per item.

    public class DynamicHub : DependencyObject
    {
        public static readonly DependencyProperty HeaderTemplateProperty = DependencyProperty.RegisterAttached(
            "HeaderTemplate",
            typeof(DataTemplate),
            typeof(DynamicHub), new PropertyMetadata(null, HeaderTemplateChanged)
            );

        private static void HeaderTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var hub = d as Hub;
            if (hub == null) return;
            var template = e.NewValue as DataTemplate;
            if (template == null) return;
            foreach (var hubSection in hub.Sections)
            {
                hubSection.HeaderTemplate = template;
            }
        }
        public static void SetHeaderTemplate(UIElement element, DataTemplate value)
        {
            element.SetValue(HeaderTemplateProperty, value);
        }

        public static DataTemplate GetHeaderTemplate(UIElement element)
        {
            return element.GetValue(HeaderTemplateProperty) as DataTemplate;
        }

        public static readonly DependencyProperty SectionTemplateProperty = DependencyProperty.RegisterAttached(
            "SectionTemplate",
            typeof(DataTemplate),
            typeof(DynamicHub), new PropertyMetadata(null, SectionTemplateChanged)
            );

        private static void SectionTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var hub = d as Hub;
            if (hub == null) return;
            var template = e.NewValue as DataTemplate;
            if (template == null) return;
            foreach (var hubSection in hub.Sections)
            {
                hubSection.ContentTemplate = template;
            }
        }
        public static void SetSectionTemplate(UIElement element, DataTemplate value)
        {
            element.SetValue(SectionTemplateProperty, value);
        }

        public static DataTemplate GetSectionTemplate(UIElement element)
        {
            return element.GetValue(SectionTemplateProperty) as DataTemplate;
        }

        public static readonly DependencyProperty DataSourceProperty = DependencyProperty.RegisterAttached(
            "DataSource",
            typeof(object),
            typeof(DynamicHub),
            new PropertyMetadata(null, DataSourceChanged)
            );

        private static void DataSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var data = e.NewValue as IEnumerable;
            var hub = d as Hub;
            var template = GetSectionTemplate(hub);
            var header = GetHeaderTemplate(hub);
            if (data == null || hub == null) return;

            hub.Sections.Clear();
            foreach (var section in data)
            {
                var sect = new HubSection { DataContext = section, ContentTemplate = template, HeaderTemplate = header };
                var hubData = section as IHubData;
                if (hubData != null)
                {
                    sect.Header = hubData.Header;
                }

                hub.Sections.Add(sect);
            }
        }

        public static void SetDataSource(UIElement element, object value)
        {
            element.SetValue(DataSourceProperty, value);
        }

        public static object GetDataSource(UIElement element)
        {
            return element.GetValue(DataSourceProperty);
        }
        private interface IHubData
        {
            object Header { get; }
        }
    }

Here is a XAML example to use it:

        <Hub local:DynamicHub.DataSource="{Binding HubSections}"
                local:DynamicHub.SectionTemplate="{StaticResource HubSectionTemplate}"
                local:DynamicHub.HeaderTemplate="{StaticResource HubHeaderTemplate}">
        </Hub>

And a data template to display it:

            <DataTemplate x:Key="HubHeaderTemplate">
                <StackPanel>
                    <TextBlock Text="HubHeader" Style="{StaticResource TitleTextBlockStyle}"/>
                    <TextBlock Text="{Binding SectionHeader}" Style="{StaticResource TitleTextBlockStyle}"/>
                </StackPanel>
            </DataTemplate>
            <DataTemplate x:Key="HubSectionTemplate">
                <StackPanel>
                    <TextBlock Text="HubSection" Style="{StaticResource BodyTextBlockStyle}"/>
                    <TextBlock Text="{Binding SectionNumber}" Style="{StaticResource BodyTextBlockStyle}"/>
                </StackPanel>
            </DataTemplate>

Hope it helps, full demo code is on GitHub.

 
IP Blocking Protection is enabled by IP Address Blocker from LionScripts.com.