Utility class or Common class in asp.net - asp.net

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.

Related

Defining and implementing interfaces in R

I'm interested in defining and inheriting from interfaces in R. By interface, I mean OOP interfaces. I know R supports class extension. This link http://adv-r.had.co.nz/OO-essentials.html gives an example of extending a reference class in R. It defines a NoOverdraftAccount reference class that extends an Account reference class.
Instead of extending the Account reference class, I'd like to be able to define an account interface, IAccount. I would like I'd like NoOverDraftAccount to implement IAccount, such that:
NoOverDraftAccount must implement all methods in IAccount.
NoOverDraftAccount cannot declare any new public methods not already declared in IAccount.
NoOverDraftAccountcan declare private methods and properties.
What's the best way to achieve this?
The closest I've come to an answer was from the question Multiple inheritance for R6 classes. But, the question wasn't focused on interfaces.
Thanks for your time.
I don't think "declarations" make much sense in an interpreted language like R. As there's no compile step there's no way to test if something actually conforms to a declared interface without running a function on the class, something like does_class_follow(class,interface), at some point.
So I think you have to start from scratch - you need to define an interface specification class and write the does_class_follow function.
My first thought was that a class would have to know what interface(s) it conformed to so that the test could introspect this, but perhaps that's wrong and you should have a file of interface definitions and pseudo-declarations that tested everything.
For example, have some file interfaces.R that looks like:
IAccount = Interface(
public = list("deposit","withdraw")
)
Implements(Account, IAccount)
Implements(Account, NoOverDraftAccount)
Then when the package is loaded those Implements functions would run and test the classes against that specification of what an Account interface is. Whether its better to test at load time or to put these sort of things in the ./test/ folder and test them at test time using test_that or another test system is a question...
As you may be aware you'll have to implement this separately for all the OO systems in R that you want to use - S3, S4, R5, ReferenceClasses, R6, proto, R.oo and all the other ones I've forgotten...

Enum naming to avoid name clashes

I'm trying to standardise the way I name things, but as a newbie I always seem to come up with an issue somewhere further down the line.
Case in point - I have a user control and enum that clash. The UC is very specific and contains a form dropdownlist/validation for customer input - the name relates to the type of input so the class is named EmploymentStatus.
However, the dropdownlist is populated via an enum - ideally this would be called EmploymentStatus too as I've adopted the recommended singular form for enums.
No doubt everyone has come across this issue at some point, but what is a good solution?
I think namespaces would be the way to go here. Just put the enum in a separate namespace then refer to fully qualified e.g.
MyCompany.MyApplication.AnotherNamespacePart.EmploymentStatus
If this is a bit verbose then you can use namespace aliases to make things a bit more readable.
using myEnum = MyCompany.MyApplication.AnotherNamespacePart;
... some code
myEnum.EmploymentStatus
Please note I've assumed C# here but the principle will hold for other asp.net languages
In my humble opinion and all that

Understanding the use of Interfaces and Base Classes

I know there are a number of post out there on Interfaces and Base classes, but I'm having a hard time getting the correct design pattern understanding.
If I were to write a reporting class, my initial though would be to create an interface with the core properties, methods, etc. that all reports will implement.
For example:
Public Interface IReportSales
Property Sales() As List(Of Sales)
Property ItemTotalSales() As Decimal
End Interface
Public Interface IReportProducts
Property Productss() As List(Of Inventory)
Property ProductsTotal() As Decimal
End Interface
Then I assume I would have a class to implement the interface:
Public Class MyReport
Implements IReportSales
Public Property Sales() As System.Collections.Generic.List(Of Decimal) Implements IReportItem.Sales
Get
Return Sales
End Get
Set(ByVal value As System.Collections.Generic.List(Of Decimal))
Items = value
End Set
End Property
Public Function ItemTotalSales() As Decimal Implements IReport.ItemTotalSales
Dim total As Decimal = 0.0
For Each item In Me.Sales
total = total + item
Next
End Function
End Class
My thought was that it should be an interface because other reports may not use "Items", this way I can implement the objects that are used for a given report class.
Am I way off? should I have still have just created a base class? My logic behind not creating a base class was that not all report classes may use "Items" so I didn't want to define them where they are not being used.
To attempt to answer you question, abstract classes are used to provide a common ancestor for related classes. An example of this in the .Net API is TextWriter. This class provides a common ancestor all various classes whose purpose is to write text in some fashion.
Interfaces are more properly used to act as adapters for different objects that don't belong in the same "family" of objects but have similar capabilities. A good example of this can be seen with the various collections in the .Net API.
For example, the List and Dictionary classes provide the ability for you to manage a collection of objects. They do not share a common ancestor by inheritance, this wouldn't make sense. In order to allow easy interop between them though, they implement some of the same interfaces.
Both classes implement IEnumerable. This cleanly allows you use objects of either type List or Dictionary as an operand for anything that requires an IEnumerable. How wonderful!
So now in your case in designing new software you want to think about how this would fit into your problem space. If you give these classes a common ancestor via inheritance of an abstract class you have to be sure that all the items that inherit from it are truly of the base type. (A StreamWriter is a TextWriter, for example). Inappropriate use of class inheritance can make your API very difficult to build and modify in the future.
Let's say you make an abstract class, ReportBase, for your repots. It may contain a few very generic methods that all reports simply must have. Perhaps it simply specifies the method Run()
You then only have one type of report you want to make so you define a concrete Report class that inherits from ReportBase. Everything is great. Then you find out you need to add several more types of reports, XReport, YReport, and ZReport for sake of example. It doesn't really matter what they are, but they work differently and have different requirements. All of the reports generate pretty HTML output and everyone is happy.
Next week your client says they want XReport and YReport to be able to output PDF documents as well. Now there are many ways to solve this, but obviously adding an OutputPdf method to your abstract class is a poor idea, as some of those reports shouldn't or can't support this behavior!
Now this is where interfaces could be useful to you. Let's say you define a few interfaces IHtmlReport and IPdfReport. Now the report classes that are supposed to support these various output types can implement those interfaces. This will then let you create a function such as CreatePdfReports(IEnumerable<IPdfReport> reports) that can take all reports that implement IPdfReport and do whatever it needs to do with them without caring what the appropriate base type is.
Hopefully this helps, I was kind of shooting from the hip here as I'm not familiar with the problem you're trying to solve.
Yes, if you don't know how many reports are not going to use Items , you can go for Abastract class.
Another good thought follows:
You can also create both Interface and Abstract class
Define Sales in Interface , create two abstract classes , one for Reports that implement both and another for Report not implementing Sales. Implement interface for both
define both method (implement sales) in first and only implement sales in second.
Give appropriate names to both Abstract classes e.g. ReportWithItemsBase or ReportWithoutItemsBase.
This way you can also achieve self explaining named base classes on deriving Report classes as well.

