I need a bit of a architecture help, I think what I've been doing may not necessarily be the best approach.
Things to note:
This is not an android specific question.
Android does however require that I need to serialise objects across 'screens'.
Consider the following:
I'm currently working on a game for android where a character class needs to be passed between different screens. In order to do this I need to serialise the objects. Taking into account that are different types of characters that will be needed I'd like to create a class that inherits for each of these. Where I have static characters I'd like to inherit from the Character class and set the defaults such as 'Name', and 'Description' within the constructor.
Current implementation:
I'm passing the serialised sub class objects around. ( Eg: UserCharacter with a base of Character ) Ideal situation would for me to be able to deserialise the object as it's base class however that doesn't seem to me work. The only working solution I have for this at the moment is by doing the following when trying to do serialise:
new XmlSerializer(typeof (Character, new [] { typeof(CharacterUser)}));
This allows me to pass in multiple sub types. This however is not feasible in the long term as it just means code duplication across my application as well as everytime a new character sub class is created I need to add at it any point I would need to deserialise. I'd rather have the code written and working where I leave it to do it's own thing. I'm sure you can understand that.
Another thing I've tried is to do is use IXmlSerializable on the character object and deal with the Reading and Writing independantly. I think that this however requires implementation of a list to work correctly? Currently my ReadXml never gets called. (Great idea, but it's not worked for me so far)
Anyone got any ideas I could try?
I think it's quite an open question, please let me know if I need to scope a little differently.
Related
I have a question regarding the structure of my code and how to keep classes simple. I am working on simplifying the service layer of a C# project. Much of the code has not taken into account OOP practices and there are few classes with methods over 200 lines. I have begun to extract out smaller methods but have a quick query regarding how to do this.
As an example, i have a method that retrieves file directories that are specific to a customer, then checks to see if they exist, creates them if they don't and finally returns an object with a list of these directories. I want to stick to the principle of not having private methods and extract out into new classes though traditional i would have created private methods for checking if directories exist, another for creating them, a third for retrieving the folder names and returning the object and a public method to call all of these in order with an associated interface with a single method.
Should i be creating new classes for each of these private methods and if so would they all need an interface? or perhaps keep them all public and call them from elsewhere?
Thanks in advance!
Short answer: you should do neither of those things.
If you want to approach the problem from an object-oriented perspective, forget for a while what the methods are doing. Think about what the code is about. You only mentioned "Customer" as a possible "business" relevant thing. Try to come up with other business relevant things. What are those files? Reports? ActivityLogs? Messages? CreditReports :) ?
The point is, object-orientation is not about just having methods in different classes. The classes and the methods must have some business meaning. If they don't mean anything, then there is no real reason to have them in the first place!
From that it is also clear that "StorageManager", "StorageUtil", and things like that shouldn't exist, because it doesn't have any business meaning at all.
So start with finding out what the application is about (the things), and then you can move certain responsibilities to the appropriate thing.
I wanted to pass a Class Object from one activity to another in Xamarin.Android app.
I can pass the simple strings using Intent.PutExtra method.
Does anybody know about it. anyhelp is appreciated :)
Just adding in case someone else comes across this. The nice thing about Xamarin/.NET is how easy it is to use JSON. You can Serialize your data to a string and pass that through the Extras.
JSON.NET is a nice library (that you can find on the Xamarin component store) for this and there is also some built in JSON classes in .NET. An example using JSON.NET would be like this.
Intent i = new Intent(Application.Context, typeof(SecondActivity));
i.PutExtra("key", JsonConvert.SerializeObject(myObject));
StartActivity(i);
And in the other Activity you can deserialize it.
var obj = JsonConvert.DeserializeObject<OBJ_TYPE>(Intent.GetStringExtra("key"));
This is better than using a static reference in my opinion.
The concept is the same as with a standard (non-Xamarin) application.
You can use Intent#putExtra(String, Parcelable) to pass any object that implements the Parcelable interface as an extra.
The Parcelable interface is a little bit complex, so be sure to read the documentation to ensure that your class conforms to the requirements. You may also want to check out this SO question for more information on creating a Parcelable class.
You cannot pass an object reference via an Intent. This is because Activities are designed to work completely independently of each other. Users can throw your Activity in the background while performing other tasks, so it is entirely possible (and very likely) that your Activity's variables will be garbage collected. When the user later comes back to your Activity, it should be able to recreate its state.
If you really need to pass a reference to an object directly, you can do so by making that object a static variable. While this is a quick and dirty way to solve the problem of getting data from one Activity to another, it does not solve the problem of the variable potentially being garbage collected at some point, and is generally a poor design choice.
I'm trying to code an HTML parser in C#. I need to get data from, let's say, 10 gambling website. I'm trying to figure out what is the best approach.
At first, I thought to write one big function that parse all of the websites with a switch statement, but I believe it's an overkill. It will be too long. I use HTML agility pack, so each implementation will have similar and yet different structure.
What is the best way to implement such a structure?
Make a base class with the common parts and create a sub-class for each different parser. The functions that change from parser to parser can be declared as abstract so they have to be overridden in the different sub-classes.
You could implement a strategy pattern, it would be something along the lines of having an Abstract class (perhaps with some shared methods) that each Concrete class implements and overrides the Abstract method. Using a Factory method you could then select the appropriate Concrete class to call for parsing the HTML (perhaps depending on the Site URL or some configuration).
There are lots of ways to go with that. Being a start simple guy, I'be be implementing one website / parser combination.
Then looking at what was common.
They all have a url.
They will all have some Parse thingy
And presumably you want to extract the same sort of information from each one.
And then you want to do something with that info.
That suggests a website class
A class to navigate through the website and get the page(s)
A parsing class
A parsing information class.
You could use inheritance, though my first thought was an interface.
Either way you should end up a with a collection of websites to parse, each one described by it's own instance.
From there you could simply do a foreach, you could schedule, you could do them in parallel. More to the point you could add and remove targets, keep going on the others when one of them twiddles with their site, or goes down...
Prove your idea with one site, your infrastructure with two, and batter away at the others, while having deployed something that works and see if anything happens in the real world that you hadn't thought of.
Big bangs are for making universes, not applications.
The answer to just about every single question about using C# with JSON seems to be "use JSON.NET", but that's not the answer I'm looking for.
The reason I say that is, from everything I've been able to read in the documentation, JSON.NET is basically just a better performing version of the DataContractSerializer built into the .NET framework...
Which means if I want to deserialize a JSON string, I have to define the full, strongly-typed class for EVERY request I might have. So if I have a need to get categories, posts, authors, tags, etc., I have to define a new class for every one of these things.
This is fine if I built the client and know exactly what the fields are, but I'm using someone else's API, so I have no idea what the contract is unless I download a sample response string and create the class manually from the JSON string.
Is that the only way it's done? Is there not a way to have it create a kind of hashtable that can be read with json["propertyname"]?
Finally, if I do have to build the classes myself, what happens when the API changes and they don't tell me (as twitter seems to be notorious for doing)? I'm guessing my entire project will break until I go in and update the object properties...
So what exactly is the general workflow when working with JSON? And by general I mean library-agnostic. I want to know how it's done in general, not specifically to a target library...
It is very hard to be library-agnostic as you request because how you work with json really depends on the library you use. As an example inside JSON.NET there are multiple ways you could work with JSON. There is the method you talk about with direct serialization into objects. That is type safe but will break if the data from your API changes. However, there is also a LINQ-to-JSON that provides a JObject (which behaves fairly similarly to XElement) that provides a way to do JObject["key"] as you requested in your question. If you are really just looking for a flexible way to work with JSON inside C#, then check out JSON.NET's LINQ-to-JSON.
In reality no matter how you do it, if the API changes your code is likely to break. Even if you are just strictly a hashtable-based approach, your code will still be likely to break if the data coming back changes.
Edit
JSON.NET Documentation
Examples
If you check out the examples, the second one should give you a good example of how LINQ-to-JSON works. It allows you to work with it without defining any classes. Everything gets converted to standard framework classes (mostly collections and strings). This avoids the need to maintain classes.
I've been a Perl developer for over a decade, and I've just recently started to work in C#. I'm surprised by how much I like it (I don't like Java at all) but one of the most difficult cognitive switches is going from "Everything can be treated as a string and the language takes care of conversions" to "Pre-define your types." In this case string-thinking might be an advantage, because it's what you need to do for the kind of API you're asking for.
You need to write a JSON parser that understands the syntax, which is fairly simple: comma-separated lists, key/value pairs, {} for hashes/objects, [] for arrays, and quoting/escaping constructs. You'll want to create a Hashtable to start because the top-level entity in JSON is always an object, then scan the JSON string character-by-character. Pull out key/value pairs; if the value starts with { then add it as a new Hashtable, if it starts with [ add it as a new ArrayList, otherwise add it as a string. If you get { or [ you'll need to recursively descend to add the child data elements.
If .NET has a good recursive descent parser, you could probably use that to make the job simpler or more robust, but JSON is simple enough to make this a good and reasonably completable exercise.
Never sure where to place functions like:
String PrettyPhone( String phoneNumber ) // return formatted (999) 999-9999
String EscapeInput( String inputString ) // gets rid of SQL-escapes like '
I create a Toolbox class for each application that serves as a repository for functions that don't neatly fit into another class. I've read that such classes are bad programming practice, specifically bad Object Oriented Design. However, said references seem more the opinion of individual designers and developers more than an over-arching consensus. So my question is, Is a catch-all Toolbox a poor design pattern? If so, why, and what alternative is there?
Great question. I always find that any sufficiently complex project require "utility" classes. I think this is simply because the nature of object-oriented programming forces us to place things in a neatly structured hierarchical taxonomy, when this isn't always feasible or appropriate (e.g. try creating an object model for mammals, and then squeeze the platypus in). This is the problem which motivates work into aspect oriented programming (c.f. cross cutting concern). Often what goes into a utility class are things that are cross-cutting concerns.
One alternative to using toolbox or utility classes, are to use extension methods to provide additional needed functionality to primitive types. However, the jury is still out on whether or not that constitutes good software design.
My final word on the subject is: go with it if you need, just make sure that you aren't short-cutting better designs. Of course, you can always refactor later on if you need to.
I think a static helper class is the first thing that comes to mind. It is so common that some even refer to it as part of the object-oriented design. However, the biggest problem with helper classes is that they tend to become a large dump. I think i saw this happen on a few of the larger projects i was involved in. You're working on a class and don't know where to stick this and that function so you put it in your helper class. At which point your helpers don't communicate well what they do. The name 'helper' or 'util' itself in the class name doesn't mean anything. I think nearly all OO gurus advocate against helpers since you can very easily replace them with more descriptive classes if you give it enough thought. I tend to agree with this approach as I believe that helpers violate the single responsibility principle. Honestly, take this with a grain of salt. I'm a little opinionated on OOP :)
In these examples I would be more inclined to extend String:
class PhoneNumber extends String
{
public override string ToString()
{
// return (999) 999-9999
}
}
If you write down all the places you need these functions you can figure out what actually uses it and then add it to the appropriate class. That can sometimes be difficult but still something you should aim for.
EDIT:
As pointed out below, you cannot override String in C#. The point I was trying to make is that this operation is made on a phone number so that is where the function belongs:
interface PhoneNumber
{
string Formatted();
}
If you have different formats you can interchange implementations of PhoneNumber without littering your code with if statements, e.g.,
Instead of:
if(country == Countries.UK) output = Toolbox.PhoneNumberUK(phoneNumber);
else ph = Toolbox.PhoneNumberUS(phoneNumber);
You can just use:
output = phoneNumber.Formatted();
There is nothing wrong with this. One thing is try to break it up into logical parts. By doing this you can keep your intellisense clean.
MyCore.Extensions.Formatting.People
MyCore.Extensions.Formatting.Xml
MyCore.Extensions.Formatting.Html
My experience has been that utility functions seldom occur in isolation. If you need a method for formatting telephone numbers, then you will also need one for validating phone numbers, and parsing phone numbers. Following the YAGNI principle, you certainly wouldn't want to write such things until they're actually needed, but I think it's helpful to just go ahead and separate such functionality into individual classes. The growth of those classes from single methods into minor subsystems will then happen naturally over time. I have found this to be the easiest way to keep the code organized, understandable, and maintainable over the long term.
When I create an application, I typically create a static class that contains static methods and properties that I can't figure out where to put anywhere else.
It's not an especially good design, but that's sort of the point: it gives me a place to localize a whole class of design decisions that I haven't thought out yet. Generally as the application grows and is refined through refactoring, it becomes clearer where these methods and properties actually ought to reside. Mercifully, the state of refactoring tools is such that those changes are usually not exceptionally painful to make.
I've tried doing it the other way, but the other way is basically implementing an object model before I know enough about my application to design the object model properly. If I do that, I spend a fair amount of time and energy coming up with a mediocre solution that I have to revisit and rebuild from the ground up at some point in the future. Well, okay, if I know I'm going to be refactoring this code, how about I skip the step of designing and building the unnecessarily complicated classes that don't really work?
For instance, I've built an application that is being used by multiple customers. I figured out pretty early on that I needed to have a way of separating out methods that need to work differently for different customers. I built a static utility method that I could call at any point in the program where I needed to call a customized method, and stuck it in my static class.
This worked fine for months. But there came a point at which it was just beginning to look ugly. And so I decided to refactor it out into its own class. And as I went through my code looking at all the places where this method was being called, it became extremely clear that all of the customized methods really needed to be members of an abstract class, the customers' assemblies needed to contain a single derived class that implements all of the abstract methods, and then the program just needed to get the name of the assembly and the namespace out of its configuration and create an instance of the custom features class at startup. It was really simple for me to find all of the methods that had to be customized, since all I needed to do was find every place that my load-a-custom-feature method was being called. It took me the better part of an afternoon to go through the entire codebase and rationalize this design, and the end result is really flexible and robust and solves the right problem.
The thing is, when I first implemented that method (actually it was three or four interrelated methods), I recognized that it wasn't the right answer. But I didn't know enough to decide what the right answer was. So I went with the simplest wrong answer until the right answer became clear.
I think the reason it's frowned upon is because the "toolbox" can grow and you will be loading a ton of resources every time you want to call a single function.
It's also more elegant to have the methods that apply to the objects in the actual class - just makes more sense.
That being said, I personally don't think it's a problem, but would avoid it simply for the reasons above.
I posted a comment, but thought I'd elaborate a bit more.
What I do is create a Common library with namespaces: [Organisation].[Product].Common as the root and a sub namespace Helpers.
A few people on here mention things like creating a class and shoving some stuff they don't know where else to put in there. Wrong. I'd say, even if you need one helper method, it is related to something, so create a properly named (IoHelper, StringHelper, etc.) static helper class and put it in the Helpers namespace. That way, you get some structure and you get some sort of separation of concerns.
In the root namespace, you can use instance utility classes that do require state (they exist!). And needless to say also use an appropriate class name, but don't suffix with Helper.