TEdit property variable delphi - validation

I have a form in Delphi including several TEdit boxes. I would like a way to check the validation all of the boxes kind of, currently I would have to have a boolean variable assigned to each TEdit. e.g.
Var
TEdit1Valid:boolean;
TEdit2Valid:boolean;
etc, etc for every TEdit on the form.
For the first method it would have to look something like this:
If TEdit1Valid then
ShowMessage('Your', Edit1.Name, 'is invalid');
etc, etc for each TEdit box.
This creates many variables and I was just wondering if there is a better way to do it. One idea I had is to assign a property called Valid to a TEdit, but I don't know how to do this. With this method I could then write an array of TEdits for each TEdit and execute the following
for I := 1 to High(EditList) do
begin
if EditList[I].Valid = false then
ShowMessage('Your ', EditList[I].Name, 'is invalid');
end
This is just an example bit of rough code that I just wrote and could use along with other things I could do iteratively like this.
So could someone either suggest a good method of doing this or show me how to do the afore mentioned method.

How about using the OnExit event handler on the TEdit controls? For example:
procedure TForm1.Edit1Exit(Sender: TObject);
begin
with Sender as TEdit do
begin
if not IsValidEdit(Text) then
ShowMessage('Your ' + Name + ' is invalid');
end;
end;
Then apply that same OnExit event to all your TEdit controls. This example "IsValidEdit" function that I used above can validate the Text values of your TEdit, or you could just put your validation code within the OnExit event (but it would be "cleaner", in my opinion, to use a specific function to validate).
function IsValidEdit(const AValue: string): boolean;
begin
if Length(AValue) < 5 then // not valid if length less than 5
Result := False
else
Result := True;
end;

You can use the Tag property. It an integer rather than a boolean. According to the Embarcadero help -
Tag has no predefined meaning. The Tag property is provided for the
convenience of developers. It can be used for storing an additional
integer value or it can be typecast to any 32-bit value such as a
component reference or a pointer.

OnExit is good for individual field validations, and is useful when you don't want the user to leave the field empty or with an improper value. It's not advisable for overall form validation, although it works.
For form validation, you're better off creating a method (eg., Validate) that's called in the OnClose handler, and if it fails, show a message, position the cursor on the field in question, then set Action := caNone, which will prevent the form from closing.

Related

"That name is not valid" for my VBA function in Excel/Mac

