Comperio
Quem deve validar? a função que chama ou a função chamada?
0Fala galera, desta vez vamos falar sobre a responsabilidade de validação dos dados. Quem deve validar, a função que está sendo chamada ou a função que chama?Acho que este é um assunto defendido de diversas maneiras por nós, programadores. Eu não fazia a mínima idéia antes de conhecer o design por contrato(DBC). No DBC contratos são realizados e todas as partes envolvidas devem respeitar o contrato. Se você ainda não conhece o DBC pode olhar um pouco aqui e aqui. Basicamente o contrato é estabelecido indicando o que a função precisa receber(validade dos parâmetros) e o que ela vai retornar quando recebe os parâmetros necessários. Os contratos podem ser feitos com ferramentas como o CodeContracts ou até com comentários,Vamos olhar um exemplo usando comentários
1: public class Calculadora
2: {
3:
4: /// <summary>
5: /// Realiza a divisão entre dois numeros
6: /// </summary>
7: /// <param name="dividendo">Pode ser qualquer valor</param>
8: /// <param name="divisor">Pode ser qualquer valor exceto 0</param>
9: /// <returns></returns>
10: public static Decimal Dividir(Decimal dividendo, Decimal divisor)
11: {
12: return dividendo / divisor;
13: }
14: }
Bem, na pior das hipóteses o desenvolvedor sabe que a validação deve ser feita antes de chamar a função apresentada, além disso sabe que se passar os parâmetros corretos vai obter uma resposta valida. As coisas ficam mais legais quando você está usando ferramentas como o CodeContracts.
Além da notificação ao usuário da função fica relativamente mais fácil de escrever testes para validar o contrato da função, temos em mente quais contratos devem ser respeitados e quais não devem. Uns exemplos de testes contra o contrato.
1: [TestClass]
2: public class CalculadoraTeste
3: {
4:
5: [ExpectedException(typeof(DivideByZeroException))]
6: [TestMethod]
7: public void TesteDividir_DividindoPorZero()
8: {
9: Calculadora.Dividir(10, 0);
10: }
11:
12: [TestMethod]
13: public void TesteDividir_ValorMaximo()
14: {
15: Assert.AreEqual(1, Calculadora.Dividir(Decimal.MaxValue, Decimal.MaxValue));
16: }
17: public void TesteDividir_parametrosSimples()
18: {
19: Assert.AreEqual(10, Calculadora.Dividir(100, 10));
20:
21: }
22:
23: }
Bem, com o DBC aprendi este modelo de desenvolvimento onde na maioria das vezes o cliente deve fazer a validação antes da chamada do método. Os principais benefícios desta abordagem são relacionados à separação de responsabilidades. Quando o cliente valida os dados é possível criar por exemplo uma camada Fachada responsável pelas validações e isolar o Núcleo do sistema que agora não se preocupa mais com códigos de validação. O legal do facade é quando você ainda consegue aproveitar ele em diversos ambientes diferentes, por exemplo trabalho em um projeto onde o Facade é utilizado via Ajax, assim a validação cliente e servidor não fica duplicada.
Outro beneficio legal é a maior facilidade de propagar erro e invalidade dos dados, afinal de contas você vai estar uma camada mais próxima do cliente, não precisa ficar propagando erros por N camadas.
Concluindo, O DBC me ensinou uma maneira legal de validar os dados. Nos projetos em que trabalho gosto da idéia do projeto fachada apesar de ter que escrever mais código ficou feliz em eliminar a duplicidade de validações.
Adicional: você ainda pode gerar testes beaseados em contratos, olhe esta ferramenta.
A way to use facades
0Hello folks, Today in the morning I was reading my email when I saw an interesting post at dotnetarchitects. This post is a discussion about facades and its implementation. A lot of people gave their tips, I also recommend you have a look, I gave my tip too. My tip was based in my experience when using facades.
I’m working in a project called comperio, in this project I have been trying to be a junior architect. We(dev Team) thought that would be nice if we had a layer that could do all validations and if these validations were ok this layer could call the layer that knows how to process the operation.We had decided to use a Facade layer to do these validations, but this facade layer were an server-side layer and we thought, should we do the same code in client side to improve the UX ? after some discussion we decided to use the facade layer to do the validation in both. So we write an action that calls the validate method in facade and it worked fine.
A facade was used because we think that the business logic layer should work as system’s core. Thus any error that could be avoided should avoid before enter in the system’s core. If you look our architecture you can see that the UI project has a reference to Facade project and nothing more. So, every layer or application that wants to use our system’s core must call our facade. The other reason to do it was that we want provide an API, an this API cant use core resources without some validations.
This approach is a simple way to implement validation, if you agree the idea that validation should be done in client and server side. Other cool tip I read was the use of keys in the assembly so we can ensure that the UI project is Using the Facade project.
How to make inheritance in Entity Frameworks
0Hello Guys, since my last post I had some problems when I tried to make some inheritance relationship using entity Framework. After one weekend I Figured out the why I was doing wrong. So I’ll explain how to solve these problems and make your inheritance relationship works.
1º The first Thing to do is create a console application that we’ll use to test our model.
2º Download my DataBase sample backup and restore it in your machine.
3º Add a new ADO.NET Entity Data Model, Generate this model using a existent DataBase, select the database that you restored and select all tables. After it you have a model that contains these tables:
Now You can see that we can make some inheritance relationship. One of these is the inheritance between Person and Academic Person. So academic person is a specific kind of person. Let’s make this inheritance. As you can read in a lot of blogs and sites you have to do some phases to achieve the inheritance. so, the first step is delete the relationship between the tables that you want make the inheritance.
1-delete the relationship between Person and academic Person.
2- Create an inheritance relationship between Person and Academic Person. Right click in person entity and select inheritance.
3- After the inheritance had been done you can see that the Primary key in AcademicPerson(AcademicPersonID) isn’t a primary key anymore. So just think, if academic person inherits person they have to have the same key, so you have to delete the property.
4-After delete the key you have to set the mapping for academicPersonID to PersonID, because as we thought both have to be equals.
After these steps you should be able to use inheritance, but when you try to validate your model you get This message:
Error 11010: Association End ‘AcademicPerson’ is not mapped
I Looked for this error but I get just nonsense answer. So I tried by myself to solve this problem. After some hours I found the solution, this messages means:
The AcademicPerson entity is related to others entities in its model, so if you change the primary key academicPersonID you have to change all relationships to academicPersonEntity.
If you look count the error messages you’ll se that there are four messages and there are four relationships to academicperson too. Therefore, to solve this problem you have to change the relationships, So right-click in the relationship between AcademicPerson and AcademicPersonKnowledgeArea, select table mapping and in the line you see PersonID set the other key to AcademicPersonID.
To solve the error 11010 you have to do the same to all relationships. After it you should be able to validate your model.So now you can use inheritance. Now let’s use our inheritance in our console application.
ComperioBlogEntities Context = new ComperioBlogEntities();
AcademicPerson academicPerson = new AcademicPerson();
academicPerson.AcademicOrganization = Context.AcademicOrganization.FirstOrDefault();
academicPerson.AddressNumber = “01″;
academicPerson.BirthDate = DateTime.Now.Date;
academicPerson.City = “Rio de Janeiro”;
academicPerson.Country = “Brasil”;
academicPerson.EducationLevel = Context.EducationLevel.FirstOrDefault();
academicPerson.Email = “mail@mail.com”;
academicPerson.Enrolment = “0814700001″;
academicPerson.LattesPlatformWebPage = “www.programmingandliving.blogspot.com”;
academicPerson.Name = “Higor”;
academicPerson.Neighbourhood = “VP”;
academicPerson.State = “RJ”;
academicPerson.Street = “ABC Street”;
academicPerson.WebPage = “www.programmingandliving.blogspot.com”;
academicPerson.ZipCode = “21225″;
Context.AddToPerson(academicPerson);
Context.SaveChanges();
If you try to execute you’ll get the error bellow.
This is easy to fix, it means that you have to set off the identity column in academicPerson table. Otherwise the EF cannot set the Same ID of PersonID. So set off the Identity of AcademicPersonID and run your application.
So, I had some other problems but these were the worst ones.
KeyWords:
Entity Framework inheritance erros
Error 11010: Association End is not mapped
An error occurred while updating the entries. See the InnerException for details.