i am building a sort of program that generates a random list of word according to a database.
I Made a class that deals with the word selecting and handling (a random select function, a connect to the database function etc..)
I have 3 variables that indicate the last 3 words chosen.
how do I use a funcion on the form1 (button 1 press), to manipulate the same 3 variables, without creating them from scratch everytime (what happens now...)
To make myself clearer:
accualy what I need is to know how to keep track of a variable between multiple classes.
I might be using the whole classes thing wrong... I am now triyng to get the grasp of it.
Thank you very much,
Barak.
Your two options as I see it are:
1) an instance of a class that holds those variables that can be passed around
You may want to use the singleton pattern for this class if you want to make sure there is only ever one of them.
2) A static class with static members holding this information.
It may be that your entire random word class could be static. In this case you'd just call the methods and properties on that class to generate and access your words.
Also I would suggest that you may want to consider a collection to hold your words rather than three separate variables. It will of course depend on your implementation so I will mention it just inc ase you haven't thought of it and I'm not saying you definitely should. :)
I would avoid static or Singletons just for this purpose - they're not good habits to pick up for simple object oriented scenarios.
Encapsulate the state variables in a class, which you instantiate first, then pass by reference into the form and/or data fetch logic.
Key to this is understanding the concept of reference - your form and fetch logic will see the same instance of your state class, effectively sharing it.
If you implement the "variables" as properties on the state class, you can use events to notify other parts of your code when the word states change.
Consider also clearly defining the possible interactions (interfaces) on the state class. One aspect seems to be to add a word, another to pull out statistics based on the added words. The state class can accommodate all this, and provide a nice place for future extensions.
Try to think in terms of public interface methods/properties, while keeping "variables" (i.e. fields like counters or collections) private.
I also agree that your post should be improved with snippets of actual code - help us helping you.
And I hope your code is not being used to generate spam mails/posts... :-)
Related
My teacher told me that encapsulation is data/information hiding.
But what I understand from here is that Encapsulation is bundling data and methods that act on that data into one unit. And that [encapsulation] allows us to create information hiding mechanisms. Like, making a variable read-only, or making it accessible through some checkpoints.
Am I right that encapsulation in itself is not data hiding, but a way through which we can hide data?
There is no authoritative source that can tell you with full confidence. You (we all) have to ask unfortunately every time it comes up what exactly the speaker/writer means.
Most of the time is encapsulation a little bit more than information hiding.
Encapsulation is a bit more abstract, and may refer to not just data, but logic or any knowledge in general.
Data hiding is just that (normally), hiding the data (the instance variables).
How these things get implemented is a source of even more debate! For example some (if not most) people refer to data hiding when instance variables are simply declared private. Even if there is a public getter for that same data! (the linked article seem to support this position)
Again for others (myself included) calling data hidden when there is a public getter for it sounds strange to say the least.
Some people insist that getters are ok (the data hiding applies) if the returned data is immutable, since it can not be changed.
Encapsulation is often used together with logic. For example: I encapsulate how to send emails in this class, etc.
The problem is, everyone uses the same words, so it's nigh impossible to tell what someone really means by either of these things. If you want to know what someone is talking about, always demand an example (or two).
I will give an explanation to encapsulation and data hiding as I understood from code complete book
When you create a class/method the primary goal is to reduce complexity of your program. You create a class/method to hide information so that you won’t need to think about it. Sure, you’ll need to think about it when you write the class/method. But after it’s written, you should be able to forget the details and use the class/method without any knowledge of its internal workings.
So each class/method should ask a question "What should I hide in order to reduce complexity?" and hence you start to create the interface that this class/method provides to the outside world (other classes/methods). This consists of creating a good abstraction for the interface to represent and ensuring that the details remain hidden behind the abstraction.
Abstraction helps to manage complexity by providing models that allow you to ignore implementation details. Encapsulation is the enforcer that prevents you from looking at the details even if you want to. If I declare a method as private, I'm forcing that it should be used only inside the class and not from outside and if I declare it as public I'm saying that it is part of the interface this class is providing and it can be used from outside. The two concepts are related because, without encapsulation, abstraction tends to break down.
It means you can't mess with the other object's innards unless that object lets you. It is encapsulated, in a capsule you can't get into. An artifact of this is hiding information. If you are closed up, and only you can open things up, then you've pretty much hidden everything inside of yourself. Thus, the hiding is a consequence of encapsulating.
Think of a Birthday class that takes in a Birthdate (DateTime) in the constructor.
It has properties the following that are filled
Public Property _ZodiacSign As String = String.Empty
Public Property _ChineseZodiac As String = String.Empty
Public Property _ChineseZodiacChar As String = String.Empty
Public Property _is21AndOver As Boolean
Public Property _ChineseDate As String
Public Property _EstimatesConvievedDate As DateTime
You have no idea what the logic is to figure out the zodiac sign or chinesezodiac or are they over 21, it is a black box.
I am wonder what is best to do.
I have main function with iteration loop.
For each item in the list I need to get data from the db by using NHibernate.
There are sub functions which are called in the iteration loop body.
In each sub function I need to use data from the item association tables.
for ex. If the Item is Teacher, each func need the Teacher.Students and etc. In my case the record list include many items.
So my question what is better:
1 - To send the Teacher.Students to each sub func.
or 2 - Declare a class variable that all the func know it and it will initialized on each iteration.
Thank in advance!
Imagine you would maintain the code, but somebody else wrote it. It would be much easier for you to understand what a function does if you see what it is receiving as input. So you know what kind of data a function processes. You should not use a class variable if you can just call your function with this data as input.
You can read about good programming style at Elements of Programming Style
From there you get:
Use variables at the smallest possible level of scope. One implication of this rule is that you should minimize the use of global variables. There is a place in good programming style for global variables, and that is for a body of knowledge that will be acted on by many sections of the program, and which is in some sense the major essence of that program. Don't use global variables as a convenient means to communicate between two subroutines.
You should avoid using any kind of global variables and always store your data in the smallest possible scope. This is one of the principles of good design.
The code is so clearer easier to understand, maintain, reuse and change. Dependencies are kept low.
Imagine you need to change this code in the future. If you touch a global variable, you might possibly break some code on the other side (as other methods can use the same variable). If it is localizes, you just need to analyse the impact inside of the method.
Besides, the method with parameters is nicelly encapsulated and its signature is self-explanatory. YOu can even possibly reuse it in the future!
UPDATE
There are a lots of resources on internet, here is a good start: http://www.oodesign.com/design-principles.html
In your case the use of global variables clearly breaks the Open-closed Principle:
Software entities like classes, modules and functions should be open
for extension but closed for modifications.
If you use the global variable instead of sending parameter (Teacher.Students), your method is obviously not closed for modifications, as any change to this global variable (not part of the method!) cause potential crash in the method. With the parameter, your method is closed and protected.
I too think on the line of using functions instead class level variables.
When i try to create good object hierarchy which will help to write less code and avoid to use unnecessary fields ,i feel myself free to create many base classes for good grouping which is usually abstract.
What can be disadvantage of doing it like that ? Many times inherited class can be slower ?
To see many unnecessary abstract classes which hasn't enough good naming can cause confusing when encounter it in intelli-sense(auto-complete) ? What can be other else ?
Many times inherited class can be slower?
There's only one way to answer performance questions: try it both ways, and measure the results. Then you'll know.
What can be disadvantage of doing it like that?
The disadvantage of overly complex object hierarchies are:
1) they are confusing because they represent concepts that are not in the business domain
For example, you might want to have a storage system that can store information about employees, computers and conference rooms. So you have classes StorableObject, Employee, Room, Computer, where Employee, Room and Computer inherit from StorableObject. You mean "StorableObject" to represent something about your implementation of your database. Someone naively reading your code would ask "Why is a person a "storable object?" Surely a Computer is a storable object, and a Room is where it is stored. When you mix up the mechanisms of the shared code with the meaning of the "is a kind of" relationship in the business domain, things get confusing.
2) you only get one "inheritance pivot" in C#; it's a single inheritance language. When you make a choice to use inheritance for one thing, that means you've chosen to NOT use inheritance for something else. If you make a base class Vehicle, and derived classes MilitaryVehicle and CivilianVehicle, then you have just chosen to not have a base class Aircraft, because an aircraft can be either civilian or military.
You've got to choose your inheritance pivot very carefully; you only have one chance to get it right. The more complicated your code sharing mechanism is, the more likely you are to paint yourself into a corner where you're stuck with a bunch of code shared, but cannot use inheritance to represent concepts that you want to model.
There are lots of ways to share code without inheritance. Try to save the inheritance mechanism for things that really need it.
I have just made a very simple practical test (unscientific though) where I created empty classes named A, B, C ... Q, where B inherited from A, C from B and so on to Q inheriting from P.
When attempting to retrieve some metrics on this I created some loops in which I simply created x number of A object, x number of B objects and so on.
These classes where empty and contained only the default constructor.
Based on this I could see that if it took 1 second (scaled) to create an object of type A then it took 7-8 seconds to create an object of type Q.
So the answer must be YES a too deep hierarchy will impact performance. If it is noticable depends on many things though, and how many objects you are creating.
Consider composition over inheritance, but I don't think you'll experience performance issues with this.
Unless you're doing reflection, or something like that where your code has to walk the inheritance tree at runtime, you shouldn't see any speed differences, no matter how many levels of inheritance a class has, or no matter how many classes implement your particular class.
The biggest drawback is going to be making your code unnecessarily brittle.
If class B is implementing/inheriting A just because B is going to need similar fields, you will find yourself in a world of hurt six months later when you decide that they need to behave differently from A to B. To that regard, I'll echo k_b in suggesting you'll want to look at the Composition pattern.
This question already has answers here:
Order of items in classes: Fields, Properties, Constructors, Methods
(16 answers)
Closed 9 years ago.
Is there a standard way of laying out a C# file? As in, Fields, then Properties, then Constructors, etc?
Here's what I normally do, but I'm wondering if there's a standard way?
Nested Classes or Enums
Fields
Properties
Events
Constructors
Public Methods
Private Methods
Do people group their fields together, or do they put them with the properties? Or do people not worry about an order? Visual Studio seems to make it so hard to do.
Edit: Moved other part about ReSharper here: Make Resharper respect your preference for code order.
I tend to use Microsoft StyleCop, which has a set order according to rule SA1201:
Cause An element within a C# code
file is out of order in relation to
the other elements in the code.
Rule Description A violation of this
rule occurs when the code elements
within a file do not follow a standard
ordering scheme.
To comply with this rule, elements at
the file root level or within a
namespace must be positioned in the
following order:
Extern Alias Directives
Using Directives
Namespaces
Delegates
Enums
Interfaces
Structs
Classes
Within a class, struct, or interface,
elements must be positioned in the
following order:
Fields
Constructors
Finalizers (Destructors)
Delegates
Events
Enums
Interfaces
Properties
Indexers
Methods
Structs
Classes
Complying with a standard ordering
scheme based on element type can
increase the readability and
maintainability of the file and
encourage code reuse.
When implementing an interface, it is
sometimes desirable to group all
members of the interface next to one
another. This will sometimes require
violating this rule, if the interface
contains elements of different types.
This problem can be solved through the
use of partial classes.
Add the partial attribute to the class, if the class is not already
partial.
Add a second partial class with the same name. It is possible to place
this in the same file, just below the
original class, or within a second
file.
Move the interface inheritance and all members of the interface
implementation to the second part of
the class.
I think there's no best way. There are two important things to consider when it comes to layout. The first most important thing is consistency. Pick an approach and make sure that the entire team agrees and applies the layout. Secondly, if your class gets big enough that you are searching for where those pesky properties live (or have to implement regions to make them easier to find), then your class is probably too large. Consider sniffing it, and refactoring based on what you smell.
To answer the reshaper question, check under Type Members Layout in Options (under the C# node). It's not simple, but it is possible to change the layout order.
I don't believe regions are necessarily a sign of bad code. But to determine that you will have to review what you have. As I've stated here this is how I regionize my code.
Enumerations
Declarations
Constructors
Methods
Event Handlers
Properties
But the main thing is keeping it consistent and purposeful.
I tend to clump private data and tend to clump related methods/properties in functional groups.
public class Whatever {
// private data here
int _someVal = kSomeConstant;
// constructor(s)
public Whatever() { }
#region FabulousTrick // sometimes regionize it
// fabulous trick code
private int SupportMethodOne() { }
private double SupportMethodTwo() { }
public void PerformFabulousTrick(Dog spot) {
int herrings = SupportMethodOne();
double pieces = SupportMethodTwo();
// etc
}
#endregion FabulousTrick
// etc
}
You can try Regionerate to help with this. I really like it and it's a Scott Hanselman pick.
As said, I don't think there is a best way as such. But some organisation does help you the programmer.
How often in a long project have you spent time going up and down one or more source files trying to find one of your functions.
So I make use of the #region a lot to in this sort of way -
region Events : All of the event references that this class uses (at least in this particular partial class).
region Controls : All functions that directly interact with controls on a form.
region MDI : set the mdi up
Then there will be some to do with functionality rather than interface,
region Regex searches
I sort of make it up as I go along, but using the same pattern I always use. I must say I have been told by some programmers picking up my work that it is easy to follow and others that its messy.
You can please half the people half the time and the other half a quarter of the time and the other quarter of the time you confuse everyone including yourself. I think Winston Chrchil said that.
Whatever makes your more productive. Some like private fields next to property accessors, some like fields together above the constructors. The biggest thing that can help is grouping "like," elements. I personally like bringing together private methods, private properties, etc.
Try some things out and again, whatever you feel makes you more productive and helps you keep your code maintained.
Each to their own, but I tend to follow the same order that the MSDN help follows.
I also don't like to nest classes or enums, instead create separate files for them, that also makes writing unit tests easier (since it's easy to find the associated test file when you need to add/fix/refactor a test).
IMHO the order isn't that important because VS makes it very easy to find all members (especially if you follow the one class/interface/enum per file approach), and Sandcastle will group them if you want to build docs, so I'd be more concerned about giving them meaningful names.
On top of keeping a consistent set of regions in your class files, I keep all components of a region in alphabetical order. I tend to have a bit of "visual memory" when it comes to reading code and it drives me crazy having to use the navigation dropdown to find code in a file because it's all over the place.
I use the following layout:
events
globals/class-wide fields
private/internal
properties
methods
public/protected
properties
methods
nested classes (although I try to avoid these whenever possible)
I also firmly believe in 1 code "thing" (class, interface, or enum) per file, with the file name the same as the "thing" name. Yes, it makes a larger project but it makes it infinately easier to find things.
Why use a GlobalClass? What are they for? I have inherited some code (shown below) and as far as I can see there is no reason why strUserName needs this. What is all for?
public static string strUserName
{
get { return m_globalVar; }
set { m_globalVar = value; }
}
Used later as:
GlobalClass.strUserName
Thanks
You get all the bugs of global state and none of the yucky direct variable access.
If you're going to do it, then your coder implemented it pretty well. He/She probably thought (correctly) that they would be free to swap out an implementation later.
Generally it's viewed as a bad idea since it makes it difficult to test the system as a whole the more globals you have in it.
My 2 cents.
When you want to use a static member of a type, you use it like ClassName.MemberName. If your code snippet is in the same class as the member you're referring (in this example, you're coding in a GlobalClass member, and using strUserName) you can omit the class name. Otherwise, it's required as the compiler wouldn't have any knowledge of what class you're referring to.
This is a common approach when dealing with Context in ASP.Net; however, the implementation would never use a single variable. So if this is a web app I could see this approach being used to indicate who the current user is (Although there are better ways to do this).
I use a simillar approach where I have a MembershipService.CurrentUser property which then pulls a user out from either SessionState or LogicalCallContext (if its a web or client app).
But in these cases these aren't global as they are scoped within narrow confines (Like the http session state).
One case where I have used a global like this would be if I have some data which is static and never changes, and is loaded from the DB (And there's not enough of the data to justify storing it in a cache). You could just store it in a static variable so you don;t have to go back to the DB.
One a side note why was the developer using Hungarian notation to name Properties? even when there was no intellisense and all the goodness our IDEs provide we never used hungarian notation on Properties.
#Jayne, #Josh, it's hard to tell - but the code in the question could also be a static accessor to a static field - somewhat different than #Josh's static helper example (where you use instance or context variables within your helper).
Static Helper methods are a good way to conveniently abstract stateless chunks of functionality. However in the example there is potential for the global variable to be stateful - Demeter's Law guides us that you should only play with state that you own or are given e.g. by parameters.
http://www.c2.com/cgi/wiki?LawOfDemeter
Given the rules there occasional times when it is necessary to break them. You should trade the risk of using global state (primarily the risk of creating state/concurrency bugs) vs. the necessity to use globals.
Well if you want a piece of data to be available to any other class running in the jvm then the Global Class is the way to go.
There are only two slight problems;
One. The implmentation shown is not thread safe. The set... method of any global class should be marked critical or wrapped in a mutex.
Even in the niave example above consider what happens if two threads run simultaniously:
set("Joe") and set("Frederick") could result in "Joederick" or "Fre" or some other permutation.
Two. It doesnt scale well. "Global" refers to a single jvm. A more complex runtime environment like Jboss could be runnning several inter communicating jvms. So the global userid could be 'Joe' or 'Frederick' depending on which jvm your EJB is scheduled.