I see a lot of code snippets with this example:
private string _possessor;
public string Possessor
{
get { return _possessor; }
set { _possessor = value; }
}
My questions is, why not just use plain property as in:
public string Possessor { get; set; }
I was reading on the internet, but could not really see the difference? You can either way set values in both examples and second example requires less coding and looks cleaner.
In the case that you are showing, it's true, there are no differences on doing each approach and the second one is cleaner. Knowing the first approach is useful because sometimes you need a property to do more than just get/set so in that case you will need to use the first approach.
You can also see here that with each new c# version, different ways of implement properties were created. The second approach is Auto-implemented properties
The main purpose of doing this is to help achieve data Encapsulation, which helps us by hidden the data in a class from other classes. this is also known as data-hiding.
Another good reason why this is done is when there some special validation or special business rules that needs to be checked before we set that particular value.
You can read more on Encapsulation from this site https://www.geeksforgeeks.org/c-sharp-encapsulation/
I'm modifying an app for performance gains. The app has a class with many properties. Typically this class is populated in its entirety by a primary key that pulls a large query from a database. The application is in great part slow because this happens constantly throughout, even though much of the time only one two properties in the class are needed in a given section of code. The existing large class has only a default constructor and all of its properties are nullable or have default values. In code below ignore lack of constructors and how these objects are populated.
public class Contract
{
public enum ContractStatus
{
Draft, Active, Inactive
}
private Int32 contractId = DALC.DefaultInt32;
private String name = DALC.DefaultString;
private ContractStatus status;
private ContractType contractType = null;
private CurrencyType currencyType = null;
private Company company = null;
}
As you can see it has its own properties, and also references other classes (e.g. ContractType, Company).
A few approaches I've thought of in light of common design patterns:
1) re-factor this hugely and break up those smaller sub-sections into their own classes with their own properties. Then reconstruct that large class with all of the smaller ones when it is needed. This will be quite laborious, though even if it sounds ideal and consistent with SOLID OOD principles.
2) Create new classes that simply contain the large class, but only expose one or two of its properties. I'm still creating a full blown version of the original, large class, but I will only populate the data I need. This will be via simple DB query, thus the bulk of the class will sit there unused and its null default classes it's referencing won't ever be constructed.
public class ContractName
{
Contract contract;
public ContractName()
{
contract = new Contract();
}
public String Name
{
get { return contract.Name; }
set { contract.Name = value; }
}
}
3) Add new constructors to existing large class with a parameter indicating what chunks of code I want to actually populate. This sounds messy and kind of nasty and wrong, and would leave me in the scenario where if Contract is created by a contract ID in one section of code it has different info than if created by contract ID elsewhere.
Thanks for any ideas!
I would recommend option 1: extract the classes you think you need to extract now. The other two options are just adding more technical debt which will take even longer to resolve in the future. Well-factored code is usually much easier to optimise than big complicated classes.
In my experience, breaking up classes is not all that laborious. In fact I usually find myself surprised by how quickly I can execute refactorings like Extract Class as long as I follow the recipe.
i have got various custom datatypes in my web application to map some data from the database.
something like:
Person
Id
Name
Surname
and i need a List of persons in most of my application's pages
i was thinking to create a getter property that gets the list of persons from the database and store into cache in this way i do not have to call the database each time
something Like (pseudo code)
public List<Person> Persons
{
get { return if cache != null return List of Persons from cache else get from the database;}
}
Where shall i put this getter? in my Person class definition or into my base page( page from which all the others pages inherit)
Thanks
I think putting it in your base page would be better option.
Depending on your application architecture, putting process related code in your domain classes might be an issue. Some use it in DDD (domain-driven design) type applications though.
Better even, I usually try to hide those implementation details in a service class. You could have a PersonService class that would contain your above method and all person related operations. This way, any page requiring person information would simply call the PersonService; and you can concentrate your page code on GUI related code.
I don't think that you should put it in your Person class since it accesses the database and HttpContext.Current.Cache. Furthermore I think you should make it a method and not a property, to imply that this may be a "lengthy" operation. So, of the two options, I would put it on the base Page class.
I'm new to the .NET world having come from C++ and I'm trying to better understand properties. I noticed in the .NET framework Microsoft uses properties all over the place. Is there an advantage for using properties rather than creating get/set methods? Is there a general guideline (as well as naming convention) for when one should use properties?
It is pure syntactic sugar. On the back end, it is compiled into plain get and set methods.
Use it because of convention, and that it looks nicer.
Some guidelines are that when it has a high risk of throwing Exceptions or going wrong, don't use properties but explicit getters/setters. But generally even then they are used.
Properties are get/set methods; simply, it formalises them into a single concept (for read and write), allowing (for example) metadata against the property, rather than individual members. For example:
[XmlAttribute("foo")]
public string Name {get;set;}
This is a get/set pair of methods, but the additional metadata applies to both. It also, IMO, simply makes it easier to use:
someObj.Name = "Fred"; // clearly a "set"
DateTime dob = someObj.DateOfBirth; // clearly a "get"
We haven't duplicated the fact that we're doing a get/set.
Another nice thing is that it allows simple two-way data-binding against the property ("Name" above), without relying on any magic patterns (except those guaranteed by the compiler).
There is an entire book dedicated to answering these sorts of questions: Framework Design Guidelines from Addison-Wesley. See section 5.1.3 for advice on when to choose a property vs a method.
Much of the content of this book is available on MSDN as well, but I find it handy to have it on my desk.
Consider reading Choosing Between Properties and Methods. It has a lot of information on .NET design guidelines.
properties are get/set methods
Properties are set and get methods as people around here have explained, but the idea of having them is making those methods the only ones playing with the private values (for instance, to handle validations).
The whole other logic should be done against the properties, but it's always easier mentally to work with something you can handle as a value on the left and right side of operations (properties) and not having to even think it is a method.
I personally think that's the main idea behind properties.
I always think that properties are the nouns of a class, where as methods are the verbs...
First of all, the naming convention is: use PascalCase for the property name, just like with methods. Also, properties should not contain very complex operations. These should be done kept in methods.
In OOP, you would describe an object as having attributes and functionality. You do that when designing a class. Consider designing a car. Examples for functionality could be the ability to move somewhere or activate the wipers. Within your class, these would be methods. An attribute would be the number of passengers within the car at a given moment. Without properties, you would have two ways to implement the attribute:
Make a variable public:
// class Car
public int passengerCount = 4;
// calling code
int count = myCar.passengerCount;
This has several problems. First of all, it is not really an attribute of the vehicle. You have to update the value from inside the Car class to have it represent the vehicles true state. Second, the variable is public and could also be written to.
The second variant is one widley used, e. g. in Java, where you do not have properties like in c#:
Use a method to encapsulate the value and maybe perform a few operations first.
// class Car
public int GetPassengerCount()
{
// perform some operation
int result = CountAllPassengers();
// return the result
return result;
}
// calling code
int count = myCar.GetPassengerCount();
This way you manage to get around the problems with a public variable. By asking for the number of passengers, you can be sure to get the most recent result since you recount before answering. Also, you cannot change the value since the method does not allow it. The problem is, though, that you actually wanted the amount of passengers to be an attribute, not a function of your car.
The second approach is not necessarily wrong, it just does not read quite right. That's why some languages include ways of making attributes look like variables, even though they work like methods behind the scenes. Actionscript for example also includes syntax to define methods that will be accessed in a variable-style from within the calling code.
Keep in mind that this also brings responsibility. The calling user will expect it to behave like an attribute, not a function. so if just asking a car how many passengers it has takes 20 seconds to load, then you probably should pack that in a real method, since the caller will expect functions to take longer than accessing an attribute.
EDIT:
I almost forgot to mention this: The ability to actually perform certain checks before letting a variable be set. By just using a public variable, you could basically write anything into it. The setter method or property give you a chance to check it before actually saving it.
Properties simply save you some time from writing the boilerplate that goes along with get/set methods.
That being said, a lot of .NET stuff handles properties differently- for example, a Grid will automatically display properties but won't display a function that does the equivalent.
This is handy, because you can make get/set methods for things that you don't want displayed, and properties for those you do want displayed.
The compiler actually emits get_MyProperty and set_MyProperty methods for each property you define.
Although it is not a hard and fast rule and, as others have pointed out, Properties are implemented as Get/Set pairs 'behind the scenes' - typically Properties surface encapsulated/protected state data whereas Methods (aka Procedures or Functions) do work and yield the result of that work.
As such Methods will take often arguments that they might merely consume but also may return in an altered state or may produce a new object or value as a result of the work done.
Generally speaking - if you need a way of controlling access to data or state then Properties allow the implementation that access in a defined, validatable and optimised way (allowing access restriction, range & error-checking, creation of backing-store on demand and a way of avoiding redundant setting calls).
In contrast, methods transform state and give rise to new values internally and externally without necessarily repeatable results.
Certainly if you find yourself writing procedural or transformative code in a property, you are probably really writing a method.
Also note that properties are available via reflection. While methods are, too, properties represent "something interesting" about the object. If you are trying to display a grid of properties of an object-- say, something like the Visual Studio form designer-- then you can use reflection to query the properties of a class, iterate through each property, and interrogate the object for its value.
Think of it this way, Properties encapsulate your fields (commoningly marked private) while at the same time provides your fellow developers to either set or get the field value. You can even perform routine validation in the property's set method should you desire.
Properties are not just syntactic sugar - they are important if you need to create object-relational mappings (Linq2Sql or Linq2Entities), because they behave just like variables while it is possible to hide the implementation details of the object-relational mapping (persistance). It is also possible to validate a value being assigned to it in the getter of the property and protect it against assigning unwanted values.
You can't do this with the same elegance with methods. I think it is best to demonstrate this with a practical example.
In one of his articles, Scott Gu creates classes which are mapped to the Northwind database using the "code first" approach. One short example taken from Scott's blog (with a little modification, the full article can be read at Scott Gu's blog here):
public class Product
{
[Key]
public int ProductID { get; set; }
public string ProductName { get; set; }
public Decimal? UnitPrice { get; set; }
public bool Discontinued { get; set; }
public virtual Category category { get; set; }
}
// class Category omitted in this example
public class Northwind : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
You can use entity sets Products, Categories and the related classes Product and Category just as if they were normal objects containing variables: You can read and write them and they behave just like normal variables. But you can also use them in Linq queries, persist them (store them in the database and retrieve them).
Note also how easy it is to use annotations (C# attributes) to define the primary key (in this example ProductID is the primary key for Product).
While the properties are used to define a representation of the data stored in the database, there are some methods defined in the entity set class which control the persistence: For example, the method Remove() marks a given entity as deleted, while Add() adds a given entity, SaveChanges() makes the changes permanent. You can consider the methods as actions (i.e. you control what you want to do with the data).
Finally I give you an example how naturally you can use those classes:
// instantiate the database as object
var nw = new NorthWind();
// select product
var product = nw.Products.Single(p => p.ProductName == "Chai");
// 1. modify the price
product.UnitPrice = 2.33M;
// 2. store a new category
var c = new Category();
c.Category = "Example category";
c.Description = "Show how to persist data";
nw.Categories.Add(c);
// Save changes (1. and 2.) to the Northwind database
nw.SaveChanges();
I'm having trouble understanding how to use ORM generated objects. We're using LLBLGen for mapping our database model to objects. These objects we encapsulate in another layer which represents our business model(I think).
Maybe this bit of code will explain this better.
public class Book { // The class as used in our application
private BookEntity book; // LLBLGen entity
private BookType bookType; // BookType is another class that wraps an entity
public Book(int Id) {
book = new BookEntity(Id);
}
public BookType BookType {
get { return this.bookType; }
set {
this.bookType = value;
this.book.BookType = new BookTypeEntity(value.ID);
this.book.Save();
}
}
public int CountPages() { } // Example business method
}
Exposing the entity's fields like properties feels awkward, since I'm mapping all over again. With list-types it's even much worse, since I have to write a "Add" and "Remove" method plus a property that exposes List.
In the above example in the BookType setter I need access to the BookTypeEntity object, I can get this object by instantiating a new one using the ID oh the BookType object. This also doesn't feel good.
I'm wondering if I shouldn't just extend the BookEntity object and add my business logic there? Or maybe use partials?
In the LLGLGen examples they use the entity objects directly, but this looks very messy to me. I want to have objects which can also have methods for my business logic(like CountPages) in the code above.
I've never used LLBLGen for mapping, but most of the ORM tools I've worked with generate partial classes. I then add any custom code/logic I'd like to add to those objects in a seperate file (so they don't get over-written if the partial classes are re-generated).
Seems to work pretty well. If you don't get partial classes from your ORM, I'd create a Facade which wraps your Data Object with your Business Logic...that way the two are seperated and you can re-gen one without overwriting the other.
UPDATE
Partial classes support implementing an Interface in one declaration of a partial class and not the other. If you want to implement an interface, you can implement it in your custom code partial file.
Straight from MSDN:
partial class Earth : Planet, IRotate { }
partial class Earth : IRevolve { }
is equivilant to
class Earth : Planet, IRotate, IRevolve { }
Dunno if it's possible in LLGLGen, but what I generally do when working with ORMs is to create an interface to the persisted class, in your example IBook. I expose this interface via a public getter from the wrapping class. This way, if needs will be, you can extend you IBook the way you want if you need to add some custom behaviour to its fields.
Generally speaking, I think there's 3 ways of "mapping" your ORM-entities to your domain:
The way you've posted. Basically, remap everything again
The way I posted, expose the ORM-entity as an interface
Expose the ORM-entity directly
I don't like #1, cause I don't like to have 2 mappings in my application. DRY, KISS and YAGNI are all violated by this.
I don't like #3 cause it would make whatever consumer-layer of your domain-layer talk directly to the ORM layer.
.. So, I go with #2, as it seems to be the lesser of 3 evils ;)
[Update] Small code snippet :)
ORM-generated class in the data-layer:
public class Book : IBook
{
public string ISBN {get; private set;}
}
IBook is found in the business-logic layer, along with a book wrapper:
public interface IBook
{
string ISBN {get;}
}
public class BookWrapper //Or whatever you want to call it :)
{
//Create a new book in the constructor
public BookWrapper()
{
BookData = new Data.MyORM.CreateNewBook();
}
//Expose the IBook, so we dont have to cascade the ISBN calls to it
public IBook BookData {get; protected set;}
//Also add whichever business logic operation we need here
public Author LookUpAuther()
{
if (IBook == null)
throw new SystemException("Noes, this bookwrapper doesn't have an IBook :(")
//Contact some webservice to find the author of the book, based on the ISBN
}
}
I don't know if this is a recognizable design-pattern, but it's what I use, and so far it has worked quite well :)
You are feeling the pain of the mismatch between the different paradigms of relational data and objects.
By this, I mean that the worlds of relational data and objects are very, very different from each other. For example, in database-land all data is public. In object-land, data is encapsulated and very specifically not made public. In database-land, all relationships are bi-directional, whereas in object-land an object in a collection might not have any reference to its parent. In database-land, procedures are global. In object-land, procedures are local to the object which contains the acted-upon data.
For these reasons and more, an approach which creates objects that represent database tables is inherently going to be painful. While yes, technically they are objects, they have the semantics of database-land. Making them live in object-land, as you have experienced, is difficult if not impossible. This can be referred to as data-first.
A better approach (in my opinion) is to focus on mapping objects to the database, rather than mapping the database to objects. This can be referred to as object-first, and is supported very well by NHibernate. This approach emphasizes the fact that a database is an implementation detail of a system, not a design precept.
I realize this doesn't specifically answer your question, but I hope it provides some context as to why you are having a hard time conceptualizing your entities: they are tables first and entities second.