|
It was marked as a joke because initially I was just going to post a crying face, joking that I was deeply offended by Ahmed's pure hatred for regions. Then I was curious, as I've never seen, nor thought to, separate a class into partials (except when using code generation, obviously).
Interesting, why are you so against partials?
|
|
|
|
|
I'm not per se against partials, but I do think the splitting of big classes into smaller pieces is an abuse of this otherwise great feature if the only intend is to get smaller code chunks.
In my opinion good/acceptable uses:
- Separation of generated and hand written code
- Separating the implementation of interfaces from "regular" class code especially when there are many interfaces to implement
- Splitting the implementation of a "big" class for disconnected teams (no access to a common source repository)
- Separate static stuff from instance stuff
Let me know your take on the usage scenarios.
Cheers!
|
|
|
|
|
Normally it would only be the first point you mentioned for working with code generation, but I like the idea of seperating out interface implementations! That's cool! Am I getting you right, so eg. An IList<t>, IEnumerable<t> (contrived):
Filename: MyList.IList.cs
public partial class MyList : IList<string> { ... }
Filename: MyList.IEnumerable.cs
public partial class MyList : IEnumerable<string> { ... }
Is this kind of what you mean (naming convention notwithstanding)?
Also, I think I may even adopt using partials for separating static and instance code. I normally use regions for that, but it still annoys me when I confuse them... Very interesting insight! Thank you, I'm glad I asked you that question
|
|
|
|
|
You got what I was trying to say even though I'm not sure if you can write it that way. My take on this would be that you would have to mention all the implemented interfaces in every partial class definition, but to be really sure I would need to try your take on this in a real example.
|
|
|
|
|
Because regions are horribly abused and the break the natural collapsing of methods that the IDE does, making it harder to read code.
Because people abuse regions to "break-up" a very large functions into smaller pieces. If it needs a f***ing region, then put that section of code into another method! and if there are so many methods that you need to region-ize them, then put them into a separate file (partial class)!
aaaaaggghh!
"If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams
|
|
|
|
|
So it's really about how you've seen them used? Ok, well I hardly ever use a region inside a method, I think that's a bit crazy. There is one exception to this - when there is horrific yet necessary code, I may "region it out" of a method saying "Ugly Code - DO NOT TOUCH" or something similar I think I've only committed this atrocity once...
I generally use regions to separate parts of the class, eg.
public class SomeClass : IUpdateable, IDrawable
{
#region Private fields
#region Constructor
#region Properties
#region Methods
#region Static methods
#region Event production
#region Event consumption
#region IUpdateable implementation
#region IDrawable implementation
}
It's usually pretty free-form my region-ising and its naming convention, but I tend to have the four: Private fields, Constructor, Properties and Methods in every class. For me it makes it easier when I go back to it to edit, for example, a method - I don't want to scroll or whatever, I just want to see the methods.
|
|
|
|
|
I've regioned some error-handling in some methods, but it's not a habit.
|
|
|
|
|
Class size doesn't really matter, well it sure isn't a primary concern. Object orientation should guide you. I'll assume it isn't a huge static class holding everything (as a VB module would).
My advice would be you ask yourself a number of questions:
1.
check the class name. Does it cover well everything inside the class? And would it be easy to come up with one or two new names that cover the content any better?
2.
check your "executive summary" comment, which is supposed to describe at a high level what your class is offering. Does it exceed 5 lines of text (excluding the petty details that aren't executive at all)? Does the text suggest a split somehow?
3.
look for inheritance. Are some parts of your class only relevant to some of its instances? If so, use inheritance.
4.
look for properties and methods that may be relevant to other objects, i.e. that would have (potential) value when applicable to other objects. If so, consider aggregation. See e.g. the decorator pattern.
5.
test yourself: without looking at the code, try and name all public properties and methods by heart. If you can't name half of them right away, you might be better of with a smaller class, if that were possible.
After looking at it from those different angles, I think you should know what to do (and if you don't, it tells you it doesn't really matter).
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
Size of the class doesn't make any problem and the partial classes are not used for making small chunks of code as well.
In fact partial classes are used to eliminate the readability problem.
and my argument is this one that when we create new window form in visual stdio so the class is divided into two parts. In one part of the class the declaration initialization of different controls are performed and the second part is given to the user to use those controls.
now think if we have both the things in one class then it will be difficult to manage.
thanks
|
|
|
|
|
I just realised that my mouse seems to automatically move into position ready to click "Good Answer" whenever I start to read one of your Answers. I wonder if my sub-conscience will ever be wrong...
return 5;
|
|
|
|
|
You can't hold me responsible for your actions, consciously nor otherwise. Just keep clicking whenever you feel an urge.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
Size doesn't matter... well, not directly anyway.
How many people are working on the project? I prefer to keep files small to reduce the need for multiple developers needing to modify the same file at the same time (an ounce of prevention is worth a pound of cure). The goal, then is to split it up into functional sections, and I do like partial classes. At the extreme (and I know extremes) you can have one method per file, but even I don't go that far (yet). The next thing is to put overloaded versions of one method in one file. And you can put similar methods (like operators) in one file. Basically, I'd say that it's better to have too many parts than too few.
Some of my "largest" classes are Data Access Layers -- all the methods that access tables in a particular database. Unfortunately, with many, I started writing them before partial classes were introduced so each is in one big file . More recent DALs I split into a section for each table. You could, instead, make a section for inserts, another for deletes, etc., but that doesn't seem right. It also doesn't seem right to develop separate classes for each table or action.
So if you have separate files for each table, you can assign Alice to work on Employee methods and Bob to work on Department methods, etc.
|
|
|
|
|
|
One of the goals of programming is clarity. Clarity facilitates software maintenance, and makes code more reliable since it's easier to spot errors. Another (sometimes contradictory) goal is efficiency.
So, if your class split improves clarity or efficiency, it could be the right thing to do.
One measure of clarity is the amount of interaction between the two split classes, called "coupling". If every method in one class depends on, and interacts with something in the other class, the classes are coupled, and this impairs clarity. E.g. to understand a method in one class, you constantly have to bring the other class up on the screen. This breaks your train of thought, and makes consequences of changes less clear.
If the two split classes are independent, with little coupling, splitting them is probably the right thing to do. Small classes are easier to work with than large classes, so this improves clarity.
|
|
|
|
|
If you think you need to ask the question about a class, it is probably time to refactor it.
I wasn't, now I am, then I won't be anymore.
|
|
|
|
|
I have recently posted about the AccessMemoryViolation issue on my WndProc when the usb device is being turned on (or hooked up). This part is solved and runs good.
Now the other thing is that I wonder if there is a way to send the message to WndProc during the startup (WM_CREATE) with the following Parameters:
Message: WM_DEVICECHANGE
WParam: DBT_DEVICEARRIVAL
LParam: DBT_DEVTYP_DEVICEINTERFACE
Code snippet:
----
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using HID_API_Library;
namespace USB_Box_Application
{
public partial class Form1 : Form
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int PostMessage(int hWnd, int msg, int wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(int hWnd, int msg, int wParam, IntPtr lParam);
int[,] deviceInfo = new int[1,2];
Device_Controller dc = new Device_Controller();
DeviceControl[] deviceControl = new DeviceControl[4];
IntPtr[] hwndProcess = new IntPtr[4];
public Point[] PanelLoc = new Point[4];
public Form1()
{
InitializeComponent();
dc.ParentHandle = this.Handle;
dc.RegisterHidNotification(this.Handle);
DisplayPanels();
this.label2.Text = this.Handle.ToInt32().ToString();
SendMessage(this.Handle.ToInt32(), HID_API.WM_DEVICECHANGE, HID_API.DBT_DEVICEARRIVAL, (IntPtr)HID_API.DBT_DEVTYP_DEVICEINTERFACE);
}
private void DisplayPanels()
{
PanelLoc[0] = new Point(0, 0);
PanelLoc[1] = new Point(205, 0);
PanelLoc[2] = new Point(0, 105);
PanelLoc[3] = new Point(205, 105);
for (int i = 0; i < 4; i++)
{
if (deviceControl[i] == null)
deviceControl[i] = new DeviceControl();
deviceControl[i].Location = PanelLoc[i];
try
{
deviceControl[i].DeviceHandle = dc.cbInfos[i].usbHandle;
deviceControl[i].DeviceBoxId = dc.cbInfos[i].boxID;
deviceControl[i].DeviceProductId = dc.cbInfos[i].productId;
deviceControl[i].DeviceVendorId = dc.cbInfos[i].vendorId;
deviceControl[i].DeviceConnected = true;
}
catch
{
deviceControl[i].DeviceHandle = -1;
deviceControl[i].DeviceBoxId = -1;
deviceControl[i].DeviceProductId = -1;
deviceControl[i].DeviceVendorId = -1;
deviceControl[i].DeviceConnected = false;
}
}
this.Controls.AddRange(deviceControl);
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x0001:
{
dc.RegisterHidNotification(this.Handle);
SendMessage(this.Handle.ToInt32(), HID_API.WM_DEVICECHANGE, HID_API.DBT_DEVICEARRIVAL, m.LParam);
break;
}
case HID_API.WM_DEVICECHANGE:
{
switch (m.WParam.ToInt32())
{
case HID_API.DBT_DEVICEARRIVAL:
{
OnDeviceChange(m);
break;
}
case HID_API.DBT_DEVICEREMOVECOMPLETE:
{
RemoveDevice(ref m);
break;
}
}
break;
}
}
base.WndProc(ref m);
}
void OnDeviceChange(Message m)
{
switch (m.WParam.ToInt32())
{
case HID_API.DBT_DEVICEARRIVAL:
{
DEV_BROADCAST_HDR hdr = (DEV_BROADCAST_HDR)m.GetLParam(typeof(DEV_BROADCAST_HDR));
if (hdr.dbch_devicetype == HID_API.DBT_DEVTYP_DEVICEINTERFACE)
{
DEV_BROADCAST_DEVICEINTERFACE1 dbd = (DEV_BROADCAST_DEVICEINTERFACE1)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_DEVICEINTERFACE1));
string usbDevice = new string(dbd.dbcc_name);
if (usbDevice.Contains("Vid_1238&Pid_5000"))
label2.Text = "USB Box Found!";
if (usbDevice.Contains("Vid_0483&Pid_0003"))
label2.Text = "Clear Box Found!";
SECURITY_ATTRIBUTES securityAttrib = new SECURITY_ATTRIBUTES();
int usbHandle = HID_API.CreateFile(usbDevice, HID_API.GENERIC_READ,
HID_API.FILE_SHARE_READ | HID_API.FILE_SHARE_WRITE,
ref securityAttrib,
HID_API.OPEN_EXISTING,
HID_API.FILE_FLAG_OVERLAPPED, 0);
if (usbDevice.Contains("Vid_1238&Pid_5000"))
MessageBox.Show(string.Format("{0}: {1} {2}", "USB Box Found", "Handle =", usbHandle));
if (usbDevice.Contains("Vid_0483&Pid_0003"))
MessageBox.Show(string.Format("{0}: {1} {2}", "Clear Box Found", "Handle =", usbHandle));
}
break;
}
}
}
|
|
|
|
|
Hi again,
1.
your code still is not correct, you're still sending a phony pointer in your Form's constructor.
2.
why would you want to send it earlier than you are already doing? if you must, you could send it from inside the static Main method, however it would not get processed by your Form yet, as it does not exist yet.
BTW: you could work without the SendMessage, just trick your WndProc so that it mimics the receipt of whatever it is you want the first time it is called...
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
This "sendmessage" is an example... i know that this line has phony pointer.
How do I trick WndProc that it would mimic the receipt for the first time it is called?
|
|
|
|
|
Elementary:
bool firstMessage=true;
override WndProc(...) {
if (firstMessage) {
firstMessage=false;
...
}
...
}
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
i'm developing a simple socket application for server client architecture. it works fine when the
pc is having a static it , but when the pc is obtaining Ips automatically means when the radio button for
"obtain an ip autmatically" , it gives the exception saying this ip is not valid in the context ,
any idea to address this situation.
thanx in advance.
|
|
|
|
|
Can you use machine name instead of IP address. As you indicated the IP address can be changed when it is using dynamic IP setting, where as the machine name stays the same.
|
|
|
|
|
Which IP address are you referring to here, the local or remote? If it is the remote address then you need to verify that it is consistent with the actual address in use by the remote machine. Perhaps if you show an extract of your code, and what results you are seeing, we can offer some further suggestions.
I must get a clever new signature for 2011.
|
|
|
|
|
thanx for all of you ..!
and this is the code segment i use.
localIP = Dns.GetHostAddresses(Dns.GetHostName())[0];
IPEndPoint localEndpoint = new IPEndPoint(localIP, 7575);
lSoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
lSoc.Bind(localEndpoint);
lSoc.Listen(10);
|
|
|
|
|
You need to go through this code with your debugger and see exactly what values are being returned for the IP address.
I must get a clever new signature for 2011.
|
|
|
|
|
In a client server architecture the 'server' IP is traditionally fixed. Not dynamic.
In a client server architecture the client connects to the server.
If the server IP is not fixed then one must use another mechanism which will require some other server to get the current IP. Host name resolution is one method to do that. It does however require that the host name is being managed by a DNS server.
|
|
|
|
|