A simple VBA function. When I try to use it in my worksheet, all I get, no matter what I do, is "That name is not valid". I'm out of ideas.
Sub FindABV(temperature)
With Worksheets("Sheet1")
.Range("C28").GoalSeek _
Goal:=temperature, _
ChangingCell:=.Range("B28")
End With
FindABV = .Range("B28").Value
End Sub
I've tried creating a new Module to put it in. No change.
And no error indications from the code editor.
The Sub procedure performs a task and then returns control to the calling code, but it does not return a value to the calling code.
See more here.
This said, you cannot set a procedure equal to something:
FindABV = .Range("B28").Value
because that name is not valid (you cannot say that a procedure is equal to a certain value, it doesn't make sense). You probably wanted to use a Function to return the value of that cell calculated by the Goal Seeker depending on the input temperature that you pass by the function:
Function FindABV(temperature)
With Worksheets("Sheet1")
.Range("C28").GoalSeek _
Goal:=temperature, _
ChangingCell:=.Range("B28")
End With
FindABV = .Range("B28").Value '<-- return the value
End Function
However, be careful: if =FindABV(temperature) lies on Sheet1.Range("B28"), you will have a circular reference because your function will try to have the value of itself.
Your code will not deliver the results you want. If you want to have the Function work for different values than the ones stored in B28 and C28 you'll have to write it more like this:
Public Function FindABV(goalCell As Range, changeCell As Range, temperature As Double)
goalCell.GoalSeek Goal:=temperature, ChangingCell:=changeCell
FindABV = changeCell
End Function
But this doesn't matter in any case because GoalSeek actually changes the value in the ChangingCell which Excel will not do if it is called from within a Function.

IS there reflection in Oracle Forms 6 or later?

IS there reflection in Oracle Forms 6 or later?
Is it possible to enumarate labels or other elements?
Forms is an old and venerable programming language, and it doesn't support full-on reflection, Java style. However, it does have a complement of GET and SET functions which enable us to interrogate and manipulate a Form's metadata.
So we can step through the items of a block and get their labels using GET_ITEM_PROPERTY like this (example adapted from the documentation):
DECLARE
cur_itm VARCHAR2(80);
cur_block VARCHAR2(80) := :System.Cursor_Block;
cur_label VARCHAR2(120);
BEGIN
cur_itm := Get_Block_Property( cur_block, FIRST_ITEM );
WHILE ( cur_itm IS NOT NULL ) LOOP
cur_itm := cur_block||’.’||cur_itm;
cur_label := Get_Item_Property( cur_itm, LABEL);
-- do whatever you want with the label here
cur_itm := Get_Item_Property( cur_itm, NEXTITEM );
END LOOP;
END;
You could change the LABEL of the current item using SET_ITEM_PROPERTY.
Note: LABEL is a property which only applies to certain items (buttons, checkboxes, etc) so you might what to include a test for the item type and perhaps grab the PROMPT_TEXT instead, if that's appropriate.
There are loads of ways we can change the appearance and behaviour of a Form on the fly. The Form Builder Reference covers all the built-ins, so there's no point in recapitulating it here. Find out more.

Delphi Interface Performance Issue

I have done some really serious refactoring of my text editor. Now there is much less code, and it is much easier to extend the component. I made rather heavy use of OO design, such as abstract classes and interfaces. However, I have noticed a few losses when it comes to performance. The issue is about reading a very large array of records. It is fast when everything happens inside the same object, but slow when done via an interface. I have made the tinyest program to illustrate the details:
unit Unit3;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
const
N = 10000000;
type
TRecord = record
Val1, Val2, Val3, Val4: integer;
end;
TArrayOfRecord = array of TRecord;
IMyInterface = interface
['{C0070757-2376-4A5B-AA4D-CA7EB058501A}']
function GetArray: TArrayOfRecord;
property Arr: TArrayOfRecord read GetArray;
end;
TMyObject = class(TComponent, IMyInterface)
protected
FArr: TArrayOfRecord;
public
procedure InitArr;
function GetArray: TArrayOfRecord;
end;
TForm3 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
MyObject: TMyObject;
implementation
{$R *.dfm}
procedure TForm3.FormCreate(Sender: TObject);
var
i: Integer;
v1, v2, f: Int64;
MyInterface: IMyInterface;
begin
MyObject := TMyObject.Create(Self);
try
MyObject.InitArr;
if not MyObject.GetInterface(IMyInterface, MyInterface) then
raise Exception.Create('Note to self: Typo in the code');
QueryPerformanceCounter(v1);
// APPROACH 1: NO INTERFACE (FAST!)
// for i := 0 to high(MyObject.FArr) do
// if (MyObject.FArr[i].Val1 < MyObject.FArr[i].Val2) or
// (MyObject.FArr[i].Val3 < MyObject.FArr[i].Val4) then
// Tag := MyObject.FArr[i].Val1 + MyObject.FArr[i].Val2 - MyObject.FArr[i].Val3
// + MyObject.FArr[i].Val4;
// END OF APPROACH 1
// APPROACH 2: WITH INTERFACE (SLOW!)
for i := 0 to high(MyInterface.Arr) do
if (MyInterface.Arr[i].Val1 < MyInterface.Arr[i].Val2) or
(MyInterface.Arr[i].Val3 < MyInterface.Arr[i].Val4) then
Tag := MyInterface.Arr[i].Val1 + MyInterface.Arr[i].Val2 - MyInterface.Arr[i].Val3
+ MyInterface.Arr[i].Val4;
// END OF APPROACH 2
QueryPerformanceCounter(v2);
QueryPerformanceFrequency(f);
ShowMessage(FloatToStr((v2-v1) / f));
finally
MyInterface := nil;
MyObject.Free;
end;
end;
{ TMyObject }
function TMyObject.GetArray: TArrayOfRecord;
begin
result := FArr;
end;
procedure TMyObject.InitArr;
var
i: Integer;
begin
SetLength(FArr, N);
for i := 0 to N - 1 do
with FArr[i] do
begin
Val1 := Random(high(integer));
Val2 := Random(high(integer));
Val3 := Random(high(integer));
Val4 := Random(high(integer));
end;
end;
end.
When I read the data directly, I get times like 0.14 seconds. But when I go through the interface, it takes 1.06 seconds.
Is there no way to achieve the same performance as before with this new design?
I should mention that I tried to set PArrayOfRecord = ^TArrayOfRecord and redefined IMyInterface.arr: PArrayOfRecord and wrote Arr^ etc in the for loop. This helped a lot; I then got 0.22 seconds. But it is still not good enough. And what makes it so slow to begin with?
Simply assign the array to a local variable before iterating through the elements.
What you're seeing is that the interface methods calls are virtual and have to be called through an indirection. Also, the code has to pass-through a "thunk" that fixes up the "Self" reference to now point to the object instance and not the interface instance.
By making only one virtual method call to get the dynamic array, you can eliminate that overhead from the loop. Now your loop can go through the array items without the extra overhead of the virtual interface method calls.
You're comparing oranges with apples, as the first test reads a field (FArr), while the second test reads a property (Arr) that has a getter assigned with it. Alas, interfaces offer no direct access to their fields, so you really can't do it any other way than like you did.
But as Allen said, this causes a call to the getter method (GetArray), which is classified as 'virtual' without you even writing that because it's part of an interface.
Thus, every access results in a VMT-lookup (indirected via the interface) and a method call.
Also, the fact that you're using a dynamic array means that both the caller and the callee will do a lot of reference-counting (you can see this if you take a look at the generated assembly code).
All this is already enough reasons to explain the measured speed difference, but can indeed easily be overcome using a local variable and read the array only once. When you do that, the call to the getter (and all the ensueing reference counting) is taking place only once. Compared to the rest of the test, this 'overhead' becomes unmeasurable.
But note, that once you go this route, you'll loose encapsulation and any change to the contents of the array will NOT reflect back into the interface, as arrays have copy-on-write behaviour. Just a warning.
Patrick and Allen's answers are both perfectly correct.
However, since your question talks about improved OO design, I feel a particular change in your design that would also improve performance is appropriate to discuss.
Your code to set the Tag is "very controlling". What I mean by this is that you're spending a lot of time "poking around inside another object" (via an interface) in order to calculate your Tag value. This is actually what exposed the "performance problem with interfaces".
Yes, you can simply deference the interface once to a local variable, and get a massive improvement in performance, but you'll still be poking around inside another object. One of the important goals in OO design is to not poke around where you don't belong. This actually violates the Law of Demeter.
Consider the following change which empowers the interface to do more work.
IMyInterface = interface
['{C0070757-2376-4A5B-AA4D-CA7EB058501A}']
function GetArray: TArrayOfRecord;
function GetTagValue: Integer; //<-- Add and implement this
property Arr: TArrayOfRecord read GetArray;
end;
function TMyObject.GetTagValue: Integer;
var
I: Integer;
begin
for i := 0 to High(FArr) do
if (FArr[i].Val1 < FArr[i].Val2) or
(FArr[i].Val3 < FArr[i].Val4) then
begin
Result := FArr[i].Val1 + FArr[i].Val2 -
FArr[i].Val3 + FArr[i].Val4;
end;
end;
Then inside TForm3.FormCreate, //APPROACH 3 becomes:
Tag := MyInterface.GetTagValue;
This will be as fast as Allen's suggestion, and will be a better design.
Yes, I'm fully aware you simply whipped up a quick example to illustrate the performance overhead of repeatedly looking something up via interface. But the point is that if you have code performing sub-optimally because of excessive accesses via interfaces - then you have a code smell that suggests you should consider moving the responsibility for certain work into a different class. In your example TForm3 was highly inappropriate considering everything required for the calculation belonged to TMyObject.
your design use huge memory. Optimize your interface.
IMyInterface = interface
['{C0070757-2376-4A5B-AA4D-CA7EB058501A}']
function GetCount:Integer:
function GetRecord(const Index:Integer):TRecord;
property Record[Index:Integer]:TRecord read GetRecord;
end;

Component disabling and enabling at runtime in Delphi 2K9. Weird problem

Here is code:
procedure DisableContrlOL(const cArray : array of string; ReEnable : boolean = False);
// can be called from VKP / RAW / Generation clicks
var
AComponent: TComponent;
CompListDis, CompListEna : TStringList;
begin
CompListDis := TStringList.Create;
CompListEna := TStringList.Create;
for i := Low(cArray) to High(cArray) do begin
AComponent := FindComponent(cArray[i]);
if Assigned(AComponent) then
if (AComponent is TControl) then begin
if TControl(AComponent).Enabled then
CompListEna.Add(TControl(AComponent).Name)
else
CompListDis.Add(TControl(AComponent).Name);
ShowMessage(TControl(AComponent).Name);
if ReEnable then begin // if reenabling needed, then all whi
if not TControl(AComponent).Enabled then
TControl(AComponent).Enabled := True;
end else if (TControl(AComponent).Enabled) then
TControl(AComponent).Enabled := False;
end;
end;
end;
I think no more explanations are needed.
The ShowMessage correctly shows name of each component, but nothing is added in StringLists. Why?
UPDATE: As question has gone pretty wild, I did confirm answer, which a bit helped me.
I understand that I did write things pretty unclear, but I am very limited, because these code lines is part of commercial project, and my hobby and heart thing. The main problem was found already 6h ago, but Rob just wanted to extend this whole question :D No, no offense, mate, it's OK. I am happy to receive so willing and helpful posts. Thanks again.
How do you know that nothing is added to the lists? You create them in this code and the only references to them are in local variables. The objects are leaked when this function returns, so you never actually use the lists anywhere.
You've said you have code for "modular testing." Since that code isn't here, I must assume the code is not part of this function. But if you have external code that's supposed to check the contents of the lists, then the lists can't be just local variables. No other code can access them. You need to either return those lists or accept lists from outside that you then fill. Here's an example of the latter:
procedure DisableContrlOL(const cArray: array of string;
Reenable: Boolean
CompListDis, CompListEna: TStrings);
// can be called from VKP / RAW / Generation clicks
var
AComponent: TComponent;
AControl: TControl;
i: Integer;
begin
for i := Low(cArray) to High(cArray) do begin
AComponent := FindComponent(cArray[i]);
if not Assigned(AComponent) or not (AComponent is TControl) then
continue;
AControl := TControl(AComponent);
if AControl.Enabled then
CompListEna.Add(AControl.Name)
else
CompListDis.Add(AControl.Name);
ShowMessage(AControl.Name);
AControl.Enabled := Reenable;
end;
end;
The caller of this function will need to provide a TStrings descendant for each list. They could be TStringList, or they could be other descendants, such as TMemo.Lines, so you can directly observe their contents in your program. (They can't be just TStrings, though, since that's an abstract class.)
As you can see, I made some other changes to your code. All your code using the Reenable parameter can be simplified to a single statement. That's because enabling a control that's already enabled, and disabling a control that's already disabled, are no-ops.
Also, Name is a public property of TComponent. You don't need to type-cast to TControl before reading that property, but since you're type-casting so often elsewhere, it made sense to introduce a new variable to hold the type-casted TControl value, and that can make your code easier to read. Easier-to-read code is easier-to-understand code, and that makes it easier to debug.
Emphasizing that this is largely based on Rob's excellent suggestions, it looks as though you could simplify the code to:
procedure DisableContrlOL(const cArray : array of string;
ReEnable : boolean = False);
var
AComponent: TComponent;
begin
for i := Low(cArray) to High(cArray) do
begin
AComponent := FindComponent(cArray[i]);
if Assigned(AComponent) then
if (AComponent is TControl) then
begin
ShowMessage(TControl(AComponent).Name);
TControl(AComponent).Enabled := ReEnable;
end;
end;
end;
Not clear what the stringlists were for, since their contents were lost when execution left the scope of this procedure. If you want to return them, you should create and free them in the calling code.
That sure looks like it ought to work. This is the sort of thing that the debugger can probably help with more than we can here.
Try breaking the problematic line down into multiple lines, like so:
if TControl(AComponent).Enabled then
CompListEna.Add(TControl(AComponent).Name)
else CompListDis.Add(TControl(AComponent).Name);
Rebuild with the "Use Debug DCUs" option on, and place a breakpoint on the if statement. Then use F7 to trace your way through the logic and see what's going on.

Which syntax is better for return value?

I've been doing a massive code review and one pattern I notice all over the place is this:
public bool MethodName()
{
bool returnValue = false;
if (expression)
{
// do something
returnValue = MethodCall();
}
else
{
// do something else
returnValue = Expression;
}
return returnValue;
}
This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct?
I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.
A lot of people recommend having only one exit point from your methods. The pattern you describe above follows that recommendation.
The main gist of that recommendation is that if ou have to cleanup some memory or state before returning from the method, it's better to have that code in one place only. having multiple exit points leads to either duplication of cleanup code or potential problems due to missing cleanup code at one or more of the exit points.
Of course, if your method is couple of lines long, or doesn't need any cleanup, you could have multiple returns.
I would have used ternary, to reduce control structures...
return expression ? MethodCall() : Expression;
I suspect I will be in the minority but I like the style presented in the example. It is easy to add a log statement and set a breakpoint, IMO. Plus, when used in a consistent way, it seems easier to "pattern match" than having multiple returns.
I'm not sure there is a "correct" answer on this, however.
Some learning institutes and books advocate the single return practice.
Whether it's better or not is subjective.
That looks like a part of a bad OOP design. Perhaps it should be refactored on the higher level than inside of a single method.
Otherwise, I prefer using a ternary operator, like this:
return expression ? MethodCall() : Expression;
It is shorter and more readable.
Return from a method right away in any of these situations:
You've found a boundary condition and need to return a unique or sentinel value: if (node.next = null) return NO_VALUE_FOUND;
A required value/state is false, so the rest of the method does not apply (aka a guard clause). E.g.: if (listeners == null) return null;
The method's purpose is to find and return a specific value, e.g.: if (nodes[i].value == searchValue) return i;
You're in a clause which returns a unique value from the method not used elsewhere in the method: if (userNameFromDb.equals(SUPER_USER)) return getSuperUserAccount();
Otherwise, it is useful to have only one return statement so that it's easier to add debug logging, resource cleanup and follow the logic. I try to handle all the above 4 cases first, if they apply, then declare a variable named result(s) as late as possible and assign values to that as needed.
They both accomplish the same task. Some say that a method should only have one entry and one exit point.
I use this, too. The idea is that resources can be freed in the normal flow of the program. If you jump out of a method at 20 different places, and you need to call cleanUp() before, you'll have to add yet another cleanup method 20 times (or refactor everything)
I guess that the coder has taken the design of defining an object toReturn at the top of the method (e.g., List<Foo> toReturn = new ArrayList<Foo>();) and then populating it during the method call, and somehow decided to apply it to a boolean return type, which is odd.
Could also be a side effect of a coding standard that states that you can't return in the middle of a method body, only at the end.
Even if no code is executed after the return value is assigned now it does not mean that some code will not have to be added later.
It's not the smallest piece of code which could be used but it is very refactoring-friendly.
Delphi forces this pattern by automatically creating a variable called "Result" which will be of the function's return type. Whatever "Result" is when the function exits, is your return value. So there's no "return" keyword at all.
function MethodName : boolean;
begin
Result := False;
if Expression then begin
//do something
Result := MethodCall;
end
else begin
//do something else
Result := Expression;
end;
//possibly more code
end;
The pattern used is verbose - but it's also easier to debug if you want to know the return value without opening the Registers window and checking EAX.

Resources