Should I use a singleton class that inherits from an instantiable class or there's another better pattern?

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.

One file per function...really?

I am relatively new to Flex/ActionScript, but I have been using a pattern of creating one file per function in my util package - with the name of the file being the same as the name of the function. Like if the file was convertTime.as:
package util{
public function convertTime(s:String):Date{
...
}
}
This way I can import the function readily by doing:
import util.convertTime;
...
convertTime(...);
I like this way better than importing a class object and then calling the static methods hanging off of it, like this:
import util.Util;
...
Util.convertTime(...);
But, the more I do this, the more files I'll end up with, and it also seems a bit wasteful/silly to put only one function into a file, especially when the function is small. Is there another alternative to this? Or are these two options the only ones I have?
Update: after some research, I've also posted my own answer below.
Yes, these are your two main options for utility libraries. We actually use both of these approaches for our generic utility functions. For a very small set of functions that we feel should actually be builtins (such as map()), we put one function per file, so that we can use the function directly.
For more obscure/specialized utility functions, we don't want to pollute our global namespace so we make them static functions on a utility class. This way, we're sure that when someone references ArrayUtils.intersect(), we know what library intersect() came from, and what roughly it's for (it intersects two arrays).
I would recommend going with the latter route as much as possible, unless you have a function that a) you use very frequently and b) is really obvious what it does at a glance.
I came across some other alternatives after all and thought I'd share them here.
Alternative 1 - use inheritence
This is probably an obvious answer, but is limited. You would put your static methods into a parent class, inherit them to get them in the subclasses. This would only work with classes. Also, because ActionScript is single inheritence, you can only inherit once.
Alternative 2 - Alias the methods
You still write utility functions as static methods hanging off util classes, but you alias them so you can access them with a shorter name, ex:
import mx.binding.utils.BindingUtils;
var bind:Function = BindingUtils.bindProperty;
Now you can just call
bind(...);
rather than than the lengthy
BindingUtils.bindProperty(...);
You can do this within the class scope and the function scope, but not the package scope - because apparently you can only have one visible attribute inside a package. If you do this in the class scope, you will want to make sure it doesn't conflict with your other class attribute names.
Alternative 3 - use include
As described in this flexonrails blog post you can use include to simulate a mixin in ActionScript. An include is different from an import in that all it's doing is copying the entirety of the file you are including from and paste it into the place you are including it at. So, it has completely no handling of namespace issues, you can not reference its full path name afterwards like you can with imports, if you have conflicting names, you are on your own with this. Also unlike import, it creates different copies of the same code. But what you can do with this is put any number of functions in a file, and include them into class or function scope in another file. Ex:
// util/time_utils.as
function convertTime(..){
...
}
function convertDate(..){
...
}
To include:
include 'util/time_util.as'; // this is always a relative path
...
convertTime(...);
# an0nym0usc0ward
OOP is simply the method of consolidating like functions or properties into an object that can be imported and used. It is nothing more that a form of organization for your code, ALL code executes procedurally in the processor in the end, OOP is just organization of sources. What he is doing here may not be OOP as you learn from a book, but it does the exact same thing in the end, and should be treated with the same respect.
Anyone that truly understands OOP wouldn't be naive enough to think that the approved and documented form of OOP is the only possible way to object orient your code.
EDIT: This was supposed to be a comment response to an0nym0usc0ward's rude comment telling him to learn OOP. But I guess I typed it in the wrong box :)

Resources