should I use accessors or not? - encapsulation

I have programmed for about 2-3 years now and actually I am developing a game in actionscript atm. I have a character class which have some fields like name, level, experience, damage, defence and so on. right now I have made them protected so the deriving classes can see them, and I have used getters and setters to encapsulate them, so other classes only can see the getters. However in actionscript it seems that you can't make accessors protected, so they must be public. But why should I use accessors at all if anybody can just see them and edit them anyway? Should I just skip the encapsulation and just go with public fields and encapsulate the ones who need to do some other statements when set. For instance if I increase the experience field it should check for a level up while increasing.
I like accessors in c# because they make the coding easier as you can't see private/protected accessors in other classes.
It would be nice to have some more experienced programmers opinion on accessors.

Accessors are a great convention, but I suppose you don't have to follow that.
The advantage of using them is you have a better API, that is, it's pretty obvious what the IncreaseLevel() function does.
Also, you have the flexibility to notify other parts of your code. For instance, if every time you increase a level, you want a certain animation to take place, it could take place in the IncreaseLevel() function. All in all, I recommend it.

Related

Update form from class or interface

I have a winform onto which I have a number of controls across a few tabs. I am writing logic which will enable / disable some of these controls based on the combo box selections made by the user. I am guessing that writing the logic in frmMain.vb isn't best practice so I'm wondering whether I should gain access to my form's controls through:
an interface
through friend-declared properties in frmMain.vb that are accessed by another class or
Other
Any help would be welcome!
In general it is a good idea to tie your front-end code to a buisiness logic layer so that it is the logic that controls the enabling/disabling of the controls. If possible, group the controls based on what will get disabled together, then make a routine that disables them all at once, and name it well, like disableAddContactInfoArea() or SetAddContactInfoArea(boolean isEnabled). In my mind, the routine will sit in frmMain.vb.
One thing to avoid is just exposing each individual control to another class (unless, in ine case, that is all you need for a specific business process - but even then you should put it in a routine and name it well to make future edits easy and less complex). Your primary objective is to manage complexity (check out Steve McConnell's book Code complete, maybe chapter 7 for this).
An ideal would be to have a few public Subs on the frmMain.vb, only there to do exactly what needs done, then have the business logic layer call those routines on the instace of frmMain that you are using.

please help with best approach for extension of WPF built-in class

I want to extend Shapes.Rectangle WPF built-in class with some additional proprietary properties. I can do this in 3 different ways:
Declare my own wrapper class and have WPF Rectangle as one of its members.
Declare my own struct/class with my proprietary properties and put it in Rectangle.Tag field.
Declare WPF dependency property for each of my proprietary properties and use Rectangle.SetValue() & Rectangle.GetValue() methods.
What is the best approach from performance point of view (speed, memory consumption), giving that at every moment only part of my proprietary properties will have meaningful value ?
Thanks.
You can Create a Behavior that extends Behavior.
That's the best and easiest way (and Blend friendly) to add behavior to existing elements.
It's part of WPF4 now, and you can use it after u add a reference to System.Windows.Interactivity.
Are you going to be using your "sort of" derived Rectangle everywhere, or is it going to sometimes be a Rectangle and sometimes yours?
If you're going to be using some of your properties every single time, I would say you should create a wrapper class and just keep it as lightweight as possible. That'll keep your code as clean as possible. I don't think the performance will be an issue unless you're doing thousands of these. And if you are, then you might have other issues! :)

Whats so bad about binding your View to Property of a Model and NOT ViewModel?

