I have a couple of class files in C#. I want to write a method that could be used in all the classes. For example, I am trying to write the method that returns the number of rows from the database table, and I need this in multiple times, so thought of writing a single method to share among all the classes. I thought it would be easy with the use of namespace. But when I add namespace in all the class files, it gives error stating "CONTROL NAME is not present in current context". From the internet search I came to the conclusion that I also need to add the namespace in xxx.designer.cs files. Is it correct? I tried to find the designer.cs files but could not, and in one of the solution it was stated that designer.cs file is created during compile time. If so how to add the namespace on designer.cs file.
Thank you!!!
You need to create a static class and this function that classes need to share has to be a static member.
This function can now be called from anywhere.
static class Helper
{
public static string Calculate(int myVariable)
{
//do some common calculation
}
//...
}
If these classes have common data members and you need to share a common function, you can consider using a base class. All common functionality and common data members would go into the base class, and by merit of inheriting that class, all your sub classes would be able to call this function.
Create a Static class and create static member functions into that. You need not to create instance of the class in this case and you can directly call member function using class name.
Related
I'm working on a big domain, for which maintainability is very important.
There are these general workers called ExcelHandlers that implement ExcelHandlerInterface (more on the interface in the ideas section) and basically get an UploadedFile as their input, upload them wherever they want and return the read data as an associative array. Now I have created this base class ExcelFileHandler which does all of these tasks for all excel files given two arguments:
1. The Directory to upload the file
2. the mapping of the excel columns to the indexes of the associative array.
Some ExcelHandlers might have to extend the ExcelFileHandler and do some more processing, in order to get the associative array of data.
The UploadedFile is always passed to the ExcelHandler from the controller.
Now here is the question. Given the generic structure of the ExcelFileHandler how should I define services for specific ExcelHandlers given that some only differ with the original one in the directory to upload the file and the mapping array.
My Ideas:
1. The first approach involves giving the directory and the mapping as the function arguments to ExcelHandleInterface::handle this will make the prototype something like handle(UploadedFile $file, array $mapping, $dir), $mapping and $dir are given to the function as arguments and passed to the handler by the controllers which has the parameters as constructor injections.
2.1 Defining the prototype of handle to be handle(UploadedFile $file), this would require the ExcelHandlers to have knowledge of $dir and $mapping. $dir will always be injected from the constructor.
2.1.1 Foreach individual ExcelHandler in the application, define a separate class e.g: UserExcelHandler, ProductExcelHandler, .... Which extend the ExcelFileHandler and leaves us again with two choices.
2.1.1.1 inject $mapping from outside. e.g:
// in the child class
public function __construct($dir, $mapping){
parent::__construct($dir, $mapping);
}
2.1.1.2 define $mapping in the constructor of the child class. e.g:
// in the child class
public function __construct($dir){
$mapping = array(0 => 'name', 1 => 'gender');
parent::__construct($dir, $mapping);
}
2.1.2 Not to create a class for each separate ExcelHandler and instead define the ExcelFileHandler as an abstract service and decorate with the right parameters to get the concrete ExcelHandler Service with the desired functionality, obviously ExcelHandlers with custom logic must be defined seperately, and to create a uniform code base, $mapping will always be injected from the Container in this case.
In your experience, what other paths can I take and which ones yield better results in the long term?
First of all, it seams as you've already put two separate things into one.
Uploading a file and reading it's contents are two separate concerns, which can change separately (like you said, $directory and $mapping can change case-by-case). Thus I would suggest to use separate services for uploading and reading the file.
See Single responsibility principle for more information.
Furthermore, due to very similar reasons, I would not recommend base classes at all - I'd prefer composition over inheritance.
Imagine that you have 2 methods in your base class: upload, which stores file to a local directory, and parse, which reads excel file and maps columns to some data structure.
If you need to store file in a remote storage (for example FTP), you need to override upload method. Let's call this service1.
If you need to parse file differently, for example combining data from 2 sheets, you need to override parse method. Let's call this service2.
If you need to override both of these methods, while still being able to get service1 and service2, you're stuck, as you'll need to copy-and-paste the code. There's no easy way to use already written functionality from (1) and (2).
In comparison, if you have interface with upload method and interface with parse method, you can inject those 2 separate services where you need them as you need them. You can mix any implementations of those already available. All of them are already tested and you do not need to write any code - just to configure the services.
One more thing to mention - there is absolutely no need to create (and name) classes by their usage. Name them by their behaviour. For example, if you have ExcelParser, which takes $mapping as an argument to a constructor, no need to call it UserExcelParser if the code itself has nothing to do with users. If you need to parse data from several sheets, just create SheetAwareExcelParser etc., not ProductExcelParser. This way you can reuse the code. Also correct naming lets understand the code more easily.
In practice, I've seen when function or class is named by it's usage, and then it's just used in another place with no renaming, refactoring etc. These cases are really not what you're looking for.
Service names (in another words concrete objects, not classes), can of course be named by their purpose. You just configure them with any required functionality (single vs separate sheets etc.)
To summarize, I would use 2.1.2 above all other of your given options. I would inject $dir and $mapping via DI in any case, as these do not change in runtime - these are configuration.
Im using Oracle, BlazeDS, Java & Flex. I have an ArrayCollection containing data from a small database table. This table won't be the subject of much change. I want to use this ArrayCollection accross different mxml files to fill e.g. ComboBoxes etc.
The reason for asking, is that doing a database call for each time a fill a ComboBox etc is slow and seems unnecessary. I tried doing this once in the "main" .mxml file, but then the variable wasn't accessible where i needed it.
What is the best approach for accomplishing this task? What is the best way of making a variable accesible across .mxml files? :)
[Bindable] public static var yourArrayCollection:ArrayCollection
That should make it visible anywhere but using static variables is normally not a good idea.
You could also implement a singleton instance to persist a variable if you do not want to make it static and need to reference other functions etc - but I think the static variable should do fine.
If this is a larger application, I'd recommend looking at Parsley: http://www.spicefactory.org/parsley/. With Parsley, you could add the array collection to the context and simply inject it whenever you need to reference it. The array collection should be populated during application startup and can be updated as needed.
There basically are two ways. The singleton way, and the static class way. A singleton is a class that is only instanciated once, through a mechanism described here, for instance. A static class is a bit different from a regular class : you will not instanciate it, first of all.
For more information about how implement a singleton in ActionScript 3 : here.
For more information about static classes and variables : here.
You can just make it public member of some class and import that class in all MXML-based classes:
public class DBWrapper {
[Bindable]
public var ItemList:ArrayCollection;
}
I usually make it a static member of a Globals class
public class Globals {
[Bindable] public var iCollection:ArrayCollection;
}
It can be accessed from anywhere in the program (provided you have assigned a valid ArrayCollection to it first)
combobox.dataProvider=Globals.iCollection;
Currently, if I have different classes containing functions etc, I would structure them all in the 1 VB file titled whatever the main Class is. For example:
MainClass.vb:
Class MainClass
Function FunctionA() as String
...
End Function
Class SubClass
Function SubFunction() as String
....
End Function
Class SubSubClass
......
End Class
End Class
End Class
However, the problem with this is the file can become 1000s of lines long making hard to find portions of code.
Is there a way I can store SubClass in a file such as MainClass.SubClass.vb so that its easier to locate classes? Or is there a better, more standard, way of doing this?
At least C# understands "partial classes" where you can spread the code over multiple files (within the same assembly)
EDIT
I expected VB to have partial classes also (I only work in C# myself), but as noted in the comments, it does have them.
In C# I could code something like this:
File MainClass.cs:
public partial class MainClass // note the "partial" keyword
{
// some method declarations etc.
}
File MainClass.SubClass.cs:
public partial class MainClass // have to repeat this to hook up correctly
// but an "Implements" or "Extends" could be different
{
// maybe some other methods
private class SubClass
{
// etc.
}
}
But the real question is: do those subclasses really need to be inner classes of that "MainClass", or could they be top-level classes themselves?
Instead of packaging all classes into 1 class you should use multiple classes and Namespaces to store and use your code. Especially with larger Projects this can help you organize your code.
Note: The name of a Namespace may not be the same as one of class. But you can use the same Namespace for multiple classes.
i.e.
Create a "MainClass.vb"
Create a "SubClass.vb"
Code "SubClass.vb"
Namespace Main
Public Class SubClass
Function SubFunction() as String
....
End Function
End Class
End Namespace
So you can access the Class SubClass by "Main.SubClass"
If you have a lot of classes and files you could i.e. create for each Namespace a SubFolder
Main
|-- SubMain
|---|-- SubSubMain
|-- AnotherSubMain
|---|-- SubAnotherSubMain
with the Namespaces
"Main"
"Main.SubMain"
"Main.SubMain.SubSubMain"
"Main.AnotherSubMain"
etc.
To store general functions which are often or commonly used you could also create a library project.
Yes, partial classes in vb.net will allow you to do exactly what you request.
MainClass.vb
Partial Class MainClass
Function FunctionA() as String
...
End Function
End Class
MainClass.SubClass.vb
Partial Class MainClass
Class SubClass
Function SubFunction() as String
....
End Function
End Class
End Class
Leaving aside questions of re-architecting and re-factoring, which is not the question you asked, with a very large class file, described as 1000s of lines long, there may be some additional quick-fix benefits in using even more partial class files to enact a separation of concerns. Use Partial to split the unwieldy class file into logically related bundles of code across multiple smaller .vb files.
How advisable, how effective, or how dirty, this action is is obviously debatable, but the facility does exist, and it would therefore be up to you to take a view on how beneficial/problematic this partitioning option may or may not prove to be.
http://en.wikipedia.org/wiki/Partial_class
I've got a class called ArtificialIntelligenceBase from which you can create your own artificial intelligence configuration sending some variables to the constructor or you can make a class that inherits from ArtificialIntelligenceBase and in the constructor of this new class just call the function super() with the parameters of the configurations.
I've also created some examples of artificial intelligences in classes, AIPassive, AIAgressive and AIDefensive. Obviously all of them inherits from ArtificialIntelligenceBase.
The point is that there're only few public functions in the base class. The variables in the base class are read only and the non public functions are protected in case you need to apply some modifications on them when created another pre-defined AI.
You can also create another AI just calling the base class sending some parameters in the constructor like this: new ArtificialIntelligenceBase(param1, param2, param3, param4);
I've tought about make the classes as a singleton because the classes can never change and once setted, their variables never change.
The question is: Is the singleton the best pattern to do this? Because I'm not sure.
PD: You don't need to explain any patter, just mention the name and I'll search for how it works
PPD: I'm developing in AS3. Just in case it helps
Thanks
In general, singletons are evil. I don't see any reason in your case to use a singleton, either. It sounds like you're using your own version of a factory method pattern (using a constructor somehow?) or maybe a prototype (I don't know AS3 one bit), but if you're looking for other patterns a couple of other ones are abstract factory and builder.
You don't need to use the singleton pattern to limit yourself to using only one instance per type of class, though. It doesn't help avoid redundancy.
Do anyone knows about the class which has the common function which we generally use while developing web application. I have no idea what you may call it, it may be the utility class or common function class. Just for reference, this class can have some common function like:
Generate Random number
Get the file path
Get the concatinated string
To check the string null or empty
Find controls
The idea is to have the collection of function which we generally use while developing asp.net application.
No idea what you are really asking, but there already are ready-made methods for the tasks you write in various library classes:
Random.Next() or RNGCryptoServiceProvider.GetBytes()
Path.GetDirectoryName()
String.Concat() or simply x + y
String.IsNullOrEmpty()
Control.FindControl()
Gotta love the intarwebs - An endless stream of people eager to criticize your style while completely failing to address the obvious "toy" question. ;)
Chris, you want to inherit all your individual page classes from a common base class, which itself inherits from Page. That will let you put all your shared functionality in a single place, without needing to duplicate it in every page.
In your example it looks like utility class - it is set of static functions.
But I think that you should group it in few different classes rather than put all methods in one class - you shouldn't mix UI functions(6) with string functions(3,4), IO functions (2) and math(1).
As Mormegil said - those functions exists in framework, but if you want to create your own implementations then I think that for part of your function the best solution is to create extension method.