I often hear a Model must be wrapped by a ViewModel that the View is not coupled to the Model/not aware of it.
With MVC it is common to bind the View to the Model... nobody complains so what ?
I am frightened of creating all that wrappers and doing nearly only duplicating property stuff.
In some cases you don't need to, just as you don't need properties in many cases but can get away with public fields.
But your model should mirror the domain structure and logic, while a view model mirrors the UI structure and logic. At least, as far as I understood it. Those two are not necessarily the same and each one can change independently from the other.
You should always apply a pattern to your individual problem, and modify it in areas where it does not apply. Just because the pattern implies the usage of a view-model, doesn't mean you necessarily need a view-model in every scenario. In the case that your model exposes all of the needed properties and no further abstraction is needed, maybe a view-model is unnecessary.
However, in many cases the view-model will eventually be of great use and far easier to maintain than adding extra properties to the model. Consider this carefully before binding directly to the model.
The ViewModel is used to only pass the data that you really need to a view.
When you use the model, instead of the viewmodel it is possible that you use data that came directly from the database.
When using the model the wrong way, it is possible to edit data in the database that you don't want to edit.
It is safer to use a ViewModel.
One point which didn't seem to come up (directly) yet is that ViewModel can easily support data that should never even be in the model such as the text typed in the search text box or selected list items in case these values are needed in commands or further data bindings and passing them as parameters every time seems like too much trouble.
But as stated already, if you are confident that all the data you need is already available in the Model, go ahead and do away with the ViewModel.
One common scenario where ViewModels come in very handy is when Enum values should be displayed. In my eyes, a ViewModel is the perfect place to convert Enum values to user-friendly representations. You could even introduce a localization step in your ViewModel.
Furthermore, ViewModels can simplify some other scenarios. However, as you said, they can also duplicate a lot of code. That said, you could create a ViewModel with a Model property which allows to bind directly to the properties of the Model class. Now if you later realize that you need some conversion step, you can still add that property to the ViewModel and bind to that property.
But I think in most cases it makes sense to use a ViewModel from the beginning because it might be hard to introduce it in a later development stage.
There is no problem binding directly to a Model from your View where possible.
What you will find though is very quickly you run into a situation where you need to model things your view needs that aren't in your Model.
Given you never want to corrupt your Model with View concerns, you are left with no choice but to create a ViewModel.
It depends on may indicators: e.g. if your model is provided by EF there's no point in exposing it to your View - why the heck the View would need all model's method/properties and tons of stuff (not mentioning data security) But if your model is really simple and you feel, that you're not going to expand/change it much by and VM, there's nothing on the way to use it just like that :)
You might as well ask, "What's wrong with putting all the functionality of my program into one giant class?" On the one hand, there's nothing wrong; it can be made to work. On the other hand, everything is wrong: if your program is one big ball of wire, you have to straighten all of it out in order to change any of it.
Look at a Windows Forms programmer written by a beginner. You'll find all of the business logic in the buttons' Click event handlers. What's wrong with that? Don't you want that logic to be executed when the user clicks the button?
This is essentially what you're proposing doing within the world of WPF. Will it work? Sure. For trivial projects, it may even work well. You're accumulating technical debt, though, and when the time comes, you'll have to pay it off by refactoring your code into something manageable.

WPF UI element naming conventions

Although Hungarian notation is considered bad practice nowadays, it is still quite common to encode the type in the name of user interface elements, either by using a prefix (lblTitle, txtFirstName, ...) or a suffix (TitleLabel, FirstNameTextBox, ...).
In my company, we also do this, since it makes code written by co-workers (or by yourself a long time ago) easier to read (in my experience). The argument usually raised against doing this -- you have to change the name of the variable if the type changes -- is not very strong, since changing the type of a UI element usually requires rewriting all parts of the code were it is referenced anyway.
So, I'm thinking about keeping this practice when starting with WPF development (hmmm... should we use the txt prefix for TextBlocks or TextBoxes?). Is there any big disadvantage that I have missed? This is your chance to say "Don't do this, because ...".
EDIT: I know that with databinding the need to name UI elements decreases. Nevertheless, it's necessary sometimes, e.g. when developing custom controls...
Personally, I find that WPF changes the rules when it comes to this. Often, you can get away with little or no code behind, so having the prefixes to distinguish names makes things more confusing instead of less confusing.
In Windows Forms, every control was referenced by name in code. With a large UI, the semi-hungarian notation was useful - it was easier to distinguish what you were working with.
In WPF, though, it's a rare control that needs a name. When you do have to access a control via code, it's often best to use attached properties or behaviors to do so, in which case you're never dealing with more than a single control. If you're working in the UserControl or Window code-behind, I'd just use "Title" and "Name" instead of "txtTitle", especially since now you'll probably only be dealing with a few, limited controls, instead of all of them.
Even custom controls shouldn't need names, in most cases. You'll want templated names following convention (ie: PART_Name), but not actual x:Name elements for your UIs...
In my experience - In WPF when you change the type of a control, you normally do not have to rewrite any code unless you did something wrong. In fact, most of the time you do not reference the controls in code. Yes, you end up doing it, but the majority of references to a UI element in WPF is by other elements in the same XAML.
And personally, I find "lblTitle, lblCompany, txtFirstName" harder to read than "Title". I don't have .intWidth and .intHeight (goodbye lpzstrName!). Why have .lblFirstName? I can understand TitleField or TitleInput or whatever a lot more as it's descriptive of the what, not the how.
For me, wishing to have that type of separation normally means my UI code is trying to do too much - of course it's dealing with a UI element, it's in the window code! If I'm not dealing with code around a UI element, why in the world would I be coding it here?
Even from a Winforms perspective I dislike semi-hungarian.
The biggest disadvantage in my opinion, and I've written a LOT of ui code is that hungarian makes bugs harder to spot. The compiler will generally pick it up if you try to change the checked property on a textbox, but it won't pick up something like:
lblSomeThing.Visible = someControlsVisible;
txtWhatThing.Visible = someControlsVisible;
pbSomeThing.Visible = someControlsVisible;
I find it MUCH easier to debug:
someThingLabel.Visible = someControlsVisible;
whatThingTextBox.Visible = someControlsVisible;
someThingPictureBox.Visible = someControlsVisible;
I also think it's far better to group an addCommentsButton with an addCommentsTextBox than to group a btnAddComments with a btnCloseWindow. When are you ever going to use the last two together?
As far as finding the control I want, I agree with Philip Rieck. I often want to deal with all the controls that relate to a particular logical concept (like title, or add comments). I pretty much never want to find just any or all text boxes that happens to be on this control.
It's possibly irrelevant in WPF, but I think hungarian should be avoided at all times.
I like using a convention (just a good idea in general), but for UI stuff I like it to have the type of the control at the front, followed by the descriptive name -- LabelSummary, TextSummary, CheckboxIsValid, etc.
It sounds minor, but the main reason for putting the type first is that they'll appear together in the Intellisense list -- all the labels together, checkboxes, and so on.
Agree with the other answers that it's mainly personal preference, and most important is just to be consistent.
On the need for naming at all, given the prevalence of data binding... one thing you might want to consider is if your UI is ever subjected to automated testing. Something like QTP finds the visual elements in an application by Name, and so an automation engineer writing test scripts will greatly appreciate when things like tabs, buttons etc. (any interactive control) are all well named.
In WPF you practically never need (or even want) to name your controls. So if you're using WPF best practices it won't matter what you would name your controls if you had a reason to name them.
On those rare occasions where you actually do want to give a control a name (for example for an ElementName= or TargetName= reference), I prefer to pick a name describing based on the purpose for the name, for example:
<Border x:Name="hilightArea" ...>
...
<DataTrigger>
...
<Setter TargetName="hilightArea" ...
I prefix any user-interface name with two underscores, as in __ so it is sorted before other properties when debugging. When I need to use IntelliSense to find a control, I just type __ and a list of controls displays. This continues the naming convention of prefixing a single underscore to module level variables, as in int _id;.
You can use the official Microsoft website for Visual Basic 6 control naming conventions, and perhaps combine it with the recommended C# naming conventions. It's very specific, is widely used by developers in C# as well for control names, and can still be used in a WPF or Windows Forms context.
Visual Basic 6 control naming conventions: Object Naming Conventions
C# recommended naming conventions in general: General Naming Conventions

What are the best characteristics of a datalayer framework for WPF/MVVM applications?

I am creating a WPF/MVVM framework which generates the code for the model classes.
I'm planning to have for each database-table/web-service (e.g. "Customers") two model classes:
a singular model class (e.g. "Customer")
and a plural model class (e.g. "Customers")
The singular model class has all of its properties (FirstName, LastName, etc.) plus all of it methods which make sense for a singular instance, e.g. Save(), Delete(), CalculateSalary(), etc.
The plural model class has a collection of singular model objects, plus the same methods since you would want to also perform on a group of singular objects, e.g. Save(), Delete(), CalculateSalary(), but also particular methods such as Sort(), and methods that made it very easy to certain groups, e.g. LoadAllGoldCustomers(), or even LoadWithSql(string sql), etc.
I've done a framework like this before (PHP) and it made for very easy to write and understand code like this:
Customers customers = new Customers("all");
customers.CalculateSalary();
A couple inherited classes (Item and Items) took most of the code out of the individual singular and plural classes for each database table, which made a very clean environment to program in.
However, I have rarely seen other applications do this singular/plural model class split. Instead, there is almost always just one class for each database table, e.g. Customer and this class has any plural methods necessary, e.g. GetCustomers(string sql), etc.
I just noticed in the WPF Model-View-ViewModel Toolkit 0.1 walkthrough, they have you make two models their "Models" directory two classes:
Customer.cs (fields only)
CustomersDataSource.cs (one List Load() method)
Which seems to be a similar concept, just that the "plural" class is called a DataSource.
So now I am about to make another framework based in WPF/MVVM and can decide how I want to structure the model classes. I want the framework to be:
clear and easy to program against from the ViewModel, hence the clear separation of singular and plural model classes, you should just have to instantiate a singular or plural class and call a method on it and you have your data.
fit in well with the MVVM pattern (which I understand means to keep as simple as possible, just have properties and methods that the ViewModel can call, but implement no WPF-specific features such as INotifyProperityChanged)
want my datalayer to sit above any datasource, so if I use LINQ-to-SQL, I still call my own model classes, and if I want to switch to saving in Oracle, I write a lower data adapter layer for my classes to interact with that.
take advantage of LINQ in the best way possible
I would appreciate feedback from those who have developed datalayers for frameworks especially using WPF/MVVM/Composite Application Library and what characteristics you found worked best, or if you have worked with other frameworks such as CSLA, Subsonic, etc. Also, any experience or ideas on how LINQ changes/simplifies building a datalayer structure. Thanks.
Wow. That's a hard question to answer without having a day to sit down and speak with you. But here goes a shortened version anyway.
First, attempting to port a framework or any characteristics of that framework from one language to another seems like it maybe be trying to shove a square peg in a round hole. While I don't doubt that features (e.g. customer and customers) can be ported, I could certainly argue that they shouldn't be ported. Sticking with the customer.CalculateSalary exmaple, you could use .NET and create an extension method for IEnumerable that did the same thing, eliminating the need for that Customers class. I realize you may have other features as well, but that's just an example. Another example is using LINQ to sort IEnumerable.
Second, I have personally found that having the persistence methods (e.g. Save, Delete, etc.) inside of the object doesn't work well in a large system, particularly when dealing with WCF. It seems to work better in these scenarios to use some type of repository later, which seems like it would also play well with your point of switching to Oracle in the middle of development.
I also want to totally disagree with you on the bullet about fitting well into MVVM. To me, the view model is the glue between the model and the view. It is not only likely that the view model would need to know about the view (hence, WPF specific features), but desired that it know about it. ICommand is a critical interface for the view model to know about, and is one of the WPF-y assemblies (WindowsBase, PresentationCore, PresentationFramework, can't remember which). Also, INotifyPropertyChanged is also critical to data binding and should be implemented in all view models, and has nothing to do with WPF (comes from System.ComponentModel i think?).
That's my two cents. Again, it's really difficult to explain this in a short response to your question. I would recommend using the pattern for a while before making a framework for it. Good luck!

Resources